首页 > 解决方案 > R:对应于 15 年的 12 个月的数据时间序列的条形图

问题描述

我有一个如下所示的数据集。

month   Yi      Yi+1
1   0.014310185 13.43838262
2   0.014310185 15.7792948
3   0.176113783 16.14479846
4   3.143663699 16.54060078
5   3.755478277 16.75810501
6   3.767263653 17.03156884
7   3.767263653 17.03156884
8   3.829219647 17.03156884
9   4.375269901 17.78482322
10  8.707536696 18.47995179
11  10.28741362 21.33942187
12  10.66218286 21.82637774

我有 15 列 Y(Yi 到 Yi+14)。例如,Yi 列对应于 Yi 年 12 个月的降水量。我必须在 x 轴上并排绘制所有年份(及其月份)的降水量。最后,我必须得到这样的东西:
![在此处输入图像描述][1]

我已经尝试了meltgroup_by函数来按照以下命令重塑我的数据框:

df  <- read_excel("df.xls", col_names = FALSE, skip = 1)
colnames(df) <- c("month", "Yi", paste0("Yi+", 1:14)

df.melt <- melt(tab.df, id = c("month", "Yi", paste0("Yi+", 1:14))

bar <- group_by(df.melt, aes(x = 1:length(value), y = value, fill=factor(month))) +
geom_bar(position="dodge", stat="identity"))

ggplot(bar, aes(x=variable, y=mean, fill=factor(month)))

但它没有用。任何建议如何做到这一点?

标签: rggplot2bar-chart

解决方案


另一种方法是按年使用geom_col和分面。

library(data.table) # for melt
library(ggplot2)

# Took the data example from @Istrel
set.seed(2018)
df <- data.frame(month = 1:12, matrix(abs(rnorm(12 * 15)), nrow = 12))
colnames(df) <- c("month", "Yi", paste0("Yi+", 1:14))
setDT(df) # just to be sure, convert to data.table; use setDF(df) to switch back
df_m <- data.table::melt(df, "month")

ggplot(data = df_m,
       aes(x = month, 
           y = abs(value),
           fill = as.factor(month))) +
  geom_col() +
  facet_grid(cols = vars(variable),
             space = "free_x",
             scales = "free_x",
             switch = "x") +
  # Some graph adjustments:
  scale_y_continuous(expand = c(0, 0)) +  # remove space between plot area and x axis
  labs(x = "Year", y = "Climate variable") +
  scale_fill_discrete(name = "Months") + # legend title
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    panel.grid = element_blank(),
    panel.spacing = unit(0.1, "cm")  # adjust spacing between facets
  )

在此处输入图像描述

希望这也有帮助。


推荐阅读