繁体   English   中英

ggplot2 barplot - 在堆叠条形图中添加百分比标签但保留 y 轴上的计数

[英]ggplot2 barplot - adding percentage labels inside the stacked bars but retaining counts on the y-axis

我创建了一个带有变量计数的堆叠条形图。 我想将这些保留为计数,以便不同的条形大小代表不同的组大小。 但是,在条形图中,我想添加显示每个堆栈比例的标签 - 以百分比表示。

我设法为每个组创建了计数的堆叠图。 我还创建了标签,并且它们放置正确。 我挣扎的是如何计算那里的百分比?

我试过这个,但我收到一个错误:

dataex <- iris %>%
  dplyr::group_by(group, Species) %>%
  dplyr::summarise(N = n())
names(dataex)

dataex <- as.data.frame(dataex)
str(dataex)

ggplot(dataex, aes(x = group, y = N, fill = factor(Species))) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label = ifelse((..count..)==0,"",scales::percent((..count..)/sum(..count..)))), position = position_stack(vjust = 0.5), size = 3) +
  theme_pubclean()

(count) == 0 中的错误:比较 (1) 仅适用于原子和列表类型

想要的结果:

在此处输入图片说明

好吧,刚刚找到答案......或解决方法。 也许这会对将来的某人有所帮助:在 ggplot 之前计算百分比,然后只需将该向量用作标签。

dataex <- iris %>%
  dplyr::group_by(group, Species) %>%
  dplyr::summarise(N = n()) %>%
  dplyr::mutate(pct = paste0((round(N/sum(N)*100, 2))," %")) 
names(dataex)

dataex <- as.data.frame(dataex)
str(dataex)

ggplot(dataex, aes(x = group, y = N, fill = factor(Species))) +
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label = dataex$pct), position = position_stack(vjust = 0.5), size = 3) +
  theme_pubclean()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM