Show multiple histogram using facet_wrap

2019-08-19 04:18发布

问题:

Sample data

df <- data.frame(id = rep(1:6, each = 50), x = rnorm(50*6, mean = 10, sd = 5), 
                                       y = rnorm(50*6, mean = 20, sd = 10), 
                                       z = rnorm(50*6, mean = 30, sd = 15))

ggplot(df, aes(x)) + geom_histogram() + facet_wrap(~id)

How do I show x, y, z in the same plot for each id in different colours

回答1:

It's best to reshape data from wide to long first, and then add a fill aesthetic to map what (i.e. x, y, z) to different fill colours:

library(tidyverse)
df %>%
    gather(what, val, -id) %>%
    ggplot(aes(val, fill = what)) + geom_histogram() + facet_wrap(~id)