首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ggplot2绘制堆叠条形图

使用ggplot2绘制堆叠条形图
EN

Stack Overflow用户
提问于 2021-08-13 15:21:17
回答 2查看 41关注 0票数 0

我有一个这种形式的R数据帧:(第一,第二,...是行名;A,B,...是列名称)

代码语言:javascript
复制
              A   B   C    D  E
 first        30  0   0    0  0
 second       0   20  120  0  0
 third        0   40  100  0  0
 fourth       0   0   0    30 60

我希望ggplot()用x轴上的行名和y轴上的行和绘制一个条形图,这些行和应该按列头类别进行颜色堆叠,并带有数字标签,因此对于上面的数据如下所示:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-13 15:54:18

您应该将行名作为变量添加到您的数据框中,并将您的数据转换为长格式,以便ggplot可以处理它。像这样的东西很接近你的意思,我认为:

代码语言:javascript
复制
yourDataFrame %>% 
    mutate(Label = rownames(df)) %>% # add row names as a variable
    reshape2::melt(.) %>% # melt to long format
    ggplot(., aes(x = Label, y = value, fill = variable)) + 
        geom_bar(stat='identity')
票数 1
EN

Stack Overflow用户

发布于 2021-08-13 15:54:58

我想你要找的东西是这样的:

代码语言:javascript
复制
df %>%
  rownames_to_column(var = 'x') %>%
  pivot_longer(-x) %>%
  filter(value > 0) %>% 
  mutate(x = factor(x, levels = c('first', 'second', 'third', 'forth'))) %>% 
  ggplot(aes(fill = forcats::fct_rev(name), y = value, x = x, label = value)) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label=value)) +
  theme(legend.title = element_blank())

数据:

代码语言:javascript
复制
structure(list(A = c(30L, 0L, 0L, 0L), B = c(0L, 20L, 40L, 0L
), C = c(0L, 120L, 100L, 0L), D = c(0L, 0L, 0L, 30L), E = c(0L, 
0L, 0L, 60L)), class = "data.frame", row.names = c("first", "second", 
"third", "forth")) -> df
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68774806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档