在使用ggplot绘制多面板图时,无法对图像进行标记。

9

很抱歉可能会问一些简单的问题。我是一名程序员,虽然我很少处理图形,但在为这个问题苦恼了数小时后,现在是时候寻求一些帮助了。我正在使用ggplot在R中创建一个多面板图,但是我无法找到一种方法来显示图标题,除了使用ggplot之外。

以下是我想让我的代码实现的内容:

par(mfrow = c(1, 2), pty = "s", las = 1, mgp = c(2, 0.4, 0), tcl = -0.3)
qqnorm(rnorm(100), main = "")
mtext("a", side = 3, line = 1, adj = 0, cex = 1.1)
qqnorm(rnorm(100), main = "")
mtext("b", side = 3, line = 1, adj = 0, cex = 1.1)

如何将上述代码生成的图中的"a"和"b"标签,放到以下代码相应的位置?

df = data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
p = ggplot(df) + geom_point(aes(x = gp, y = y))
p2 = ggplot(df) + geom_point(aes(x = y, y = gp))
grid.arrange(p, p2, ncol = 2)

提前感谢您的帮助!

2个回答

16

你可以使用ggtitletheme

df = data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
p = ggplot(df) + geom_point(aes(x = gp, y = y)) + ggtitle('a') + theme(plot.title=element_text(hjust=0))
p2 = ggplot(df) + geom_point(aes(x = y, y = gp)) + ggtitle('b') + theme(plot.title=element_text(hjust=0))
grid.arrange(p, p2, ncol = 2)

在此输入图片描述


这比我的分面想法更好。 - joran
@user2221184,没问题。请记得点击答案旁边的勾号接受答案。 - Matthew Plourde

3

两个(不太理想的)选项:

#Use faceting, similar to Matthew's ggtitle option
df = data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
df$lab1 <- 'a'
df$lab2 <- 'b'
p = ggplot(df) + geom_point(aes(x = gp, y = y)) + facet_wrap(~lab1)
p2 = ggplot(df) + geom_point(aes(x = y, y = gp)) + facet_wrap(~lab2)
j <- theme(strip.text = element_text(hjust = 0.05))
grid.arrange(p + j, p2 + j, ncol = 2)


#Use grid.text
grid.text(letters[1:2],x = c(0.09,0.59),y = 0.99)

对于grid.text选项,如果您深入研究ggplot对象,可能可以避免手动调整这些值来获得正确的结果。


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