r - Adjust space between gridded, same-sized ggplot2 figures -


i attempting arrange multiple ggplot2 plots 1 output/grid. i'd plots (without considering labels) same size. have found way this, i'd adjust space between plots.

for example: example plots default spacing

in plot, i'd reduce amount of space between 2 plots. i've tried adjusting margins, removing ticks, etc. has removed of space.

example plots reduced space between plots

is there way have more control of spacing adjustment between plots in situations such these?

library(mass) data(iris) library(ggplot2) library(grid) library(gridextra)  p1 <- ggplot(iris,aes(species,sepal.width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) +coord_flip() +   theme(axis.title.y = element_blank()) + ylab("sepal width")  p2 <- ggplot(iris,aes(species,petal.width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) + coord_flip() +   theme(axis.title.y = element_blank(), axis.text.y=element_blank()) + ylab("petal width")   p11 <- p1 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm")) p22 <- p2 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm"),  axis.ticks.y=element_blank())   # https://stackoverflow.com/questions/24709307/keep-all-plot-components-same-size-in-ggplot2-between-two-plots # make plots same size, different labels gl <- lapply(list(p11,p22), ggplotgrob) widths <- do.call(unit.pmax, lapply(gl, "[[", "widths")) heights <- do.call(unit.pmax, lapply(gl, "[[", "heights")) lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g})  # https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2-in-r?lq=1 grid.arrange(lg[[1]],lg[[2]], ncol=2) #in gridextra 

you have set 'widths' maximums of 2 plots. means widths y-axis of 'petal widths' plot same widths of y-axis of 'sepal widths' plot.

one way adjust spacing is, first, combine 2 grobs 1 layout, deleting y-axis , left margin of second plot:

# code, using p1 , p2, not plots adjusted margins gl <- lapply(list(p1, p2), ggplotgrob) widths <- do.call(unit.pmax, lapply(gl, "[[", "widths")) heights <- do.call(unit.pmax, lapply(gl, "[[", "heights")) lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g})  # new code library(gtable) gt = cbind(lg[[1]], lg[[2]][, -(1:3)], size = "first") 

then width of remaining space between 2 plots can adjusted:

gt$widths[5] = unit(2, "lines")  # draw plot grid.newpage() grid.draw(gt) 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -