grid.arrange中的错误 - arrangeGrob()函数

5

我有两个图表p1和p2,我想使用grid.arrange绘制它们。我的代码如下:

grid.arrange(p1, p2, ncol=2,
    top = textGrob("Distribution across each day of the week", 
    gp = gpar(fontface = "bold", cex = 1.5)),
    bottom = "Day of the week")

然而,当我运行它时,出现错误"Error in arrangeGrob(...) : could not find function "textGrob"
当我只运行grid.arrange(p1, p2, ncol=2)时,它能够成功运行,但是没有标签和标题。然而,我不明白我的代码出了什么问题。我尝试了 main=...top=... 但都没有起作用。
有什么建议吗?

1
如果您添加 library(grid),您的代码将正常工作 - textGrob 是该软件包中的一个函数。例如,使用您的代码:`library(gridExtra); library(grid) ;grid.arrange(rectGrob(), top = textGrob("Distribution across each day of the week", gp = gpar(fontface = "bold", cex = 1.5)), bottom="Day of the week")` - user20650
1
谢谢,问题已经解决了。感谢你和@lawyeR的帮助! - greenhorntechie
由于遗漏库调用,投票关闭为打字错误。 - user20650
1个回答

2

这里有两个简单的png文件。

value <- c(0, 1, 20, 3, 3, 0, 0, 5, 2, 5, 2, 7)
names.arg =c("0-15","15-19","20-24","25-29","30-34",
             "35-39","40-44","45- 49","50-54","55-59","60-64","65 Jahre oder Älter")
df <- data.frame(names.arg = names.arg, value = value)

p1 <- ggplot(df, aes(x=names.arg, y=value)) + geom_bar(stat = "identity")
save(p1, file = "p1.png")

value2 <- c(0, 1, 20, 3, 3, 0, 0, 5, 2, 5, 2, 7)
names2 =c("0-15","15-19","20-24","25-29","30-34",
             "35-39","40-44","45- 49","50-54","55-59","60-64","65 Jahre oder Älter")
df2 <- data.frame(names = names2, value = value2)

p2 <- ggplot(df2, aes(x=names, y=value)) + geom_bar(stat = "identity", fill = "red")
save(p2, file = "p2.png")

当你结合使用 top =bottom = 参数时,它们可以正常工作:

grid.arrange(p1, p2, ncol=1, top = "Example", bottom = "Sample")

这里输入图片描述

根据评论编辑

grid.arrange() 调用之外创建标题:

title <- textGrob("Distribution across each day of the week", gp = gpar(fontface = "bold", cex = 1.5))

并修改调用:

grid.arrange(p1, p2, ncol=1, top = title, bottom = "Sample")

enter image description here


谢谢你的示例。但是,如果我想自定义我的标签 - 顶部和底部,该怎么办?我想textGrob会提供这种灵活性。但它与grid.arrange不兼容。 - greenhorntechie
编辑演示了如何自定义顶部和底部标题。您考虑过接受答案吗(通过点击绿色勾号图标)? - lawyeR
感谢 @lawyeR 的回复。 - greenhorntechie
@lawyeR,我认为你的编辑与原始问题中的代码相同,不是吗?问题是由于需要调用grid库,因此它现在并没有得到真正的解答。 - user20650

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