2 years ago

#75028

test-img

Aurora González Vidal

Adding ylim changes where the mean point is plotted in violinplots

I am trying to do a violinplot for a single variable and drawing its mean as a point. I manage to do so as follows, for example, with the following data the mean is 0.06 and it woks fine:

vble <- c(-1.6666667, NA, -0.2777778, 0.5555556, -2.7777778 , 1.1111111, -0.1587302, NA, NA, 0.0000000, 2.2222222, -1.6666667, 1.1111111, NA, NA, -2.2222222, NA, 4.4444444)
df <- data.frame(id = 1:length(vble), vble)
m <- mean(subsetgr$new, na.rm = TRUE)
m
p = ggplot(data = df, aes(x = "", y = vble)) +
  geom_violin(fill = "#C77CFF")  +   stat_summary(fun = "mean",
                                                geom = "point",
                                                color = "black")
p+ geom_hline(yintercept = 0)

Correctly portrayed

As you can see, the point is above the horizontal line over 0.

However, when I adjust the y limits:

p + lims(y = c(-5, 3)) + geom_hline(yintercept = 0)

the point is plotted below such line. Incorrectly portrayed

I need to adjust the y limits, what do you suggest that I do so that the mean point is correctly plotted?

Thank you very much!


Edit The following solutions, suggested in comments, are also not what I am looking for:

p + coord_cartesian(ylim = c(-5, 3))+ geom_hline(yintercept = 0)

coord_cartesian keeps the average point in the correct place but does not adapt the figure to the new y-axis and therefore, it does not fit opt3

p + scale_y_continuous(limits = c(-5,3)) + geom_hline(yintercept = 0)

scale_y_continuous also deletes data and this changes where the average point is portrayed

opt4

And adding the argument "oob" also brings the same issue

p + scale_y_continuous(limits = c(-5,3), oob = scales::oob_keep) + geom_hline(yintercept = 0)

opt5

Is there a way to manually plot a point in the violinplot. It is not ideal, but I would have to do it only 10 times, for 10 plots, so it should be fine.

r

ggplot2

point

violin-plot

0 Answers

Your Answer

Accepted video resources