2

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?

3
  • take a look at: stackoverflow.com/questions/16148076/… Commented Mar 31, 2014 at 0:37
  • Thanks, but that doesn't look like what I'm after. If your're referring to the heights option of grid.arrange, could you please tell me how to adjust my example accordingly. All my tries so far have failed. Commented Mar 31, 2014 at 0:53
  • +1 for such a nicely reproducible question with an almost-there attempt included. Commented Mar 31, 2014 at 1:34

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.