GGPLOT2:是否有覆盖一个情节各方面的ggplot方式(ggplot2: Is there a

2019-08-19 20:27发布

我想用ggplot和小面来构造一系列的因素分组密度地块。 此外,我想的层上每个不受由小面所施加的约束的小面的另一密度图。

例如,多面的情节是这样的:

require(ggplot2)
ggplot(diamonds, aes(price)) + facet_grid(.~clarity) + geom_density()

然后我想有层次上的每个小面的顶部以下单密度图:

ggplot(diamonds, aes(price)) + geom_density()

此外,在ggplot重用神话做到这一点的最好办法,还是有一个首选的方法?

Answer 1:

实现这一目标的一个方法是使新的数据帧diamonds2只包含列price ,然后有两只geom_density()调用-一个将使用原来的diamonds和第二使用diamonds2 。 作为diamonds2不会有列clarity的所有值将在所有方面被使用。

diamonds2<-diamonds["price"]
ggplot(diamonds, aes(price)) + geom_density()+facet_grid(.~clarity) + 
     geom_density(data=diamonds2,aes(price),colour="blue")

UPDATE -通过@BrianDiggs的建议可以在不使新的数据帧,但将其变换的内部来实现相同的结果geom_density()

ggplot(diamonds, aes(price)) + geom_density()+facet_grid(.~clarity) +
     geom_density(data=transform(diamonds, clarity=NULL),aes(price),colour="blue")

另一种方法是不小面绘制数据。 添加两个调用geom_density() -在一个添加aes(color=clarity)有不同颜色的线密度为每个级别clarity和留空第二geom_density() -这将增加整体黑色密度线。

ggplot(diamonds,aes(price))+geom_density(aes(color=clarity))+geom_density()



文章来源: ggplot2: Is there a way to overlay a single plot to all facets in a ggplot
标签: r ggplot2