0

I have data

Name    V1
M1      50 
M2      10 
M1      30
M1      45
M2      5
M2      7

With my code, I was able to produce a violin plot. But I don't know how to put the value of mean in each violin plot in number using base R (not ggplot)?

Here is an example of my code.

with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"), 
                   plotCentre="line", rectCol="white", col="gray", ylab="", 
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

Thanks a lot

KoenV
  • 4,113
  • 2
  • 23
  • 38
Lara
  • 73
  • 1
  • 8
  • Welcome to SO. Before posting a question please read: **[How to ask a good question](https://stackoverflow.com/help/how-to-ask)**. – KoenV May 27 '19 at 12:08
  • Hi Thanks for your suggestion. I've already edited to make it clear. Hope that it's okay now? – Lara May 28 '19 at 05:02
  • I updated my answer with a version where the means appear inside the violin-plots. Please, have a look. – KoenV May 29 '19 at 05:38

1 Answers1

0

You could use the following code:

Your data:

Data <- read.table(header = TRUE, 
            text = "Name    V1
                    M1      50 
                    M2      10 
                    M1      30
                    M1      45
                    M2      5
                    M2      7")

Code

library(vioplot)
library(dplyr)

## calculate the mean per group
DataMean <- Data %>% 
  group_by(Name) %>%
  summarize(mean = mean(V1))

## your plotting code
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"), 
                   plotCentre="line", rectCol="white", col="gray", ylab="", 
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

## use base r 'text' to add the calculated means
## at position 1 and 2 on the X-axis, and
## at height of the Y-axis of 60 (2 times)
text(x = c(1, 2), y = c(60,60), labels = round(DataMean$mean, 2))

yielding the following plot:

enter image description here

Of course, we can play around with the position of the text. If we want the means to appear inside the violin plots, we use the mean values as Y-coordinates, and change the color to make it more visible (and shift the X-coordinates a little to the right, in combination with a lighter grey).

### playing with position and color
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"), 
                   plotCentre="line", rectCol="white", col="lightgray", ylab="", 
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
text(x = c(1.1, 2.1), y = DataMean$mean, labels = round(DataMean$mean, 2), col = "blue")

yielding this plot:

enter image description here

Please, let me know whether this is what you want.

KoenV
  • 4,113
  • 2
  • 23
  • 38