Skip to content
Prev 138420 / 398506 Next

ggplot2 - Problem with grid plot

Hi R-help

I'm trying to create a grid plot in which each plot in the grid contains two
density plots (colored by factor) and two vertical lines at the respective
medians (also colored by the factor).

Using the diamonds dataset as an example, the following commands give me
price density plots by factor cut in a single, ungridded plot.

p <- ggplot(data=diamonds, aes(x=price)) + geom_density(aes(color=cut))
p


I can add vertical lines at the medians of each density as follows.

medians <- data.frame(cut=levels(diamonds$cut),
intercept=tapply(diamonds$price, list(diamonds$cut), median))
p + geom_vline(data=medians, aes(color=factor(cut)))



I can create a gridded plot of price density by factors cut and color (where
color is the grid reference) as follows.

p + facet_grid(color~.)


However I've had no luck trying to now add vertical grid lines on each
density plot within each grid. Can anyone offer a suggestion on how to do
this?

Is this a limitation with ggplot2? I'm using ggplot2 0.5.7, R 2.6.2, Windows
XP.