Reputation: 21
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.
Upvotes: 0
Views: 7809
Reputation: 705
This page has several basic examples of multiple data sources represented on one plot. Here is one similar to your example drawing:
Upvotes: 0
Reputation: 59345
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)
Upvotes: 2