簡體   English   中英

每個欄的寬度不同,在ggplot2中使用geom_bar和“position = fill”

[英]different width for each bar, using geom_bar with “position=fill” in ggplot2

你能告訴我是否可以制作條形高度標准化為1的條形圖,但是條形寬度與每個區域中的元素數量成比例。

示例:此圖

ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) + geom_bar(position="fill")

然后使3個條的寬度成比例

table(factor(mtcars$cyl))

在position_fill()中有“width”參數,但它必須是常量,不是嗎?

謝謝,

弗朗索瓦

編輯:

我試了一下,得到消息:“position_fill需要恆定的寬度”

所以我想要得到我想要的東西是不可能的,至少使用geom_bar。

我可以通過預處理數據來完成,但不是完全在單個ggplot調用中。

library("plyr")
mt <- ddply(mtcars, .(cyl, vs), summarise, n=length(cyl))
mt <- ddply(mt, .(cyl), mutate, nfrac = n/sum(n), width = sum(n))
mt$width <- mt$width / max(mt$width)

mt數據集現在具有制作繪圖所需的一切:

> mt
  cyl vs  n      nfrac     width
1   4  0  1 0.09090909 0.7857143
2   4  1 10 0.90909091 0.7857143
3   6  0  3 0.42857143 0.5000000
4   6  1  4 0.57142857 0.5000000
5   8  0 14 1.00000000 1.0000000

並且ggplot調用看起來像

ggplot(mt, aes(x=factor(cyl), fill=factor(vs), y=nfrac)) +
  geom_bar(aes(width=width), position="stack", stat="identity")

它確實拋出警告:

Warning message:
position_stack requires constant width: output may be incorrect 

但創造了情節:

在此輸入圖像描述

這是你想要的嗎?

library(ggplot2)
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) + geom_bar(position="fill") + coord_flip()

在此輸入圖像描述

暫無
暫無

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

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