ggplot2:有没有一种方法可以将单个绘图覆盖到ggplot中的所有刻面 [英] ggplot2: Is there a way to overlay a single plot to all facets in a ggplot

查看:442
本文介绍了ggplot2:有没有一种方法可以将单个绘图覆盖到ggplot中的所有刻面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot和faceting来构建一系列按因子分组的密度图。另外,我希望在每个面上都有一层不受该面强加的约束的另一个密度图。

I would like to use ggplot and faceting to construct a series of density plots grouped by a factor. Additionally, I would like to a layer another density plot on each of the facets that is not subject to the constraints imposed by the facet.

例如,分面图如下:

For example, the faceted plot would look like this:

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

然后我希望在每个方面都有以下单一密度图:

and then I would like to have the following single density plot layered on top of each of the facets:

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

此外,ggplot有faceting做到这一点的最佳方式,还是有一个首选的方法?

Furthermore, is ggplot with faceting the best way to do this, or is there a preferred method?

推荐答案

实现这一目标的一种方法是创建新的数据框 diamonds2 ,它只包含 price 然后两个 geom_density()调用 - 一个将使用原始钻石,第二个使用 diamonds2 。在 diamonds2 中,不会有任何列清晰所有值都将用于所有方面。

One way to achieve this would be to make new data frame diamonds2 that contains just column price and then two geom_density() calls - one which will use original diamonds and second that uses diamonds2. As in diamonds2 there will be no column clarity all values will be used in all facets.

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

UPDATE - 正如@BrianDiggs所建议的那样,如果不创建新的数据框,但可以在 geom_density()内转换它,可以实现相同的结果。

UPDATE - as suggested by @BrianDiggs the same result can be achieved without making new data frame but transforming it inside the 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)中使用不同颜色的密度线对于清晰度的每个级别,并留下空的第二个 geom_density() - 这将添加整个黑色密度线。

Another approach would be to plot data without faceting. Add two calls to geom_density() - in one add aes(color=clarity) to have density lines in different colors for each level of clarity and leave empty second geom_density() - that will add overall black density line.

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

这篇关于ggplot2:有没有一种方法可以将单个绘图覆盖到ggplot中的所有刻面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆