首页 > 解决方案 > R geom_bar:按组可视化单个大小和总大小

问题描述

所以我想制作一个条形图来按组可视化个人大小和总大小。

为了按组分隔值,我使用了Position = 'dodge'. 为了绘制总大小,我使用了stat = 'identity'. 为了可视化个人大小,我使用了aes(color='black').

这三个似乎不能一起工作。

# make fake data
t1 = tibble(type = c('a', 'b', 'c', 'a', 'a'), Quantity = c(100, 200, 150, 50, 75), fill=c('1','1','1','2','2'))

# no dodge, correctly stacked
p1 = ggplot(t1) + 
  geom_bar(aes(type, Quantity, fill=fill, color='black'), 
           stat='identity', alpha=0.5) +
  scale_color_manual(values='black', guide=FALSE)

# with dodge, overlap in same group
p2 = ggplot(t1) + 
  geom_bar(aes(type, Quantity, fill=fill, color='black'), 
           stat='identity', alpha=0.5, position='dodge') +
  scale_color_manual(values='black', guide=FALSE)

p1 / p2

绘图示例

这个例子是根据2017年发的这篇帖子修改的。在帖子中,解决方案是合并同一组的数据点。但在我的情况下,如果合并数据,将没有信息来绘制单个大小。既然是 2021 年,还有其他解决方案吗?

标签: rggplot2colorspositiongeom-bar

解决方案


您应该先计算总数并尝试绘制。例如,此代码生成以下图。我不确定是否fill需要列

t1 = tibble(type = c('a', 'b', 'c', 'a', 'a'), Quantity = c(100, 200, 150, 50, 75))
p2 = t1 %>% 
    group_by(type) %>% 
    mutate(total = sum(Quantity)) %>% 
    pivot_longer(-type) %>% 
    ggplot() + 
    geom_bar(aes(type, value, fill=name, color='black'), 
             stat='identity', alpha=0.5, position='dodge') +
    scale_color_manual(values='black', guide=FALSE)

在此处输入图像描述


推荐阅读