Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GGplot2 facet_wrap() histograms given a value of other column

I have a large dataframe data that looks like this

     state    values
1      0       0.25
2      1       0.73
3      1       0.21
4      2       0.95
5      3       0.37
6      0       0.72
7      2       0.81
8      1       0.13
9      1       0.05
10     3       0.46

I would like to use facet_wrap() to create four histograms: each one of them would correspond to values for a given value of state, so i.e. value histogram only for the observations that come from the state == 1. At the same time I want my histograms to have the same x values: min and max of the whole dataset, so that I can compare them easily. The number of observations for each class may vary.

I tried to do that in this fashion, but it’s obviously wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplot(gather(data), aes(value)) + 
  geom_histogram(bins = 6) + 
  facet_wrap(~ values + state, scales = "free_x")

>Solution :

Something like this?

df %>% 
  mutate(state=factor(state)) %>% 
  ggplot(aes(x=values)) + 
  geom_histogram(bins = 6)+
  facet_wrap(.~state)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading