[R] Violin Plot - using ggplot2

JP jeanpaul.ebejer at inhibox.com
Wed Mar 30 11:26:07 CEST 2011


Hi there,

I am trying to create a violin plot with ggplot2 (which looks awesome
by the way).  I am probably not understanding the code correctly by
this is what I am trying (this works if you want to copy and paste it
in R)

library(ggplot2)
p <- rep(c(rep("condition_a", 4), rep("condition_b", 4)), 2)
q <- c(rep("grp_1", 8), rep("grp_2", 8))
r <- sample(1:5, 16, rep = T)
d <- data.frame(p, q, r)
gg1 <- ggplot(d, aes(y=r, x=factor(p)))
gg2 <- gg1 + geom_ribbon(aes(ymax = ..density.., ymin = -..density..),
stat = "density") + facet_grid(q ~ ., as.table = F, scales = "free_y")
+ labs(x = "some x desc", y = "some y desc")
print(gg2)

The result I am getting is posted as an image at
http://awesomescreenshot.com/0e8ae8c52  (I tried to draw what I would
like to achieve.)

What I would like to achieve instead is the equivalent of this using ggplot2

library(lattice)
bwplot( r ~ p | q,
           data=d,
           panel = panel.violin
)

What I want is to draw traditional violin plots grouping them by
grp_1, grp_2 etc (so q above).  For each group I have two conditions
(p above) which I want to plot violin plots for their values. I want
the plots to be vertical (as drawn in red in my image). Any ideas on
how to change the above ggplot2 code to do just that?  I have been
playing with  facet_grid all day... Also the values on the axis are
incorrect ... they should be in the range 1:5 (as r above) and a plot
should show the probability density of that value...

Any help?  I am going mad...

Many Thanks
JP



More information about the R-help mailing list