首页 > 解决方案 > 在一个地块上绘制每十年的平均每月计数

问题描述

我有一个数据集,其每月“流量”超过 68 年。我试图通过制作一个在 x 轴上具有季节性分布并在图上显示每个十年的平均值的图来按十年来比较流量分布。

标签: rggplot2plotdistribution

解决方案


(编辑:从折线图更改为闪避条形图,以更好地与 OP 代码对齐。)

这是一种使用 dplyr、tidyr 和 ggplot2 的方法tidyverse

library(tidyverse)
M %>%
  group_by(Decade = floor(Year/10)*10) %>%
  summarize_at(vars(Jan:Sep), mean) %>%

  # This uses tidyr::pivot_longer to reshape the data longer, which gives us the
  #  ability to map decade to color.
  pivot_longer(-Decade, names_to = "Month", values_to = "Avg") %>%

  # This step to get the months to be an ordered factor in order of appearance, 
  #   which is necessary to avoid the months showing up in alphabetical order.
  mutate(Month = fct_inorder(Month)) %>%
  # Alternatively, we could have aligned these thusly
  # mutate(Month_order = match(Month, month.abb)) %>%
  # mutate(Month = fct_reorder(Month, Month_order)) %>%

  ggplot(aes(Month, Avg, fill = as.factor(Decade))) +
  geom_col(position = position_dodge()) +
  scale_fill_discrete(name = "Decade")

在此处输入图像描述


推荐阅读