首页 > 解决方案 > 绘制按 R 中的唯一 ID 分组的汇总每日时间序列

问题描述

假设我有一个每日时间序列,其样本如下所示。我想总结每个ID's数据并geom_line通过ggplot.

我怎样才能做到这一点R

library(dplyr)
library(tidyverse)
    

    ID = c("297557", "279557","297557", "279557","297557", "279557",
    "297557", "279557","297557", "279557","280485", "280485","280485", "280485",
    "280485", "280485","280485", "280485","280485", "280485")

    Date = c("1/1/2020", "1/2/2020", "1/3/2020", "1/4/2020",
    "1/5/2020", "1/6/2020", "1/7/202", "1/8/2020", "1/9/2020", "1/10/2020",
     "1/1/2020", "1/2/2020", "1/3/2020", "1/4/2020",
    "1/5/2020", "1/6/2020", "1/7/202", "1/8/2020", "1/9/2020", "1/10/2020")
    
    Var1 = c("1", "3", "5", "7", "9", "11", "13", "15", "17", "19")
    Var2 = c("2", "4", "6", "8", "10", "12", "14", "16", "18", "20") 

# Pivot data
df = data.frame(ID, Date, Var1, Var2)
df = df %>% pivot_longer(-c(ID, Date)) %>%
  rowwise %>%
  mutate(Pixel = paste0(c(ID,".",name), collapse = "")) %>%
  select(-name)

# Lubridate
df$Date = as.Date(df$Date, format = "%m/%d/%Y")
df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)

# ggplot line plot by grouping IDs and summarizing daily data for each ID
# Summarize data in ggplot. Stuck at this step

ggplot(data = df, aes(x= Month, y=value, group = Pixel)) +
  geom_line() + 
  xlab("")

期望的输出

在此处输入图像描述

标签: rggplot2

解决方案


你可以使用

df <- data.frame(ID, Date, Var1, Var2)

library(tidyverse)
library(lubridate)

df %>% pivot_longer(-c(ID, Date)) %>%
  mutate(Pixel = paste0(ID, ".", name),
         Date = month(Date, label = TRUE, abbr = FALSE)) %>% 
  ggplot(aes(x = Date, y = value, group = Pixel, color = Pixel)) +
  geom_line() +
  labs(x = "Month")

(由于我不明白的原因,我无法上传图片atm......)

为


推荐阅读