【问题标题】:R ggplot2 stat_summary : error when plotting the minimum thresholdR ggplot2 stat_summary:绘制最小阈值时出错
【发布时间】:2015-12-22 01:57:45
【问题描述】:

我目前正在尝试绘制一个简单的 stat_summary(fun.y=mean,fun.ymin=min, fun.ymax=max,geom="pointrange"...

没有错误消息,但绘制的最小阈值是错误的,应该在 4-5 左右,它们被分配为 0。

我使用的代码是:

library(ggplot2)
library(scales)


p=ggplot(data,aes(x=Date,y=ED))+

   stat_summary(fun.y=mean,fun.ymin=min, fun.ymax=max,geom="pointrange",colour='grey60',width=.5,size=1)+

   # scale axes
   scale_y_continuous(breaks=seq(2,10,2))+
   scale_x_date(labels = date_format("%m"), breaks='6 months')+

   # theme
   theme(legend.position = "none")+
   theme_bw()+
   theme(strip.text.x = element_text(size = 16,face='bold'))+
   theme(axis.text.x=element_text(size=14,face="bold"),
         axis.text.y=element_text(size=14,face='bold'),
         axis.title=element_text(size=16,face="bold"))

p

在数据集中,每个日期有 3 个 ED 值,分别对应平均值、最小值和最大值。这是数据集:

> data
         Date   ED
1  2000-10-23 6.64
2  2000-10-23 5.28
3  2000-10-23 8.01
4  2001-05-08 5.89
5  2001-05-08 5.05
6  2001-05-08 6.73
7  2001-10-23 7.27
8  2001-10-23 5.55
9  2001-10-23 8.99
10 2002-05-08 5.83
11 2002-05-08 4.92
12 2002-05-08 6.75
13 2002-10-23 7.60
14 2002-10-23 5.67
15 2002-10-23 9.53
16 2003-05-08 5.83
17 2003-05-08 4.92
18 2003-05-08 6.75
19 2003-10-23 7.60
20 2003-10-23 5.67
21 2003-10-23 9.53
22 2004-05-07 5.83
23 2004-05-07 4.92
24 2004-05-07 6.75
25 2004-10-22 7.60
26 2004-10-22 5.67
27 2004-10-22 9.53
28 2005-05-07 5.83
29 2005-05-07 4.92
30 2005-05-07 6.75
31 2005-10-22 7.60
32 2005-10-22 5.67
33 2005-10-22 9.53

我已经检查了数据集中的值,格式是数字,没有0,负值也没有NA。

# check values
class(data$ED)
data$ED[is.na(data$ED)]
data$ED[data$ED<=0]
min(data$ED)
tapply(data$ED,list(data$Date),min)
tapply(data$ED,list(data$Date),max)

由于似乎正确绘制了平均值和最大值,我不明白我在这段代码中做错了什么。 我很乐意阅读任何想法。

谢谢,

保罗

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    似乎stat_summary() 中的参数width 导致了问题。你应该删除它。 geom_linerange() 无论如何都不允许(它使用 size 代替)。

    p=ggplot(data,aes(x=Date,y=ED))+
    
      stat_summary(fun.y=mean,fun.ymin=min, fun.ymax=max,
        geom="pointrange",colour='grey60',size=1)+
    
      # scale axes
      scale_y_continuous(breaks=seq(2,10,2))+
      ylim(2,10) +
      scale_x_date(labels = date_format("%m"), breaks='6 months')+
    
      # theme
      theme(legend.position = "none")+
      theme_bw()+
      theme(strip.text.x = element_text(size = 16,face='bold'))+
      theme(axis.text.x=element_text(size=14,face="bold"),
            axis.text.y=element_text(size=14,face='bold'),
            axis.title=element_text(size=16,face="bold"))
    
    p
    

    我无法解释为什么会发生此错误。我猜它被传递给另一个函数,在那里它以在数据中引入 0 值的方式进行解释。

    【讨论】:

    • 非常感谢,它有效。令人惊讶的是,我之前将此代码用于另一个数据集并且没有问题。就像有时会考虑这个参数“宽度”并且不会干扰任何东西,有时不会。再次感谢
    猜你喜欢
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多