简体   繁体   English

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

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

I have created an stacked barplot with the counts of a variables.我创建了一个带有变量计数的堆叠条形图。 I want to keep these as counts, so that the different bar sizes represent different group sizes.我想将这些保留为计数,以便不同的条形大小代表不同的组大小。 However, inside the bar plot i would like to add labels that show the proportion of each stack - in terms of percentage.但是,在条形图中,我想添加显示每个堆栈比例的标签 - 以百分比表示。

I managed to create the stacked plot of count for every group.我设法为每个组创建了计数的堆叠图。 Also I have created the labels and they are are placed correctly.我还创建了标签,并且它们放置正确。 What i struggle with is how to calculate the percentage there?我挣扎的是如何计算那里的百分比?

I have tried this, but i get an error:我试过这个,但我收到一个错误:

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()

Error in (count) == 0 : comparison (1) is possible only for atomic and list types (count) == 0 中的错误:比较 (1) 仅适用于原子和列表类型

desired result:想要的结果:

在此处输入图片说明

well, just found answer ... or workaround.好吧,刚刚找到答案......或解决方法。 Maybe this will help someone in the future: calculate the percentage before the ggplot and then just just use that vector as labels.也许这会对将来的某人有所帮助:在 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