【问题标题】:R geom_bar: Visualize both individual size and total size by groupsR geom_bar:按组可视化单个大小和总大小
【发布时间】:2021-05-25 13:39:43
【问题描述】:

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

为了按组分隔值,我使用了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

plot example

这个例子是从2017年发布的post修改而来的。在帖子中,解决方案是合并同一组的数据点。但在我的情况下,如果合并数据,将没有信息来绘制单个大小。既然是 2021 年,有没有别的解决办法?

【问题讨论】:

    标签: r ggplot2 colors position geom-bar


    【解决方案1】:

    您应该先计算总数并尝试绘制。例如,此代码生成以下图。我不确定是否需要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)
    

    【讨论】:

    • 感谢您的快速回复!如果您查看类型 - a 中的数量(红色)组,您会发现它们重叠。它们可以堆叠在一起,每个周围都有黑色轮廓吗?
    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多