如何使用hjust和vjust来移动ggplot2中的元素(附实例)

3,829 阅读2分钟

你可以使用hjustvjust参数在ggplot2中分别在水平和垂直方向上移动元素。

下面的例子展示了如何在不同情况下使用hjustvjust

例1:在ggplot2中移动标题位置

下面的代码显示了如何在ggplot2中创建一个标题处于默认位置(左对齐)的散点图:

library(ggplot2)

#create scatter plot with title in default position
ggplot(data=mtcars, aes(x=mpg, y=wt)) +
  geom_point() +
  ggtitle("Plot Title") 

而下面的代码显示了如何通过使用hjust=0.5来使标题居中对齐。

library(ggplot2)

#create scatter plot with title center-aligned
ggplot(data=mtcars, aes(x=mpg, y=wt)) +
  geom_point() +
  ggtitle("Plot Title") +
  theme(plot.title = element_text(hjust=.5))

注意:你也可以使用hjust=1来使标题右对齐。

例2:在ggplot2中移动坐标轴标签位置

下面的代码显示了如何在ggplot2中创建一个条形图,其中的X轴标签被旋转了90度,以使其更容易阅读:

library(ggplot2)

#create data frame
df = data.frame(team=c('The Amazing Amazon Anteaters',
                       'The Rowdy Racing Raccoons',
                       'The Crazy Camping Cobras'),
                points=c(14, 22, 11))

#create bar plot to visualize points scored by each team
ggplot(data=df, aes(x=team, y=points)) +
  geom_bar(stat='identity') +
  theme(axis.text.x = element_text(angle=90)) 

我们可以使用hjustvjust参数来调整x轴标签,使其与x轴上的刻度线更紧密地排列。

library(ggplot2)

#create data frame
df = data.frame(team=c('The Amazing Amazon Anteaters',
                       'The Rowdy Racing Raccoons',
                       'The Crazy Camping Cobras'),
                points=c(14, 22, 11))

#create bar plot to visualize points scored by each team
ggplot(data=df, aes(x=team, y=points)) +
  geom_bar(stat='identity') +
  theme(axis.text.x = element_text(angle=90, vjust=.5, hjust=1) 

例3:在ggplot2中移动文本位置

下面的代码显示了如何在ggplot2中创建一个散点图,并为图中的每个点标注文字。

library(ggplot2)

#create data frame
df <- data.frame(player=c('Brad', 'Ty', 'Spencer', 'Luke', 'Max'),
                 points=c(17, 5, 12, 20, 22),
                 assists=c(4, 3, 7, 7, 5))

#create scatter plot with annotated labels
ggplot(df) +
  geom_point(aes(x=points, y=assists)) + 
  geom_text(aes(x=points, y=assists, label=player)) 

我们可以使用vjust参数将文本元素垂直向上移动,这样它们就更容易阅读。

library(ggplot2)

#create data frame
df <- data.frame(player=c('Brad', 'Ty', 'Spencer', 'Luke', 'Max'),
                 points=c(17, 5, 12, 20, 22),
                 assists=c(4, 3, 7, 7, 5))

#create scatter plot with annotated labels
ggplot(df) +
  geom_point(aes(x=points, y=assists)) + 
  geom_text(aes(x=points, y=assists, label=player), vjust=-.6)

我们也可以用vjust的正值将文本元素垂直向下移动。

library(ggplot2)

#create data frame
df <- data.frame(player=c('Brad', 'Ty', 'Spencer', 'Luke', 'Max'),
                 points=c(17, 5, 12, 20, 22),
                 assists=c(4, 3, 7, 7, 5))

#create scatter plot with annotated labels
ggplot(df) +
  geom_point(aes(x=points, y=assists)) + 
  geom_text(aes(x=points, y=assists, label=player), vjust=1.2)

现在,注释的文本位于图中每个点的下方。

其他资源

下面的教程解释了如何在ggplot2中执行其他常见任务:

如何在ggplot2中改变图例标题
如何在ggplot2中旋转轴标签
如何在R中修复:找不到函数 "ggplot"