在ggplot中包含“无数据”

时间:2018-06-19 00:30:44

标签: r ggplot2 na

编辑:我已经尝试过向我提出建议,但na.omit正在策划我的NAs,好像它们是一个值。我还用一些示例数据和一个新的ggplot脚本更新了我的帖子,以反映向我提出的建议。

我正在尝试使用geom line在ggplot中绘制月度数据。但是,有几个月我没有数据。例如,我有April, May, June, and July个月的数据,August中没有数据,然后September中有数据。我想做的是绘制月数,包括没有数据的月份,以便正确表示时间尺度。我有相当多的差距,几个月没有数据(由于从月度到季节性监测的转变),但仍然希望所有月份都显示出总体趋势。

下面是一些示例数据(所有列都是因素),我的代码和我输出的屏幕抓取。

样本数据

Material    Month RelativeFrequency
1    Compost Apr 2017  29.2817679558011
2     Hybrid Apr 2017   37.292817679558
3 Wood Chips Apr 2017  33.4254143646409
4    Compost May 2017  28.8401253918495
5     Hybrid May 2017  34.4827586206897
6 Wood Chips May 2017  36.6771159874608
7    Compost Aug 2017  NA
8    Hybrid  Aug 2017  NA
9 Wood Chips Aug 2017  NA

脚本

  library (ggplot2)
  ggplot(data = Mound.Freq, aes(x = Month, y = RelativeFrequency, color = 
  Material, group =
  Material))+
  geom_point(data = na.omit(Mound.Freq))+
  geom_line(data = na.omit(Mound.Freq))+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Sample Output

谢谢!

2 个答案:

答案 0 :(得分:0)

让我们创建一些虚拟数据,因为OP没有提供一个虚拟数据。

# create some dummy data
R> df <- data.frame(A = 1:10, B = 11:20, c = 21:30)

接下来,我介绍一些缺失值。

R> set.seed(4)
R> df<- as.data.frame(lapply(df,function(cc) cc[ sample(c(TRUE, NA), prob = c(0.85, 0.15), size = length(cc), replace = TRUE) ]))
R> head(df)
  A  B  c
1 1 11 21
2 2 NA NA
3 3 13 23
4 4 NA 24
5 5 15 25
6 6 16 26

现在,让我们尝试使用直线和点图来绘制变量AB,以便于查看缺失值。

R> library(ggplot2)
R> ggplot(data = df, aes(x=A, y=B))+
   geom_point()+ 
   geom_line()
Warning messages:
1: Removed 4 rows containing missing values (geom_point). 
2: Removed 2 rows containing missing values (geom_path).

enter image description here

警告消息告诉我们,geom_line()已自动删除了缺失的值。它还建议使用geom_path()代替。因此,为了绘制缺失值,我们可以做这样的事情;

R> ggplot(data = df, aes(x=A, y=B))+
       geom_point(data = na.omit(df))+
       geom_line(data = na.omit(df))

enter image description here

答案 1 :(得分:0)

请注意,是否可以得到答案,但是我试图做同样的事情。下面是我的粗略解决方案。这将需要一些改进。我基本上把x和y的if语句放进去

    geom_line(  data = subData[!is.na(as.numeric(subData $Hwa2)),] ,

            aes(    if (length (na.omit(as.numeric(subData $Hwa2))) == 0) {
                    x = as.POSIXct(strptime(paste(yr,i,1, sep = "-"),"%Y-%m-%d"), tz = "GMT")
                } else {
                    x = as.POSIXct(subData $DateTime[!is.na(subData $Hwa2)], origin = "1970-01-01")
                },
                if (length (na.omit(as.numeric(subData $Hwa2))) == 0) {
                    y = 0
                } else {
                    y = na.omit(as.numeric(subData $Hwa2))
                }

            , color = "FM-13"),


            size = 0.5, 
            alpha = 1)