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.
ggplot(gather(data), aes(value)) +
geom_histogram(bins = 6) +
facet_wrap(~ values + state, scales = "free_x")
Solution 1:
Something like this?
df %>%
mutate(state=factor(state)) %>%
ggplot(aes(x=values)) +
geom_histogram(bins = 6)+
facet_wrap(.~state)