问题
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