簡體   English   中英

根據ggplot2中的類別比例調整(堆疊)條形寬度

[英]Adjusting (Stacked) Bar Width according to Proportions of Categories in ggplot2

我正在嘗試根據類別的計數(或比例)更改我的(堆積)條寬度。例如,我使用鑽石數據集。 我希望根據每個類別(變量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並且顯然不考慮酒吧寬度的類別比例,任何可以幫助我的人? 謝謝!

我覺得這很有效。 從你離開的地方開始......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM