Luigi Marongiu
2022-Feb-21 16:19 UTC
[R] How to superimpose jitter and barplot in ggplot2?
Hello, I am following this post https://www.datanovia.com/en/lessons/ggplot-error-bars/ to superimpose a jitter plot and a barplot with error bars. Te example works: ``` df2 <- ToothGrowth df2$dose <- as.factor(df2$dose) head(df2, 3) df2.summary <- df2 %>% group_by(dose) %>% summarise( sd = sd(len, na.rm = TRUE), len = mean(len) ) df2.summary ggplot(df2, aes(dose, len)) + geom_col(data = df2.summary, fill = NA, color = "black") + geom_jitter( position = position_jitter(0.2), color = "black") + geom_errorbar( aes(ymin = len-sd, ymax = len+sd), data = df2.summary, width = 0.2) ``` but on my data, it does not. The data I have is similar to the example, only with 2 classes rather than 3: ```> str(df)'data.frame': 82 obs. of 33 variables: $ id : int 1 2 3 4 5 6 7 8 9 10 ... ... $ tocopherol : num 22.39 15.93 19.91 9.52 35 ... $ tot_ascorb : num 7.306 NA NA 0.102 NA ... ... $ covid : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 2 2 2 2 2 ...> df.summary <- df %>%+ group_by(covid) %>% + summarise( + sd = sd(tot_ascorb, na.rm = TRUE), + len = mean(tot_ascorb, na.rm = TRUE) + ) `summarise()` ungrouping output (override with `.groups` argument)> df.summary# A tibble: 2 x 3 covid sd len <fct> <dbl> <dbl> 1 No 6.79 47.8 2 Yes 31.4 14.5 ``` but when I try to run ggplot, it works in part. The bar plot works: ```> ggplot(df, aes(covid, len)) +geom_col(data = df.summary, fill = NA, color = "black") + geom_errorbar(aes(ymin = len, ymax = len+sd), data = df.summary, width = 0.2) ``` but the jitter does not: ```> ggplot(df, aes(covid, len)) ++ geom_col(data = df.summary, fill = NA, color = "black") + + geom_errorbar(aes(ymin = len, ymax = len+sd), + data = df.summary, width = 0.2) + + geom_jitter(position = position_jitter(0.2), color = "black") Error in FUN(X[[i]], ...) : object 'len' not found ``` What am I getting wrong? Thanks -- Best regards, Luigi