在ggplot2中更改轴文本的字体大小和方向

Anj*_*jan 168 r ggplot2

我正在绘制一个图表,其中x轴为分类变量,y轴为数值变量.

对于x轴,假设有许多数据点,则默认文本格式会使每个刻度线的标签与其他标签重叠.我如何(a)更改轴文本的字体大小和(b)更改文本的方向,使文本垂直于轴?

Dre*_*een 260

用途theme():

d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
    theme(text = element_text(size=20),
        axis.text.x = element_text(angle=90, hjust=1)) 
#vjust adjust the vertical justification of the labels, which is often useful
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有许多关于如何格式化ggplots良好的信息在这里.您可以看到可以修改的参数的完整列表(基本上,所有参数)?theme.

  • 我认为它应该是`hjust = 1`. (2认同)

met*_*oia 63

同上@Drew Steen的使用theme().以下是轴文本和标题的常用主题属性.

ggplot(mtcars, aes(x = factor(cyl), y = mpg))+
  geom_point()+
  theme(axis.text.x = element_text(color = "grey20", size = 20, angle = 90, hjust = .5, vjust = .5, face = "plain"),
        axis.text.y = element_text(color = "grey20", size = 12, angle = 0, hjust = 1, vjust = 0, face = "plain"),  
        axis.title.x = element_text(color = "grey20", size = 12, angle = 0, hjust = .5, vjust = 0, face = "plain"),
        axis.title.y = element_text(color = "grey20", size = 12, angle = 90, hjust = .5, vjust = .5, face = "plain"))
Run Code Online (Sandbox Code Playgroud)


Meg*_*ron 16

添加到以前的解决方案,您还可以使用该函数指定对于base_size主题中包含的字体大小,例如theme_bw()(where base_sizeis 11)rel().

例如:

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(0.5), angle=90))
Run Code Online (Sandbox Code Playgroud)


med*_*igo 15

使用theme():

d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))
Run Code Online (Sandbox Code Playgroud)


JJ *_*ica 7

在制作很多图时,全局设置是有意义的(相关部分是第二行,三行一起是一个工作示例):

   library('ggplot2')
   theme_update(text = element_text(size=20))
   ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()
Run Code Online (Sandbox Code Playgroud)


HBa*_*Bat 7

处理重叠标签的另一种方法是使用guide = guide_axis(n.dodge = 2).

library(dplyr)
library(tibble)
library(ggplot2)

dt <- mtcars %>% rownames_to_column("name") %>% 
  dplyr::filter(cyl == 4)

# Overlapping labels
ggplot(dt, aes(x = name, y = mpg)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述