ggplot2:按月在同一地块上多年并分配变量

ggplot2 : Multiple years on Same Plot by Month & assigning variable

我有一个关于绘制变量的快速问题 如此 link 所示的多年: 如何将我的变量分配到“值”所在的位置而不是假数据?

在此link

访问数据

图书馆(读者)

rawdata <- read_csv("https://gist.githubusercontent.com/dewittpe/f9942bce11c34edabf888cbf8375ff17/raw/cb2b527fb2ee5c9c288b3246359c57d36df9fc6e/Data.csv")

0。设置数据

library(zoo)
library(lubridate)
library(ggplot2)
value <- rawdata$Value #Name of variable from csv

dat1 = data.frame(date = seq(as.Date("1995-01-01"),
as.Date("1995-12-01"), "1 month"),
              value = cumsum(rnorm(12)))  ###How do I assign my variable where "value" is located instead of fake data?
dat1$date = as.yearmon(dat1$date)  

dat2 = data.frame(date = seq(as.Date("1996-01-01"),
as.Date("1996-12-01"), "1 month"),
              value = cumsum(rnorm(12)))
dat2$date = as.yearmon(dat2$date)


ggplot(rbind(dat1,dat2), aes(month(date, label=TRUE, abbr=TRUE), 
                         value, group=factor(year(date)),
                         colour=factor(year(date)))) +
  geom_line() +
  geom_point() +
  labs(x="Month", colour="Year") +
  theme_classic()'

enter image description here

一个建议:使用readr将数据读入R。这将有助于设置每列的存储模式。我在 github 要点中复制了数据集。要将数据读入 R 使用

library(readr)

dat1 <- read_csv("https://gist.githubusercontent.com/dewittpe/f9942bce11c34edabf888cbf8375ff17/raw/cb2b527fb2ee5c9c288b3246359c57d36df9fc6e/Data.csv")

数据读入后,生成如下图

library(lubridate)
library(ggplot2)
library(dplyr)

# Use dplyr::filter to filter the data to the years of interest.

dat1 %>%
  dplyr::filter(lubridate::year(date) %in% 1995:1996) %>%

ggplot(.) +
  aes(x = lubridate::month(date, label = TRUE, abbr = TRUE),
      y = value,
      group = factor(lubridate::year(date)),
      color = factor(lubridate::year(date))) +
  geom_line() +
  geom_point() +
  labs(x = "Month", color = "Year") +
  theme_classic()