在ggplot条形图上以R显示百分比

在ggplot条形图上以R显示百分比,r,ggplot2,bar-chart,percentage,R,Ggplot2,Bar Chart,Percentage,我需要在条形图的条形图上以R显示百分比值 此代码绘制类别数据,类别在x上,百分比在y上。如何修改它,使其显示条本身的百分比,而不仅仅是y轴上的百分比 ggplot(data = iris) + geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) + scale_y_continuous(labels = percent) ggplot中的.count..帮助程序适用于

我需要在条形图的条形图上以R显示百分比值

此代码绘制类别数据,类别在x上,百分比在y上。如何修改它,使其显示条本身的百分比,而不仅仅是y轴上的百分比

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)

ggplot中的
.count..
帮助程序适用于简单的情况,但通常最好先在适当的级别聚合数据,而不是在ggplot调用中:

library(tidyverse)
library(scales)

irisNew <- iris %>% group_by(Species) %>% 
 summarize(count = n()) %>%  # count records by species
 mutate(pct = count/sum(count))  # find percent of total

ggplot(irisNew, aes(Species, pct, fill = Species)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
  scale_y_continuous(labels = scales::percent)
库(tidyverse)
图书馆(比例尺)
irisNew%按(物种)分组%>%
汇总(count=n())%>%#按物种统计记录
变异(pct=计数/总和(计数))#找到总数的百分比
ggplot(irisNew、aes(物种、pct、填充=物种))+
几何图形栏(stat='identity')+
几何图形文本(aes(标签=比例::百分比(pct)),位置=位置堆栈(vjust=.5))+
比例y连续(标签=比例::百分比)

vjust=.5
将每个条中的标签居中

ggplot中的
.count..
帮助程序适用于简单情况,但通常最好先将数据聚合到适当的级别,而不是在ggplot调用中:

library(tidyverse)
library(scales)

irisNew <- iris %>% group_by(Species) %>% 
 summarize(count = n()) %>%  # count records by species
 mutate(pct = count/sum(count))  # find percent of total

ggplot(irisNew, aes(Species, pct, fill = Species)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
  scale_y_continuous(labels = scales::percent)
库(tidyverse)
图书馆(比例尺)
irisNew%按(物种)分组%>%
汇总(count=n())%>%#按物种统计记录
变异(pct=计数/总和(计数))#找到总数的百分比
ggplot(irisNew、aes(物种、pct、填充=物种))+
几何图形栏(stat='identity')+
几何图形文本(aes(标签=比例::百分比(pct)),位置=位置堆栈(vjust=.5))+
比例y连续(标签=比例::百分比)

vjust=.5
将每个条中的标签居中

查看轴标签的
scales
包,以及向条中添加文本的
geom_text
。我尝试为文本添加“geom_text(aes(label=paste0(100*(…count..))/sum(…count)),大小=5”,但我遇到了一个错误:总和错误(计数):无效的“type”(完)关于argumentAh,我明白你的意思。你想在条带上文字,对吗?@divibisan是的,没错……编辑了这个问题以澄清这个问题。除了之前作为一个副本发布的问题之外,我还想看看轴标签的
缩放
包,以及用于向条带添加文字的
几何文字
。我已经尝试添加了“geom_text(aes(label=paste0(100*(…count..))/sum(…count..)))、size=5)”用于文本,但我收到一个错误:sum(count)中的错误:无效的“type”(闭包)关于argumentAh,我明白你在说什么。你想要条上的文字,对吗?@divibisan是的,没错……编辑了这个问题以澄清这个问题。除了以前作为dupeI发布的问题之外,我还看到了这个错误:层中的错误(data=data,mapping=mapping,stat=stat,geom=GeomeText,:object“…count…”找不到
表示法在一些版本中被弃用,取而代之的是
stat()
我得到这个错误:层中的错误(data=data,mapping=mapping,stat=stat,geom=GeomText,:object“…count…”找不到
表示法在一些版本中被弃用,取而代之的是
stat()