Dan*_*iel 4 label r bar-chart ggplot2
背景:我是 R 和 ggplot2 的新手,希望得到一个简单的答案,在相同的情况下可以让其他人受益。
问题:在 ggplot2 中使每个条形加起来为 100% 并在每个条形内显示百分比标签的简单方法是什么?
目标: 我想要的样子(每列总计 100%,每列内带有百分比标签)。
当前图表:这是我目前的条形图;基于“mtcars”数据集(它目前的样子)。下面我有“当前图表”:
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.
Run Code Online (Sandbox Code Playgroud)
提前谢谢了!
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")
Run Code Online (Sandbox Code Playgroud)
您的代码几乎就在那里,只是需要_fill而不是_stack就位。
小智 5
我知道已经晚了,但发布这个是因为我也经常寻找这个......你需要:
# Get labels
percentData <- mtcars %>% group_by(cyl) %>% count(am) %>%
mutate(ratio=scales::percent(n/sum(n)))
Run Code Online (Sandbox Code Playgroud)
计算每个条形内的比例,然后绘制:
# Plot
ggplot(mtcars,aes(x=factor(cyl),fill=factor(am)))+
geom_bar(position="fill")+
geom_text(data=percentData, aes(y=n,label=ratio),
position=position_fill(vjust=0.5))
Run Code Online (Sandbox Code Playgroud)
ggplot(mtcars, aes(x=factor(cyl), fill = factor(am))) +
geom_bar(position = "fill")
Run Code Online (Sandbox Code Playgroud)