【问题标题】:Adjusting (Stacked) Bar Width according to Proportions of Categories in ggplot2根据ggplot2中的类别比例调整(堆叠)条形宽度
【发布时间】:2018-04-23 16:37:26
【问题描述】:

我正在尝试根据类别的计数(或比例)更改我的(堆叠的)条形宽度,例如,我使用了 diamonds 数据集。我想根据每个类别的频率(变量cut)查看不同的宽度。我首先创建了一个变量cut_prop,然后用下面的代码进行绘制

library(tidyverse)

cut_prop = diamonds %>% 
  group_by(cut) %>% 
  summarise(cut_prop = n()/nrow(diamonds))

diamonds = left_join(diamonds, cut_prop)

ggplot(data = diamonds, 
       aes(x = cut, fill = color)) + 
  geom_bar(aes(width=cut_prop), position = "fill") + 
  theme_minimal() +
  coord_flip()

这给了我以下条形图:

R 发出警告,提示:Ignoring unknown aesthetics: width 并且显然没有考虑条形宽度的类别比例,有人可以在这里帮助我吗?谢谢!

【问题讨论】:

标签: r ggplot2 width bar-chart


【解决方案1】:

我认为这行得通。从你离开的地方开始......

df <- diamonds %>% 
  count(cut, color, cut_prop) %>% 
  group_by(cut) %>% 
  mutate(freq = n / sum(n)) %>% 
  ungroup

ggplot(data = df,
       aes(x = cut, fill = color, y = freq, width = cut_prop)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  coord_flip()

基本上,我自己计算比例而不是使用position = "fill",然后使用stat = identity而不是stat = count

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多