我需要在 R 的条形图条形上显示百分比值。
此代码绘制分类数据,类别在 x 上,% 在 y 上。如何修改它,使其在条形本身上显示百分比,而不仅仅是在 y 轴上?
ggplot(data = iris) +
geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
scale_y_continuous(labels = percent)
ggplot 中的..count..
帮助程序可能适用于简单情况,但通常最好先在适当的级别聚合数据,而不是在 ggplot 调用中聚合数据:
library(tidyverse)
library(scales)
irisNew <- iris %>% group_by(Species) %>%
summarize(count = n()) %>% # count records by species
mutate(pct = count/sum(count)) # find percent of total
ggplot(irisNew, aes(Species, pct, fill = Species)) +
geom_bar(stat='identity') +
geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
scale_y_continuous(labels = scales::percent)
vjust = .5
使每个条形中的标签居中
ggplot(data = iris, aes(x = factor(Species), fill = factor(Species))) +
geom_bar(aes(y = (..count..)/sum(..count..)),
position = "dodge") +
geom_text(aes(y = (..count..)/sum(..count..),
label = paste0(prop.table(..count..) * 100, '%')),
stat = 'count',
position = position_dodge(.9),
size = 3)+
labs(x = 'Species', y = 'Percent', fill = 'Species')