Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale density plots (for several variables) in ggplot having melted data

Tags:

plot

r

ggplot2

I have a melted data set which also includes data generated from normal distribution. I want to plot empirical density function of my data against normal distribution but the scales of the two produced density plots are different. I could find this post for two separate data sets:

Normalising the x scales of overlaying density plots in ggplot

but I couldn't figure out how to apply it to melted data. Suppose I have a data frame like this:

df<-data.frame(type=rep(c('A','B'),each=100),x=rnorm(200,1,2)/10,y=rnorm(200))
df.m<-melt(df)

using the code below:

qplot(value,data=df.m,col=variable,geom='density',facets=~type)

produces this graph: enter image description here

How can I make the two densities comparable given the fact that normal distribution is the reference plot? (I prefer to use qplot instead of ggplot)

UPDATE: I want to produce something like this (i.e. in terms of plot-comparison) but with ggplot2:

plot(density(rnorm(200,1,2)/10),col='red',main=NA) #my data
par(new=T)
plot(density(rnorm(200)),axes=F,main=NA,xlab=NA,ylab=NA) # reference data

which generates this: enter image description here

like image 955
Amin Avatar asked Jan 18 '14 02:01

Amin


1 Answers

Is this what you had in mind?

enter image description here

There's a built-in variable, ..scaled.. that does this automatically.

set.seed(1)
df<-data.frame(type=rep(c('A','B'),each=100),x=rnorm(200,1,2)/10,y=rnorm(200))
df.m<-melt(df)
ggplot(df.m) + 
  stat_density(aes(x=value, y=..scaled..,color=variable), position="dodge", geom="line")
like image 96
jlhoward Avatar answered Sep 21 '22 05:09

jlhoward