How do I create a graph that shows histogram/density plot for a variable on two levels? i.e. variable X (categorical) is plotted stratified by variable y (staff vs. mgmt) and further stratified by variable z (high score vs. low score). I should end up with 4 histograms.
Asked
Active
Viewed 7,118 times
0
-
1Why you might have gotten a downvote. There is a strong preference for questions that have data-objects created by code or as the output from `dput`. You might also mention what search strategies you used and why they didn't produce anything useful. Seems like a fairly basic request. – IRTFM Nov 17 '14 at 22:54
2 Answers
2
In future you should include your data, or at least a representative example. See this post for instructions on how to do that.
# sample data...
set.seed(1) # for reproducible example
df <- data.frame(x=rnorm(1000,mean=rep(c(0,3,6,9),each=250)),
y=rep(c("Staff","Mgt"),each=500),
z=rep(c("High","Low"),each=250))
# base R solution
par(mfrow=c(2,2),mar=c(3,4,1,1))
lapply(split(df,list(df$y,df$z)),
function(d)hist(d$x,main=paste(unique(d$y),unique(d$z),sep=".")))
# ggplot solution (one of many possibilities)
library(ggplot2)
ggplot(df) +
geom_histogram(aes(x=x,fill=interaction(z,y)),color="grey70")+
facet_grid(z~y)
0
This page has several basic examples of multiple data sources represented on one plot. Here is one similar to your example drawing:

Michael Treanor
- 585
- 8
- 9