ggplot2: How do you select a subset of factor levels to be grouped into a single facet

丶灬走出姿态 提交于 2021-02-08 09:13:43

问题


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.

For instance:

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

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.

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

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.


回答1:


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)


来源:https://stackoverflow.com/questions/15901459/ggplot2-how-do-you-select-a-subset-of-factor-levels-to-be-grouped-into-a-single

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!