![](/img/trans.png)
[英]R: ggplot stacked bar chart with counts on y axis but percentage as label
[英]Stacked bar chart in R (ggplot2) with y axis and bars as percentage of counts
我是 ggplot2 的新手,有一個關於生成堆積條形圖的問題。 我查看了這本書和專用網頁,但無法解決問題。 我有兩個因素,其中一個有 2 個級別(存在 - 不存在),其他 10 個級別。 讓我們稱這兩個為“變量”和“水果”。
我想創建一個堆疊條形圖,其中每個條形反映一種水果,並且“變量”中存在-不存在觀察的數量彼此堆疊。 這相對容易(請參閱下面圖 1 的代碼),但我還希望條形和 y 軸將“變量”中存在-不存在的計數表示為百分比。 換句話說,所有條形都應具有相同的高度(反映總數為 100%),並且存在與不存在觀察的計數應轉換為百分比。
我可以使用 ..count..*100/sum(..count..) 將 y 軸比例更改為百分比,但我無法理解如何轉換實際條形。 我創建了另一個帶有分面的圖(下面圖 2 的代碼),它在百分比方面達到了我想要的效果,但我更喜歡兩個條形圖。 有沒有人知道如何實現這一目標? 我提供了虛擬數據和可重復的示例。 謝謝你的幫助。
史蒂夫
dat <- data.frame( fruit=c("Apple", "Apple", "Orange", "Orange", "Orange", "Orange",
"Orange", "Pear", "Pear", "Pear"), variable=c("Present", "Absent",
"Present", "Present", "Present", "Present", "Absent", "Absent",
"Absent", "Present") )
# stacked bar plot
ggplot(dat, aes(x = fruit, fill = variable) ) +
geom_bar( aes(y = ..count..*100/sum(..count..) ) ) +
xlab("Fruit") +
ylab("Would like this to be percentage") +
scale_fill_manual("Condition", values = alpha( c("firebrick", "dodgerblue4"), 1) )
# with faceting
ggplot(dat, aes(x = variable, fill = variable) ) +
geom_bar( aes(y = ..count..*100/sum(..count..) ) ) +
facet_grid(. ~ fruit) +
xlab("Fruit") +
ylab("Would like this to be percentage") +
scale_fill_manual("Condition", values = alpha( c("firebrick", "dodgerblue4"), 1) )
對於第一個圖形,只需將 position = 'fill' 添加到您的 geom_bar 線! 您實際上不需要縮放計數,因為 ggplot 有一種方法可以自動執行此操作。
ggplot(dat, aes(x = fruit)) + geom_bar(aes(fill = variable), position = 'fill')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.