R:在堆栈栏上显示字符或类别

问题描述

我正在尝试将类别和百分比添加到堆栈栏中的每个级别,例如:

Category  <- c(rep(c("A","B","C","D"),times = 4))
Data      <- data.frame( Category)

p= ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
  geom_bar(position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))),stat='count',position=position_fill(vjust=0.5))

这产生了这个图:

stack bar result

但是我试图用这个命令得到这个图形,但我失败了

预期图形

Graph expected

p=ggplot(Data,position=position_fill(vjust=0.5))

  p + geom_text(data=Data,label = Category),position=position_fill(vjust=0.5))

解决方法

您在获得所需文本的过程中进展顺利,我认为如果您添加 stat = "count" 并稍微调整 vjust,您会得到您想要的。

library(ggplot2)
Category  <- c(rep(c("A","B","C","D"),times = 4))
Data      <- data.frame( Category)

ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
  geom_bar(position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))),stat='count',position=position_fill(vjust=0.5)) +
  geom_text(aes(label = Category),fontface = "bold",stat = "count",position = position_fill(vjust = 0.25))

reprex package (v0.3.0) 于 2021 年 1 月 9 日创建

,

实现预期结果的另一种选择是使用 ggtext::geom_richtext 和一些 glue

library(ggplot2)

Year      <- c(rep(c("2006-07","2007-08","2008-09","2009-10"),each = 4))
Category  <- c(rep(c("A",times = 4))
Frequency <- c(168,259,226,340,216,431,319,368,423,645,234,685,166,467,274,251)
Data      <- data.frame(Year,Category,Frequency)

my_lab <- function(x,y) {
  glue::glue("{scales::percent(x / sum(x))}<br><br><b>{y}</b>")
}

ggplot(Data,fill=factor(Category)))+
  geom_bar(position="fill")+
  ggtext::geom_richtext(aes(label = my_lab(..count..,..fill..)),label.color = NA,position=position_fill(vjust=0.5))