Let's say I have a daily time series a sample of which is shown below. I would like to summarize the each ID's
data and make line plots (geom_line
) via ggplot
.
How can I do this in 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("")
Desired output
CodePudding user response:
You could use
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")
(For reasons I don't understand, I can't upload an image atm...)