错误条在ggplot2条形图中显得太低

时间:2017-06-09 12:22:38

标签: r ggplot2

正在搜索网站(和其他人)以寻找下图所示问题的解决方案。尽管我在这里和其他地方遇到类似的问题尝试了很多不同的解决方案,但我无法让误差线从他们的“低”位置移开。

enter image description here

无论是单独生成一个图形还是两个图形并将它们与gridExtra组合,都会出现问题。

以下是包含的每个数据集的代码和示例:

第一个数据集示例:

Group      PSQI Time_Point
1 Control    2   Baseline
2 Control    2   Baseline
3 Control    2   Baseline
4 Control   13   Baseline
5 Control    1   Baseline
6 Control    7   Baseline

第二

  Group    ESS Time_Point
1 Control   3   Baseline
2 Control   4   Baseline
3 Control   1   Baseline
4 Control   0   Baseline
5 Control   7   Baseline
6 Control  11   Baseline

代码:

library(gridExtra)
library(ggplot2)
library(grid)

p1 <- ggplot(PSQI_Graph,aes(fill=Group,y=PSQI,x=Time_Point)) +
    geom_bar(position="dodge",stat="identity", width = 0.50) +
    stat_summary(fun.data = mean_cl_normal, geom = "errorbar", position = 
position_dodge(.5), width = .25)+
    guides(fill = F)+
    scale_y_continuous(name = "Mean PSQI Score", limits=c(0,25))+
    xlab("Time Point") +
    guides(fill = guide_legend(keywidth = 1.5, keyheight = 1))+
    theme_bw()

真的想把这些数据拿出来,所以会很感激任何建议。

1 个答案:

答案 0 :(得分:2)

It would be better to use geom_errorbar. First, you'll have to make a new data.frame with one line per bar, including the standard error (I added an "After" timepoint to show how this looks):

    Group PSQI Time_Point StdErr
1 Control 4.50   Baseline   1.91
2 Control 7.17      After   0.79

Then, this ggplot call will work:

ggplot(psqi, aes(fill=Group, y=PSQI, x=Time_Point, ymin=PSQI-StdErr, ymax=PSQI+StdErr)) + #the ymin and ymax parameters here tell it where to put the top and bottom error bars
    geom_bar(stat="identity") +
    geom_errorbar() #you can change the width and thickness of the bars

Yielding this image:

相关问题