Jeremy
Jeremy

Reputation: 2000

Best way to make a bunch of density plots in R

v0=sample(c(T,F),100,T)
df = data.frame(v0=v0, v1=rnorm(100,0,1) + v0*rnorm(100,1,1),v2=rnorm(100,2,1))

How do I make a bunch of plots for each variable (other than v0), where each plot is a density plot like:

ggplot(df, aes(x=v1)) + 
geom_density(aes(group=v0, colour=v0, fill=v0), 
                      bw=.15,
                      alpha=0.3)

Plot of v1

Upvotes: 0

Views: 145

Answers (1)

mtoto
mtoto

Reputation: 24188

You can melt() your data.frame and use facet_wrap():

library(reshape2)
library(ggplot2)
ggplot(melt(df), aes(x=value, bw=.15, colour=v0,fill=v0, alpha=.3)) + 
        geom_density() + facet_wrap(~variable)

enter image description here

Upvotes: 2

Related Questions