繁体   English   中英

plot 时间序列和 R 中的 NA 值

[英]plot time series and NA values in R

我一直在 R 中搜索缺失值可视化,尽管有很多不错的选项,但我还没有找到代码来获得我需要的东西。

我的数据框(df)

data.frame(
  stringsAsFactors = FALSE,
              Date = c("01/01/2000","02/01/2000",
                       "03/01/2000","04/01/2000","05/01/2000","06/01/2000",
                       "07/01/2000","08/01/2000","09/01/2000"),
            Site.1 = c(NA,0.952101337,0.066766616,
                       0.77279551,0.715427011,NA,NA,NA,0.925705179),
            Site.2 = c(0.85847963,0.663818831,NA,NA,
                       0.568488712,0.002833073,0.349365844,0.652482654,
                       0.334879886),
            Site.3 = c(0.139854891,0.057024999,
                       0.297705256,0.914754178,NA,0.14108163,0.282896932,
                       0.823245136,0.153609705),
            Site.4 = c(0.758317946,0.284147119,
                       0.756356853,NA,NA,0.313465424,NA,0.013689324,0.654615632)
) -> df

我想得到一个类似于以下的 plot:

预期情节

考虑到我的实际数据包含 51 个站点和大约 9,000 个日期

你可以尝试这样的事情:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>%
  # from wide to long
  pivot_longer(!Date, names_to = "sites", values_to = "value") %>%
  # add a column of one an NAs following your data
  mutate(fake = ifelse(is.na(value),NA, 1),
         sites = as.factor(sites)) %>%
  # plot it
  ggplot(aes(x = Date, y = reorder(sites,desc(sites)), color = fake, group = sites)) + 
  # line size
  geom_line( size = 2) + 
  # some aesthetics
  ylab('sites') +
  scale_color_continuous(high="black",na.value="white") + 
  theme(legend.position = 'none',
        panel.background = element_rect(fill ='white'),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

在此处输入图像描述

尽管如此,我更喜欢这样更简单的东西:

df %>%
  pivot_longer(!Date, names_to = "sites", values_to = "value") %>%
  ggplot(aes(x = Date, y = sites, fill =value)) + 
  geom_tile() +
  theme_light() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

在此处输入图像描述

这个答案类似于第一个,但使用 NA 值来中断行。

library(ggplot2)
library(tidyr)
library(stringr)
  df %>%  pivot_longer(., cols = 2:5) %>% 
    mutate(present = !is.na(value)) %>% 
    mutate(height = as.numeric(str_remove(name, "Site.")) * present) %>% mutate(value2 = case_when(!is.na(value) ~ height)) %>% 
      ggplot(aes(Date, value2, group = name)) +
    geom_line() + 
        theme(legend.position = "none") +
        scale_x_discrete(guide = guide_axis(angle = 90))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM