【问题标题】:creating stacked bar chart in r在r中创建堆积条形图
【发布时间】:2017-10-13 07:59:33
【问题描述】:

我真的很难在 R 中创建堆叠条形图。我是一个初学者,所以即使查看其他示例,我也无法找到正确的解决方案。 这是我的数据的样子:

         gdp_2      def_2      pcom_2      ff_2       nbr_2        tr_2    unemp_2
[1,] 0.02938106 0.01009107 0.014915879 0.9456120 0.000000000 0.000000000 0.00000000
[2,] 0.04824422 0.02513049 0.016115796 0.8303659 0.002320698 0.001255257 0.07656760
[3,] 0.06532489 0.05206917 0.011290059 0.7623530 0.002604175 0.008032572 0.09832613
[4,] 0.07485907 0.07576441 0.009215843 0.7064166 0.003207812 0.008397380 0.12213887
[5,] 0.07894689 0.10131343 0.007674296 0.6635104 0.003415185 0.009705830 0.13543392

左侧的数字 1 到 5 表示时间范围。所以我想为每个时间范围堆叠变量 gdp_2、def_2、pcom_2、ff_2、nbr_2、tr_2 和 unemp_2 的所有值。

这应该看起来像这样

当然,有一个好的图例会很好,但目前我什至不知道如何创建堆积条形图。 顺便说一下,对于那些对这个话题感兴趣的人:它是美国经济变量的预测误差方差分解。

我已经提前非常感谢你! 最好的, 黎哥

【问题讨论】:

标签: r bar-chart stacked-area-chart


【解决方案1】:

使用ggplot2dplyrtidyrtidyverse 的所有部分)...

library(tidyverse)

chart <- df %>% mutate(year=1:n()) %>% #add year as a column to your df
  gather(key=colname,value=value,-year) %>% #convert to long format
  ggplot(aes(x=year,y=value,fill=colname)) + #send to ggplot
  geom_bar(stat="identity",position="stack") #draw stacked bar

print(chart)

【讨论】:

  • 亲爱的 Andew Gustar 非常感谢您的回答。在您的示例中,它看起来很完美!这正是我想要的。但是,当我尝试使用自己的数据执行此操作时,我收到错误消息: UseMethod("mutate_") 中的错误:没有适用于 'mutate_' 的方法应用于类 "c('matrix', 'double' , '数字')"
  • 亲爱的@Andrew Gustar 非常感谢,我只需要更改我的数据,它是一个数据框,现在它工作得很好!!!非常感谢您的帮助!
  • 这就是我要建议的!很高兴你把它整理好了。
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 2013-12-19
相关资源
最近更新 更多