[英]Plotting time series of NDJFM (ND previous year and JFM of succeeding year) daily data using ggplot in R
[英]Plotting time series data in R by year
我幾乎每月都會進行一系列觀察,並希望對它們進行 plot。 有些月份可能會有不止一個觀察結果,所以這一天很重要。
我可以很容易地將 plot 它們作為一條線,但我希望將每年的觀察結果繪制在單獨的線上,以便可以在年份之間進行比較(即 2018 年的一條線,2019 年的另一條線,2020 年的另一條線)。
我希望我的 x 軸從 1 月 1 日到 12 月 31 日運行。
數據
Date Value
2018-04-30 NA
2018-05-31 102
2018-06-29 27
2018-07-01 3
2018-07-31 27
2018-09-04 52
2018-09-05 1
2018-10-01 78
2018-10-31 117
2018-11-30 245
2019-01-02 201
2019-01-31 256
2019-02-28 228
2019-04-01 155
2019-05-01 111
2019-05-31 105
2019-07-01 77
2019-07-31 61
2019-08-30 79
2019-10-01 76
2019-10-31 104
2019-12-03 196
2020-01-02 162
2020-01-31 292
2020-02-28 266
2020-03-26 145
2020-05-01 130
2020-06-03 86
2020-07-01 42
這是我迄今為止嘗試過的並且可以訪問包“ggplot2”、“dplyr”、“zoo”和“lubridate”
ggplot(a, aes(x = Date, y = Value)) +
geom_point() +
geom_line() +
scale_x_date(date_minor_breaks = "1 month", date_labels = "%B %Y") +
theme_bw()
也許這會有所幫助。 您必須首先按年份格式化日期以創建組和 colors。 您可以欺騙軸添加一個像 2020 年這樣的常見年份。這里可能的解決方案:
library(tidyverse)
#Data
df <- structure(list(Date = c("2018-04-30", "2018-05-31", "2018-06-29",
"2018-07-01", "2018-07-31", "2018-09-04", "2018-09-05", "2018-10-01",
"2018-10-31", "2018-11-30", "2019-01-02", "2019-01-31", "2019-02-28",
"2019-04-01", "2019-05-01", "2019-05-31", "2019-07-01", "2019-07-31",
"2019-08-30", "2019-10-01", "2019-10-31", "2019-12-03", "2020-01-02",
"2020-01-31", "2020-02-28", "2020-03-26", "2020-05-01", "2020-06-03",
"2020-07-01"), Value = c(NA, 102L, 27L, 3L, 27L, 52L, 1L, 78L,
117L, 245L, 201L, 256L, 228L, 155L, 111L, 105L, 77L, 61L, 79L,
76L, 104L, 196L, 162L, 292L, 266L, 145L, 130L, 86L, 42L)), row.names = c(NA,
-29L), class = "data.frame")
下一個代碼:
#Format dates
df$Date <- as.Date(df$Date)
#Create year
df$Year <- format(df$Date,'%Y')
#Create day and month of year
df$Day <- format(df$Date,'%d')
df$Month <- format(df$Date,'%m')
#Assign a dummy date
df$DayMonth <- as.Date(paste0(2020,'-',df$Month,'-',df$Day))
#Now sketch for plot
ggplot(df, aes(x = DayMonth, y = Value,group=Year,color=Year)) +
geom_point() +
geom_line() +
scale_x_date(date_minor_breaks = "1 month", date_labels = "%B %d")+
theme_bw()+
theme(axis.text.x = element_text(angle=90))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.