Hi:
This works:
library(lattice)
library(latticeExtra) # where the data frame resides
data(gvhd10)
ph <- ggplot(gvhd10, aes(x = log(FSC.H)))
ph + geom_ribbon(aes(ymax = ..density.., ymin = -..density..),
stat = "density") +
facet_grid(Days ~ ., as.table = FALSE, scales = "free_y") +
xlab("log(Forward Scatter)")
You don't want Days as either an x or y aesthetic because you intend to use it as the grouping variable. The log(FSC.H) is the 'x' variable because it plays a role similar to that in geom_density() or geom_histogram() - it provides the domain for the estimated density to be computed. ..density.. is the y-variable. The appearance has to do with the combination of the way that the plot is generated and the formula used for facet_grid(). [Think of a violin as a density plot reflected around its x-axis; this is why log(FSC.H) is the x variable.] To reproduce this structure by groups, Days has to be the 'y' variable in the facet_grid() formula so that each panel has ..density.. as its 'y'.
To do this in the other direction, we have to create a single violin plot as a separate object, using coord_flip() to switch the x and y axis,. We can then partition it by Days using facet_grid() again, except with Days on the RHS (x) this time. A couple of extra code chunks are added/modified to improve its appearance.
# Generate a violin plot and flip the x and y axes
pj <- ggplot(gvhd10, aes(x = log(FSC.H))) +
geom_ribbon(aes(ymax = ..density.., ymin = -..density..),
stat = "density") + coord_flip() +
opts(axis.text.x = theme_text(angle = 90, hjust = 0.5)) +
ylab("log(Forward Scatter)")
# Plot by groups with facet_grid()
pj + facet_grid(. ~ Days, scales = 'free_x' )
Hopefully, you can see the coordination that has to exist between the 'base' violin plot and facet_grid().
HTH,
Dennis