繁体   English   中英

R:ggplot堆叠的条形图,y轴上有计数,但百分比为标签

[英]R: ggplot stacked bar chart with counts on y axis but percentage as label

我正在寻找一种用百分比标记堆积条形图的方法,而y轴显示原始计数(使用ggplot)。 这是不带标签的情节的MWE:

library(ggplot2)
df <- as.data.frame(matrix(nrow = 7, ncol= 3,
                       data = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6", "ID7",
                                "north", "north", "north", "north", "south", "south", "south",
                                "A", "B", "B", "C", "A", "A", "C"),
                      byrow = FALSE))

colnames(df) <- c("ID", "region", "species")

p <- ggplot(df, aes(x = region, fill = species))
p  + geom_bar()

我的桌子要大得多,R很好地统计了每个地区的不同物种。 现在,我想同时显示原始计数值(最好在y轴上)和百分比(作为标签),以比较区域之间物种的比例。

我使用geom_text()尝试了很多东西,但我认为与其他问题( 例如,这个问题geom_text()的主要区别是

  • 我没有单独的列用于y值(它们只是每个区域中不同物种的计数),并且
  • 我需要每个区域的标签总计达100%(因为它们被认为代表了不同的种群),而不是整个图的所有标签。

任何帮助深表感谢!!

如@Gregor所述,分别汇总数据,然后将数据摘要输入ggplot。 在下面的代码中,我们使用dplyr创建摘要:

library(dplyr)

ggplot(df %>% count(region, species) %>%    # Group by region and species, then count number in each group
         mutate(pct=n/sum(n),               # Calculate percent within each region
                ypos = cumsum(n) - 0.5*n),  # Calculate label positions
       aes(region, n, fill=species)) +
  geom_bar(stat="identity") +
  geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%"), y=ypos))

在此处输入图片说明

更新:dplyr 0.5及更高版本中,您不再需要提供y值以使文本在每个小节内居中。 相反,您可以使用position_stack(vjust=0.5)

ggplot(df %>% count(region, species) %>%    # Group by region and species, then count number in each group
         mutate(pct=n/sum(n)),              # Calculate percent within each region
       aes(region, n, fill=species)) +
  geom_bar(stat="identity") +
  geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%")), 
            position=position_stack(vjust=0.5))

我同意Johanna。 您可以尝试:

d <- aggregate(.~region+species, df, length)
d$percent <- paste(round(ID/sum(ID)*100),'%',sep='')
ggplot(d, aes(region, ID, fill=species)) + geom_bar(stat='identity') + 
  geom_text(position='stack', aes(label=paste(round(ID/sum(ID)*100),'%',sep='')), vjust=5)

暂无
暂无

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

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