我正在尝试将类别和百分比添加到堆栈栏中的每个级别,例如:
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))
这会产生这个图表:
但是我尝试使用此命令获取此图表,但失败了
预期图表
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/