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

标签 r ggplot2 geom-bar geom-text

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

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

  p + geom_text(data=Data, aes(x=factor(""),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 于 2021 年 1 月 9 日创建(v0.3.0)

关于R:在堆栈栏上显示字符或类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65637781/

相关文章:

删除置信区间虚线并修改图例

r - 绘制表格和连接它们的箭头

r - 填充缺失值

r - ggplot : How to retrieve values for axis labels?

r - 如何按其中一行的子集的平均值对数据框进行排序?

R:使用 geom_text 在条形图上添加观察数量

在构面内重新排序分组条形图

r - ggplot : change the order of stacked bars based on the a name within the bar

r - ggplot2 中堆叠框的直方图

r - 条形 geom_bar 之间的不同空间