如何在ggplot2中调整标题位置

19

这是代码:

require(ggplot2)
require(grid)
# pdf("a.pdf")
png('a.png')
a <- qplot(date, unemploy, data = economics, geom = "line") + opts(title='A')
b <- qplot(uempmed, unemploy, data = economics) + geom_smooth(se = F) + opts(title='B')
c <- qplot(uempmed, unemploy, data = economics, geom="path") + opts(title='C')
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(a, vp = vplayout(1, 1:2))
print(b, vp = vplayout(2, 1))
print(c, vp = vplayout(2, 2))
dev.off()

并且结果:

enter image description here

而我希望拥有这样的效果,即将标题位置放在y轴的顶部附近:

enter image description here

1个回答

28

你需要寻找的是theme(plot.title = element_text(hjust = 0))。例如,如果使用最新版本的ggplot2和theme而不是opts

a <- qplot(date, unemploy, data = economics, geom = "line") + ggtitle("A") +
  theme(plot.title = element_text(hjust = 0))

或者,保留 opts

a <- qplot(date, unemploy, data = economics, geom = "line") + 
  opts(title = "A", plot.title = element_text(hjust = 0))

输入图像描述


1
虽然看起来ggplot2已经有一段时间没有更新了,所以也许应该使用opts而不是theme - Tyler Rinker
@Julius 我该如何调整标题以使其在图表内部?我尝试了 'vjust' 但它与 'hjust' 结合使用时不起作用。我想将标题移动到图表的右上角。 - Meli
1
@Meli,我认为你的问题没有类似的解决方案;你应该考虑将标题作为文本插入到图表中,就像这个链接中的示例:https://dev59.com/PGUp5IYBdhLWcg3w8LF4 - Julius Vainora

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接