Search code examples
rlabelmeanviolin-plot

How to add value of mean in number in violin plot using base R


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


Solution

  • 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.