Median and quartile on advanced violin plots in ggplot2

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')

Violin plot with summary

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

Answers (1)

Didzis Elferts
Didzis Elferts

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))

enter image description here

Upvotes: 5

Related Questions