背景: 我是 R 和 ggplot2 的新手,希望得到一个简单的答案,在相同情况下对其他人有益。
问题: 在 ggplot2 中使 每个条形添加 到 100% 并在每个条形内显示 百分比标签 的简单方法是什么?
目标: What I want it to look like(每列总计 100%,每列内带有百分比标签)。
当前图表: 这是我目前的条形图;基于“mtcars”数据集(What it currently looks like)。
下面我有“当前图表”:
library(ggplot2) # loads ggplot2
data <- mtcars # gets the mtcars dataset
#INFO: A simple barchart with X-axis being Nr of Cylinders, fill color indicating whether or not the car model has an Automatic gearbox..
# ..and Y-axis showing the count of cars by Nr of Cylinders
ggplot(mtcars, aes(x=cyl, fill = factor(am))) +
geom_bar() +
stat_count(geom = "text",
aes(label = paste(round((..count..)/sum(..count..)*100), "%")), # This row calculates the percentage across all data, adding up to 100%, but I want it to add up to 100% per X-variable (Nr of Cylinders = 4, 6, 8)
position=position_stack(vjust=0.5), colour="white") # This row positions the bar percentage level and colors it white.
提前谢谢了!
最佳答案
library(ggplot2) # loads ggplot2
data <- mtcars
ggplot(mtcars, aes(x=cyl, fill = factor(am))) +
geom_bar(position = "fill") +
stat_count(geom = "text",
aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
position=position_fill(vjust=0.5), colour="white")
您的代码几乎就在那里,只需要
_fill
而不是 _stack
就位。关于r - ggplot2 堆积条形图 - 每个条形图均为 100%,每个条形图内都有百分比标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305490/