2

Using the iris data:

require(ggplot2)
    ggplot(iris, aes(Species, Sepal.Length)) +
    geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))

We get: enter image description here

How can I keep the straight line for the means but use dashed lines instead for the other two quantiles ?

I have used the very handy function of @jan-glx for my own data here: Split violin plot with ggplot2 , but I honestly don't understand everything in this code. Plus it seems to be automatic in python according to this link https://seaborn.pydata.org/generated/seaborn.violinplot.html , but I only work with R.

And if I compute this :

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_violin(draw_quantiles = c(0.25, 0.5, 0.75),
              linetype = "dashed")

I get all the lines in dashed type : enter image description here

Thank you for your help

Y.Coch
  • 331
  • 4
  • 13

1 Answers1

2

I had the same problem as you. This is probably not the most elegant way to do so, but I first plotted the dashed line and then replotted the violin with fill="transparent".

You can control which quartiles to plot in the vector designated for draw_quantiles in geom_violin(). First draw the 25 and 75% quartiles with dashed lines than replot the violin with only the 50% quartile and solid line. Please note that the 50% quartile represents the median, not the mean value.

Here is the code:

ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.75),
      linetype = "dashed") +
geom_violin(fill="transparent",draw_quantiles = 0.5)

To get the actual mean, you must use the stat_summary(), but instead of a line, you get a point.

ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.75),
  linetype = "dashed") +
geom_violin(fill="transparent",draw_quantiles = 0.5) +
stat_summary(fun.y=mean, geom="point", shape=20, size=7, color="red", fill="red")

enter image description here

Zuntini
  • 21
  • 4
  • It doesn't work for me : I get an error message saying ']' unexpected in: " linetype = "dashed") + geom_violin(fill="transparent")]" If I remove the square brackets I get almost what I want except for the quantiles (still in dashed) – Y.Coch Dec 04 '18 at 14:18