Reputation: 586
This question is for an extension of the answer to the question posed here: Median and quartile on violin plots in ggplot2.
The solution works beautifully, but how would it be extended to also take the position of the violin plots into account when using options such as fill='foo'
Example:
require(ggplot2)
median.quartile <- function(x){
out <- quantile(x, probs = c(0.25,0.5,0.75))
names(out) <- c("ymin","y","ymax")
return(out)
}
ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+
geom_violin() +
stat_summary(fun.y=median.quartile,geom='point')
Here the summary statistics get mixed because it does not take displacement due to fill asteric mapping into account.
Can this be fixed?
In advance - Thanks!
Upvotes: 3
Views: 2981
Reputation: 98459
You should add position = position_dodge(width = 0.9)
to stat_summary()
to ensure that points are dodged according to fill values.
ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+
geom_violin() +
stat_summary(fun.y=median.quartile,geom='point',
position = position_dodge(width = 0.9))
Upvotes: 5