jhscheer jhscheer - 3 months ago 18
R Question

How to decrease space from boxplot to edge with ggplot2?

I want to put a

boxplot
beneath a histogram. I already figured out how to do this, but the
boxplot
and the histogram are equally sized and I want to slim down the
boxplot
.
When I decrease the width, the spaces to the edges stay the same. However, I want to decrease the width of the whole thing.

Here is what I have so far:

library(ggplot2)
h = ggplot(mtcars, aes(x=hp)) +
geom_histogram(aes(y = ..density..)) +
scale_x_continuous(breaks=c(100, 200, 300), limits=c(0,400)) +
geom_density(, linetype="dotted")

b <- ggplot(mtcars,aes(x=factor(0),hp))+geom_boxplot(width=0.1) +
coord_flip(ylim=c(0,400)) +
scale_y_continuous(breaks=c(100, 200, 300)) +
theme(axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())

library(gridExtra)
plots <- list(h, b)
grobs <- list()
widths <- list()
for (i in 1:length(plots)){
grobs[[i]] <- ggplotGrob(plots[[i]])
widths[[i]] <- grobs[[i]]$widths[2:5]
}
maxwidth <- do.call(grid::unit.pmax, widths)
for (i in 1:length(grobs)){
grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
do.call("grid.arrange", c(grobs, ncol=1))


hist+boxplot

Edit:

If I use grid.arrange() like so:

grid.arrange(heights=c(4,1), h, b)


enter image description here

The proportions are exactly like I wanted it, but I cannot figure out how to adjust my first example above so that the axes are aligned again.

Anyone?

Answer

You just need to use your width-corrected grobs, not the original plots, in the grid.arrange call.

grid.arrange(heights = c(4, 1), grobs[[1]], grobs[[2]])