Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple plots with multiple densities in ggplot2

Tags:

r

ggplot2

I am trying to get several plots on a graph sharing a common legend using facet_wrap(). The plots contain 4 density estimate each constructed using geom_density(). This is a minimal example of what the data look like. One density is estimated for each level of estimator, and a different plot is drawn for each value of xp.

    > esti
    estimator      value           xp
1      OLS Oracle 0.35757317 N= 10 T= 100
2      OLS Oracle 0.50540655 N= 10 T= 100
3        OLS Full 0.02276872 N= 10 T= 100
4        OLS Full 0.53616020 N= 10 T= 100
5           Lasso 0.00000000 N= 10 T= 100
6           Lasso 0.30448578 N= 10 T= 100
7  Adaptive Lasso 0.00000000 N= 10 T= 100
8  Adaptive Lasso 0.49949267 N= 10 T= 100
9      OLS Oracle 0.48392914 N= 10 T= 500
10     OLS Oracle 0.53685915 N= 10 T= 500
11       OLS Full 0.50565482 N= 10 T= 500
12       OLS Full 0.61407003 N= 10 T= 500
13          Lasso 0.38342782 N= 10 T= 500
14          Lasso 0.52012928 N= 10 T= 500
15 Adaptive Lasso 0.47951875 N= 10 T= 500
16 Adaptive Lasso 0.53222172 N= 10 T= 500

I can construct one plot with the four densities:

library('ggplot2')
ggplot(data=esti,aes(x=value,colour=estimator)) + geom_density()

Or two panels with one density in each:

ggplot(data=esti,aes(x=value)) + geom_density() +facet_wrap(~xp,scales='free_y')

However the two together doesn't work and result in an error:

> ggplot(data=esti,aes(x=value,colour=estimator)) + geom_density() +facet_wrap(~xp,scales='free_y')
Error in UseMethod("scale_dimension") : 
  no applicable method for 'scale_dimension' applied to an object of class "NULL"

I have tried different values for scales, or omitting it altogether, with no luck. I have tried to track which object was being applied to 'scale_dimension', with no luck either. Can anyone enlighten me?

like image 530
Pepin_the_sleepy Avatar asked May 25 '12 09:05

Pepin_the_sleepy


1 Answers

Since I cannot leave a comment in order to second joran's suggestion (i.e., I do not have enough reputation), here an answer:

By going from

 ggplot(data=esti,aes(x=value,colour=estimator)) + geom_density()

to

 ggplot(data=esti,aes(x=value,colour=estimator))
 + geom_density() +facet_wrap(~xp,scales='free_y')

only 2 data points are left for each estimator/xp pair. As it seems, this is not enough to compute the densities. For instance, the following line of code works (note data=rbind(esti,esti))

ggplot(data=rbind(esti,esti),aes(x=value,colour=estimator))
+ geom_density() +facet_wrap(~xp,scales='free_y')

Also, if you replace geom_density by geom_bar, it works

ggplot(data=esti,aes(x=value,colour=estimator))
+ geom_bar() +facet_wrap(~xp,scales='free_y')
like image 126
cryo111 Avatar answered Oct 27 '22 01:10

cryo111