收集行并在dplyr中绘制堆叠条形图

收集行并在dplyr中绘制堆叠条形图,r,dplyr,R,Dplyr,我有一个数据框架,我想每年(2010-2019年)收集每一行数据。由此,我想做一个堆叠的条形图,每一个堆叠在每一年都是一种感悟 #Take all rows and bind them together. y <- rbind(nrc2010,nrc2011,nrc2012,nrc2013,nrc2014,nrc2015,nrc2016,nrc2017,nrc2018,nrc2019) #Looks like this structure(list(anger = c(273, 334,

我有一个数据框架,我想每年(2010-2019年)收集每一行数据。由此,我想做一个堆叠的条形图,每一个堆叠在每一年都是一种感悟

#Take all rows and bind them together.
y <- rbind(nrc2010,nrc2011,nrc2012,nrc2013,nrc2014,nrc2015,nrc2016,nrc2017,nrc2018,nrc2019)

#Looks like this
structure(list(anger = c(273, 334, 235, 498, 442, 750, 316, 490, 
326, 419), anticipation = c(518, 580, 522, 959, 806, 1164, 535, 
756, 386, 797), disgust = c(199, 202, 132, 354, 281, 459, 178, 
282, 175, 289), fear = c(405, 467, 372, 1042, 831, 1202, 540, 
848, 477, 799), joy = c(302, 324, 300, 498, 470, 758, 355, 494, 
242, 573), negative = c(703, 690, 540, 1296, 1076, 1549, 697, 
1060, 629, 994), positive = c(1205, 1364, 1126, 2317, 1974, 3048, 
1318, 2007, 921, 1918), sadness = c(291, 264, 210, 523, 380, 
607, 298, 461, 280, 376), surprise = c(174, 182, 173, 337, 312, 
466, 270, 476, 199, 407), trust = c(836, 958, 729, 1311, 1334, 
1979, 856, 1356, 562, 1225)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))
#获取所有行并将它们绑定在一起。
y%
排列(描述(计数))

因此,从这个新表中,创建一个堆叠的条形图,x轴是年份,y轴是计数,条形图中的每个堆叠都是一个每年的情绪,用图例表示填充。

我们可以使用
mget
将所有数据集放入
列表中,然后用
bind_rows
绑定行,同时从
列表的
名称
创建一个“年”列,然后用
pivot_longer
重塑为“长”格式,并使用
ggplot
绘制条形图

library(dplyr)
library(tidyr)
library(stringr)
library(ggplot2)
mget(ls(pattern = '^nrc\\d{4}$')) %>%
   bind_rows(.id = 'year') %>% 
   mutate(year = str_remove(year, '^nrc')) %>% 
   pivot_longer(cols = -year, names_to = 'sentiment', values_to = 'count') %>%  
   arrange(desc(count)) %>% 
   ggplot(aes(x = year, y = count, fill = sentiment)) +
           geom_bar(colour = 'black', stat = 'identity')

@JohnnyThomas我更改了密码,你现在可以检查一下吗好的,太好了!x轴应该是年,而不是之前的“nrc”。此外,您是否有任何颜色主题可以更好地区分堆栈。也许是轮廓?@johnythomas我用
str\u remove
删除了前缀,太棒了!!!紫色-粉红色-品红色相互融合,有没有办法在每个街区周围放置盒子?我尝试了color=“black”,结果它们都变成了红色。@johnythomas将其更改为
geom\u bar
,因为它与
geom\u col
library(dplyr)
library(tidyr)
library(stringr)
library(ggplot2)
mget(ls(pattern = '^nrc\\d{4}$')) %>%
   bind_rows(.id = 'year') %>% 
   mutate(year = str_remove(year, '^nrc')) %>% 
   pivot_longer(cols = -year, names_to = 'sentiment', values_to = 'count') %>%  
   arrange(desc(count)) %>% 
   ggplot(aes(x = year, y = count, fill = sentiment)) +
           geom_bar(colour = 'black', stat = 'identity')