假設我有一個每日時間序列,其示例如下所示。我想總結每個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("")
期望輸出

uj5u.com熱心網友回復:
你可以用
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...)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358894.html
