Home > Blockchain >  create a scatterplot with mean and standard error of the mean
create a scatterplot with mean and standard error of the mean

Time:03-18

I am trying to create a scatterplot using ggplot2. Besides the individual values, I want to display the mean for each group and the standard error of the mean. Below you can find an example of the desired result which I created using GraphPad Prism.

I thank you very much in advance for your precious time! BR

plot in GraphPad

CodePudding user response:

The following code replicates your plot fairly well:

library(ggplot2)

ggplot(df, aes(x = group, y = y, group = group))   
  geom_point(aes(shape = group), size = 3,
             position = position_jitter(width = 0.1))  
  stat_summary(fun = mean, 
               fun.min = function(x) mean(x) - sd(x)/sqrt(length(x)), 
               fun.max = function(x) mean(x)   sd(x)/sqrt(length(x)),
               geom = 'errorbar',  width = 0.25)  
  stat_summary(fun = mean, fun.min = mean, fun.max = mean,
               geom = 'errorbar',  width = 0.5)  
  scale_y_continuous(limits = c(0, 30))  
  scale_shape_manual(values = c(16, 15))  
  labs(x = '', y = '')  
  theme_classic()  
  theme(axis.text.x = element_blank(),
        legend.position = 'none')

enter image description here

Your data needs to be in the following format:

df <- data.frame(group = rep(c("A", "B"), times = c(8, 4)),
                 y = c(1.8, 2.5, 2.4, 4, 5.5, 13, 14, 26,
                       2.3, 2.8, 5.5, 10))

df
#>    group    y
#> 1      A  1.8
#> 2      A  2.5
#> 3      A  2.4
#> 4      A  4.0
#> 5      A  5.5
#> 6      A 13.0
#> 7      A 14.0
#> 8      A 26.0
#> 9      B  2.3
#> 10     B  2.8
#> 11     B  5.5
#> 12     B 10.0

CodePudding user response:

Have a look at the geom_errorbar() function in ggplot2. You should be able to reproduce a plot similar to that in figure using geom_errorbar() and geom_dotplot().

  • Related