Force error bars to be in the middle of bar

后端 未结 2 1316
轮回少年
轮回少年 2020-12-04 03:26

I\'m using R and ggplot2 to plot a pretty basic bar graph with error bars, but I\'m having trouble forcing them to be in the center of the bars that I create.

My co

相关标签:
2条回答
  • 2020-12-04 03:45

    Your bars are 10.8 units wide (12 units each, times 0.9 for the gap), so try:

    position = position_dodge(10.8*2)
    

    in your geom_errorbar call

    0 讨论(0)
  • 2020-12-04 03:47

    While @jeremycg's answer is correct (+1 for obscure knowledge of ggplot theme system), it's more of a side-effect than a solution.

    Let's just think for a moment of the typical use case scenario for a bar chart. Generally we would use a bar chart when we are trying to present data that are:

    • Discrete by Continuous

    Right now, we have data that are:

    • Continuous by Continuous

    A dot plot would be more appropriate for this data type. But we can see that it looks a bit ridiculous because our data are not truly continuous.

    ggplot(df, aes(Time,CellCount, color = Type)) + 
      geom_point(stat="identity") + 
      geom_errorbar(aes(
        ymin = CellCount - Error, 
        ymax = CellCount + Error),   
        width = 0.9)
    

    For a presentation of this nature, one ought to use a categorical variable for their x-coordinate.

    This can be accomplished by pre-processing your variable, Time, as a factor, or by calling the variable as.factor in the aesthetic string (aes).

    ggplot(df, aes(
        x=as.factor(Time), # as.factor() makes this a discrete scale
        y = CellCount, 
        fill = Type)) +
      geom_bar(stat = "identity", position = "dodge") +
      geom_errorbar(aes(
        ymin = CellCount - Error, 
        ymax = CellCount + Error),   
        width = 0.9, 
        position = position_dodge(width = 0.9)) + # now you can use it
      labs(x= "Time (h)", y = "Cell count") +
      scale_fill_discrete(labels = c("Anirridia", "Control")) 
    
    0 讨论(0)
提交回复
热议问题