Multiple Multiple Density Charts in ggplot2

I am trying to get some graphs on a graph using a common legend using facet_wrap (). The graphs contain 4 density estimates, each of which is constructed using geom_density (). This is a minimal example of how the data looks. For each level of assessment, one density is estimated, and for each value of xp another graph is taken.

> 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 build one graph with 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, both do not work together and lead to 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 tried different values ​​for the scales or did not collect them at all, no luck. I tried to keep track of which object applies to 'scale_dimension', and with no luck. Can anyone enlighten me?

+6
source share
1 answer

Since I cannot leave a comment for the second joran sentence (i.e. I do not have enough reputation), here is the answer:

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') 

for each pair of / xp ratings, only 2 data points remain. It seems that this is not enough to calculate the densities. For example, 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 with geom_bar , it works

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

Source: https://habr.com/ru/post/916635/


All Articles