【问题标题】:ggplot2 for monthly time series dataggplot2 用于每月时间序列数据
【发布时间】:2019-09-13 04:24:12
【问题描述】:

我有一个从 1979 年到 2018 年的时间序列

        Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
1979 15.414 16.175 16.342 15.447 13.857 12.530 10.311  8.041  7.051  8.748 10.943 13.336
1980 14.862 15.955 16.041 15.429 13.793 12.205 10.100  7.984  7.667  9.183 11.383 13.593
1981 14.910 15.604 15.632 15.010 13.802 12.430 10.271  7.844  7.138  8.856 10.929 13.341
1982 15.177 15.974 16.044 15.466 13.973 12.476 10.367  8.139  7.302  9.421 11.627 13.642
1983 14.942 16.006 16.085 15.172 13.491 12.296 10.570  8.186  7.395  9.334 11.461 13.299
1984 14.473 15.299 15.584 15.015 13.577 12.152  9.977  7.771  6.805  8.561 10.842 12.989

我可以使用t(df)tidyr::gather(df) 将系列转换为单列,得到如下结果:

   key  value
1 1979 15.414
2 1979 16.175
3 1979 16.342
4 1979 15.447
5 1979 13.857
6 1979 12.530

我在尝试使用ggplot2 时出现了问题:我想从我的系列中获得一个非常漂亮的图表,但这不可能,因为我不知道如何配置 x 轴以获得一个普通的索引。我的系列是密集的正弦类型。

ggplot(df, aes(key, value)) + geom_line(aes(group=1), colour="#000099") 

这不能正确表示系列。谁能帮我获得一个好的 df 来表示我的数据?

另一方面,我试图按季度来表示它。我从zoo::as.yearqtr 找到了这个,但工作不正常。例如:ts(df,start=c(as.yearqrt("1979-1",1)),frequency=4)

我也发现了这个time series plot with x axis in "year"-"month" in R,但我更喜欢使用 ggplot2,即使可以使用相同的方式。

提前谢谢你。所有有帮助的 cmets 都会得到奖励!

【问题讨论】:

  • 您需要创建一个正确的Date 列。如果您的示例实际上是可重现的,您将更有可能收到有用的答案。

标签: r ggplot2 time-series


【解决方案1】:

您的日期当前使用行和列存储在两个位置。我们可以收集该列,以便年份和月份位于每个数据点可用的单独列中。要从月份和年份创建日期数据,我喜欢lubridate。 (在这种情况下,我用 15 分配到每个月的中旬。)

df %>%
  gather(Month, val, -Year) %>%
  mutate(date = lubridate::ymd(paste(Year, Month, 15))) %>%
  ggplot(aes(date, val)) + 
  geom_line()

df <- read.table(
  header = T, 
  stringsAsFactors = F,
  text = "Year        Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct    Nov    Dec
1979 15.414 16.175 16.342 15.447 13.857 12.530 10.311  8.041  7.051  8.748 10.943 13.336
1980 14.862 15.955 16.041 15.429 13.793 12.205 10.100  7.984  7.667  9.183 11.383 13.593
1981 14.910 15.604 15.632 15.010 13.802 12.430 10.271  7.844  7.138  8.856 10.929 13.341
1982 15.177 15.974 16.044 15.466 13.973 12.476 10.367  8.139  7.302  9.421 11.627 13.642
1983 14.942 16.006 16.085 15.172 13.491 12.296 10.570  8.186  7.395  9.334 11.461 13.299
1984 14.473 15.299 15.584 15.015 13.577 12.152  9.977  7.771  6.805  8.561 10.842 12.989")

【讨论】:

  • 你知道如何得到季度图吗?
  • 你的意思是每三个月包含一次吗?您可以在 ggplot 行之前添加filter(lubridate::month(date) %% 3 == 0) %&gt;% ..
  • 好的,谢谢。这种描述数据的方式比使用 dt() 对象要好得多。
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 2021-07-15
  • 2016-07-18
  • 2013-04-21
  • 2017-03-04
  • 1970-01-01
  • 2018-06-23
相关资源
最近更新 更多