0

I would like to plot histograms of one variable x1, subdividing the data into 4 by values of another variable x2, and place the 4 histograms in 1 plot area, 2 histograms per row.

For example,

library(tidyverse)

ggplot(filter(mpg, cty < 15), aes(x = displ)) + geom_histogram(binwidth = 0.2)
ggplot(filter(mpg, cty == c(15,16,17,18)), aes(x = displ)) + geom_histogram(binwidth = 0.05)
ggplot(filter(mpg, cty == c(19,20,21,22)), aes(x = displ)) + geom_histogram(binwidth = 0.05)
ggplot(filter(mpg, cty > 23), aes(x = displ)) + geom_histogram(binwidth = 0.1)

Thanks for your help!

P. N.
  • 13
  • 2

1 Answers1

1

You could use ggarrange() from the ggpubr-package:

p1 <- ggplot(filter(mpg, cty < 15), aes(x = displ)) + 
       geom_histogram(binwidth = 0.2)
p2 <- ggplot(filter(mpg, between(cty, 15, 18)), aes(x = displ)) +
       geom_histogram(binwidth = 0.05)
p3 <- ggplot(filter(mpg, between(cty, 19, 22)), aes(x = displ)) +
       geom_histogram(binwidth = 0.05)
p4 <- ggplot(filter(mpg, cty > 23), aes(x = displ)) +
       geom_histogram(binwidth = 0.1)
ggpubr::ggarrange(p1, p2, p3, p4)

enter image description here

As was already mentioned by markus in his comment, filtering with cty == c(15, 16, 17, 18) is returning all the values in mpg where cty lies between 15 and 18. You should use either cty %in% c(15, 16, 17, 18), cty %in% 15:18, or between(cty, 15, 18). The last variant also works for continuous variables.

Community
  • 1
  • 1
Stibu
  • 15,166
  • 6
  • 57
  • 71