r - 绘制按 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("")
期望的输出
解决方案
你可以使用
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......)
推荐阅读
- javascript - 我需要在角度翻译中翻译一个动态变量
- xml - XML - XSLT 按计数分组元素
- node.js - TypeError: Request path contains unescaped characters at googleapis
- javascript - How can I get PurifyCSSPlugin to remove my unused css in Angular6?
- android - 如何通过公交获得覆盖距离
- sql - Oracle Regexp_substr 字符串
- php - ReactPHP get_class() 期望参数 1 是对象,给定字符串
- html - Angular:从 HTML 发送元素
- javascript - 引导模式不会在页面加载时打开
- python-sphinx - Including a literal block inside an admonition