1
votes

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
I think that it will be easier to make new column to use in facet_grid()Didzis Elferts

1 Answers

1
votes

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)