I am really struggeling with creating a stacked bar chart in R. I am quite a beginner so even with looking at other examples I couldn't get to the right solution. Here is how my data looks like:
我真的很想在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
The numbers 1 to 5 on the left hand side indicate time horizons. So I would like to stack for each time horizon all the values for the variables gdp_2, def_2, pcom_2, ff_2, nbr_2, tr_2 and unemp_2.
左侧的数字1到5表示时间范围。所以我想为每个时间范围堆叠变量gdp_2,def_2,pcom_2,ff_2,nbr_2,tr_2和unemp_2的所有值。
This should look kind of like this
这看起来应该是这样的
Of course it would be nice to have a nice legend but at the moment I really do not even know how to create the stacked bar chart. By the way, for those interested in the topic: It is a forecast error variance decomposition of economic variables of the US.
当然,拥有一个不错的传奇会很好,但目前我甚至不知道如何创建堆积条形图。顺便说一句,对于那些对该主题感兴趣的人:它是美国经济变量的预测误差方差分解。
I thank you so much already in advance! Best, Rico
我已经提前感谢你了!最好的,Rico
1 个解决方案
#1
2
Using ggplot2
, dplyr
and tidyr
(all parts of tidyverse
)...
使用ggplot2,dplyr和tidyr(tidyverse的所有部分)......
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)
#1
2
Using ggplot2
, dplyr
and tidyr
(all parts of tidyverse
)...
使用ggplot2,dplyr和tidyr(tidyverse的所有部分)......
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)