Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

r - reduce space between grid.arrange plots

I asked a question HERE about grid arrange and got a terrific response. I want to reduce the space between plots now but get an error. First I present the code that works and then the error code (what I tried). I can't actually find grid.arrange and have always assumed it comes from gridExtra but I may be incorrect.

so 2 parts:

  1. How can I reduce space between plots with grid arrange
  2. Where can I find documentation about grid.arrange (Baptiste I know you maintain gridExtra so please correct my thinking or use of the package if I'm not using it in the way it was intended.)

Good code bad space

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("")
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

Bad code (my try)

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("") + theme(plot.margin= unit(1, "cm"))
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

The error:

Error in `[.unit`(theme$plot.margin, 2) : 
  Index out of bounds (unit subsetting)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was misunderstanding ggplot:

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("") + theme(plot.margin= unit(c(1, 1, -1, 1), "lines"))
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() + 
    theme(plot.margin= unit(rep(.5, 4), "lines"))


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...