rggplot2boxplotfactors

Setting Standard Deviation to ggplot2 boxplot with 2 factors


after searching for a while, I've decided to ask my first question :

it's pretty simple actually - I am plotting with ggplot2 and unfortunately the whiskers (in purple) are overlapping each other (they're not in the position they should be)

It is caused due to using different arguments from different websites (I did not find any guide for plotting with 2 different factors in ggplot2 AND ADDING SD TO THE PLOT)

so in practice I took the sd example from a different guide which consists of no factors at all.

here's my code :

ggplot(data=df2, aes(x=Usage, y=`Panas result`, fill=Positive)) +
geom_boxplot(position=position_dodge(), width=0.5) +
coord_cartesian(ylim = c(10, 45)) +
scale_fill_manual(values=c("#33FFFF","seagreen2"),labels=c('נייטרלי', "חיובי")) +
labs(fill = "מניפולציה",title="תוצאות שאלון הפנס כתלות בסיווג זמן המסך וסוג המניפולציה", x="זמן         מסך", y =   
"תוצאות שאלון הפנס") +
stat_summary(
fun.min = function(x) mean(x) - sd(x),
fun.max = function(x) mean(x) + sd(x),
geom = "errorbar",
color = "purple",
width = .5,
orientation = 'Usage') +
theme_classic()        

that yeilds the following plot :

enter image description here

again - All I ask is for the purple whiskers to be in their positions (and not one on top of the other)


Solution

  • The issue is that stat_summary defaults to position="identity". To align your errorbars with the box plots and dodge them by the same amount you have to use the same position in stat_summary as for the box plots, i.e. in your case position = position_dodge() will do as you have set width = .5 for both.

    Using some a minimal reproducible example based on mtcars:

    library(ggplot2)
    
    ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(am))) +
      geom_boxplot(position = position_dodge(), width = 0.5) +
      coord_cartesian(ylim = c(10, 45)) +
      scale_fill_manual(values = c("#33FFFF", "seagreen2"), labels = c("נייטרלי", "חיובי")) +
      labs(
        fill = "מניפולציה", title = "תוצאות שאלון הפנס כתלות בסיווג זמן המסך וסוג המניפולציה", x = "זמן         מסך", y =
          "תוצאות שאלון הפנס"
      ) +
      stat_summary(
        fun.min = function(x) mean(x) - sd(x),
        fun.max = function(x) mean(x) + sd(x),
        geom = "errorbar",
        color = "purple",
        width = .5,
        position = position_dodge()
      ) +
      theme_classic()