ggplot2:按月计算的多年同一情节&分配变量

时间:2017-05-20 23:49:57

标签: r ggplot2 charts time-series timeserieschart

我有一个关于绘制变量的快速问题 多年如此链接所示: ggplot: Multiple years on same plot by month 如何将变量分配到" value"找到而不是假数据?

访问此链接的数据

库(readr)

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

1 个答案:

答案 0 :(得分:0)

一个建议:使用readr将数据读入R.这将有助于为每列设置存储模式。我在github gist中制作了数据集的副本。要将数据读入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()

enter image description here