【问题标题】:R : Bar plot for time series of data corresponding to 12 months of 15 yearsR:对应于 15 年的 12 个月的数据时间序列的条形图
【发布时间】:2018-12-27 17:15:04
【问题描述】:

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

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)))

但它不起作用。有什么建议吗?

【问题讨论】:

  • 发布的问题似乎根本不包括任何解决问题的尝试。 StackOverflow 希望您首先尝试解决自己的问题,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以便在最小、完整和可验证的示例中说明您遇到的特定问题。更多信息请见How to Asktake the tour
  • 我根据您的评论编辑了我的问题!谢谢!
  • meltgroup_by 不是基本 R 函数。请包括所有library 行。

标签: r ggplot2 bar-chart


【解决方案1】:

另一种方法是使用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
  )

希望这也有帮助。

【讨论】:

  • 谢谢瓦伦丁。当我运行你的脚本时,它给出了这个错误:Error in value[[3L]](cond) : The melt generic in data.table has been passed a tbl_df (not a data.table) but the reshape2 package is not installed to process this type. Please either install reshape2 and try again, or pass a data.table to melt instead. &gt;
  • 嗨。使用setDT(your_tbl_df) 将其切换到data.table,如果需要还原,请使用setDF 函数。我也更新了我的答案。
  • 谢谢,错误data.table 已修复。但是,仍然存在这个问题:Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : there is no package called ‘stringr’。当我尝试安装stringr 时,我发现这个错误:Error in library.dynam(lib, package, package.lib) : shared object ‘stringi.so’ not found ERROR: lazy loading failed for package ‘stringr’ * removing ‘/Library/Frameworks/R.framework/Versions/3.3/Resources/library/stringr’ Warning in install.packages : installation of package ‘stringr’ had non-zero exit status
  • 我用这个(来自link)来安装stringrinstall.packages("stringi", dependencies=TRUE, INSTALL_opts = c('--no-lock')) install.packages("stringr", dependencies=TRUE, INSTALL_opts = c('--no-lock')) 安装stringr后它工作得很好!谢谢
【解决方案2】:

您可以融合数据框并根据序列1:180 绘制值。然后您可以为 x 轴分配自定义标签以表示年份。

library(reshape2)
library(ggplot2)

# Create example df with random values
df <- data.frame(month = 1:12, matrix(rnorm(12 * 15), 12))
colnames(df) <- c("month", "Yi","Yi+1", "Yi+2", "Yi+3", "Yi+4", "Yi+5","Yi+6",  "Yi+7", "Yi+8", "Yi+9", "Yi+10","Yi+11","Yi+12","Yi+13","Yi+14")

df_m <- melt(df, "month")

# Prepare labels (at each 6 month for 15 years)
x_labs <- c("Yi","Yi+1", "Yi+2", "Yi+3", "Yi+4", "Yi+5","Yi+6", "Yi+7",
            "Yi+8", "Yi+9", "Yi+10","Yi+11","Yi+12","Yi+13","Yi+14")

ggplot(df_m, aes(x = 1:length(value), y = value, fill=factor(month))) +
    geom_bar(position="dodge", stat="identity") +
    # add custom labels at each 6-th month
    scale_x_continuous(labels = x_labs, breaks = seq(6, 15 * 12 - 6, by = 12)) +
    xlab("year???")

【讨论】:

  • 谢谢@Istrel。问题是我无法安装包reshape2,因为无法安装它的依赖包stringr。当我使用melt (df,"month") 时,我可以只安装reshapereshape 发生此错误:Error in match.names(clabs, names(xi)) : names do not match previous names
  • 抱歉,无法重现您的错误。我试过reshepe 包,代码运行良好。
  • 感谢 Istrel。我尝试了您的随机值,并且您的脚本运行良好。但是我的 data.frame 有这个错误:Error in match.names(clabs, names(xi)) : names do not match previous names
  • 你能发布str(df)输出吗?
  • Classes ‘data.table’ and 'data.frame': 12 obs. of 16 variables: $ Yi : num 0.0143 0.0143 ... $ Yi+1 : num 13.4 15.8 .. $ Yi+2 : num 22.7 23.2 .. $ Yi+3 : num 36.5 37.6 .. $ Yi+4 : num 45.8 45.9 .. $ Yi+5 : num 49.2 49.3 .. $ Yi+6 : num 51.5 51.5 .. $ Yi+7 : num 57.5 57.6 .. $ Yi+8 : num 74.6 75.6 .. $ Yi+9 : num 77.2 77.5 .. $ Yi+10: num 87.1 87.4 .. $ Yi+11: num 89.4 89.7 ... $ Yi+12: num 91.8 91.8 .. $ Yi+13: num 96.1 96.7 .. $ Yi+14: num 99.3 99.3 .. $ month: num 1 2 3 4 5 6 7 ... - attr(*, ".internal.selfref")=&lt;externalptr&gt;
猜你喜欢
  • 2014-12-25
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 2016-02-06
  • 2019-07-30
  • 2017-11-24
相关资源
最近更新 更多