ggplot2:如何选择因子水平的子集以分组为一个方面 [英] ggplot2: How do you select a subset of factor levels to be grouped into a single facet

查看:80
本文介绍了ggplot2:如何选择因子水平的子集以分组为一个方面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个变量的一个水平与所有其他变量的综合影响进行比较.我想用多方面的图来做到这一点.

I want to compare one level of a variable against the combined influence of all other variables. I would like to do this with a facet plot.

例如:

ggplot(diamonds, aes(price, colour = cut)) + geom_density() + facet_grid(~clarity)

这清楚地提供了所有因子水平的多面图.但是,我想拥有的是第一方面的I1密度图和第二方面的〜(I1)密度图.

This provides a faceted plot of all the factor levels in clarity. However, what I would like to have is a density plot of I1 in the first facet and a density plot of ~(I1) in the second facet.

所以我想使用ggplot2的facet功能对以下内容进行比较:

So I would like to produce a comparison of the following using the facet feature of ggplot2:

ggplot(subset(diamonds, (clarity == "I1")) , aes(price, colour = cut)) + geom_density()

ggplot(subset(diamonds, !(clarity == "I1")) , aes(price, colour = cut)) + geom_density()

我可以看到如何在数据框中定义一个新列并将其用作facet_grid中的因子,但是我怀疑有更好的方法来做到这一点.

I can see how I could define a new column in the dataframe and use that as the factor in facet_grid, but I suspect there are much better ways to do this.

推荐答案

您可以创建一个新列(更好的解决方案)或使用 gridExtra 包:

You can create a new column(better solution) or use gridExtra package:

library(gridExtra)
p1 <- ggplot(subset(diamonds, (clarity == "I1")) , aes(price, colour = cut)) + geom_density()
p2 <- ggplot(subset(diamonds, !(clarity == "I1")) , aes(price, colour = cut)) + geom_density()
grid.arrange(p1,p2)

这篇关于ggplot2:如何选择因子水平的子集以分组为一个方面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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