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

时间:2015-11-18 16:35:45

标签: r ggplot2

我有两个图p1和p2,我试图用grid.arrage绘图。我的代码如下所示:

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

答案 0 :(得分: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")

enter image description here

基于评论的编辑

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