Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in grid.arrange - arrangeGrob() function

Tags:

r

ggplot2

I have two plots p1 and p2 which I am trying to plot using grid.arrage. My code looks as below:

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")

However, when I run this, I am seeing an error "Error in arrangeGrob(...) : could not find function "textGrob"

When I run only grid.arrange(p1, p2, ncol=2), it runs fine. But without any labels and title. However, I couldnt understand what is the problem with my code. I tried both main=... and as well as top=... Neither of them works.

Any suggestions?

like image 542
greenhorntechie Avatar asked Oct 31 '22 15:10

greenhorntechie


1 Answers

Here are two simple png files.

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")

When you combine them, the top = and bottom = arguments work fine:

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

enter image description here

EDIT BASED ON COMMENT

Create the title outside of the grid.arrange() call:

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

and revise the call:

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

enter image description here

like image 88
lawyeR Avatar answered Nov 15 '22 06:11

lawyeR