如何在ggplot2中调整标题位置

时间:2013-10-27 18:09:11

标签: r ggplot2

以下是代码:

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 个答案:

答案 0 :(得分:27)

您要找的是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))

enter image description here