r - 在一个地块上绘制每十年的平均每月计数
问题描述
我有一个数据集,其每月“流量”超过 68 年。我试图通过制作一个在 x 轴上具有季节性分布并在图上显示每个十年的平均值的图来按十年来比较流量分布。
解决方案
(编辑:从折线图更改为闪避条形图,以更好地与 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")
推荐阅读
- laravel - Laravel:将此服务提供者添加到 app.php 会给出“找不到类日志”
- c# - 健康文本离开对象引用未设置为每帧对象的实例
- excel - 通过变量字符串引用范围导致 1004 错误
- firebase - 我保存在 Firebase 存储中的音频文件没有声音
- javascript - 如何删除外部脚本添加的内联样式?
- python - PySpark - 删除 n-gram 中的空格
- c++ - 两个数组查找代码如何具有不同的速度
- r - 在 r 的一个季度内不购买后放置一个 0
- excel - 数据输入后保护细胞,需要输入重量,以特定格式记录输入时间,比较值,设置计数器
- laravel - 更改身份验证端点后,laravel广播频道未调用