在ggplot2中绘制多个密度图的多个图层

6

我正在尝试使用facet_wrap()将几个共享公共图例的图形绘制在一张图上。这些图包含4个密度估计,每个估计都是使用geom_density()构建的。以下是数据的最简示例。对于每个估计器级别都会估计一个密度,对于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

我可以用四个密度构建一个绘图:
library('ggplot2')
ggplot(data=esti,aes(x=value,colour=estimator)) + geom_density()

或者两个面板,每个面板的密度不同:

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

然而,将两者结合在一起不起作用,并导致错误:
> 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"

我尝试了不同的比例尺值或完全省略它,但都没有成功。我也试图追踪应用于“scale_dimension”的对象,但仍然没有成功。有人可以给我指点吗?


2
只是猜测,可能与您在每个组上仅计算两个值的密度有关?当我使用更大的数据集创建类似的图时,我没有遇到那个错误。 - joran
谢谢您的回复,使用geom_density()时出现了问题。尽管我尝试使用geom_line(stat='density'),但问题仍然存在... - Pepin_the_sleepy
2
但是......问题还是一样的,不是吗?你仍然只在两个值上计算密度。 - joran
这次使用更多的值(100)来计算密度。 - Pepin_the_sleepy
1个回答

2

由于我不能留下评论以支持joran的建议(即,我没有足够的声望),在这里提供一个答案:

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

每个估计器/ xp 对仅剩下 2 个数据点。看起来这不足以计算密度。 例如,以下代码行有效(请注意 data=rbind(esti,esti)

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

此外,如果您将geom_density替换为geom_bar,它也可以正常工作。
ggplot(data=esti,aes(x=value,colour=estimator))
+ geom_bar() +facet_wrap(~xp,scales='free_y')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接