我正在制作一系列条形图,其中百分比值位于每个条形图上方.我想把它舍入到0位小数,但默认为小数点后1位.这是使用mtcars的示例.
library(ggplot2)
library(scales)
d <- mtcars
g <- ggplot(d, aes(gear)) +
geom_bar(aes(y = (..count..)/sum(..count..), fill=factor(..x..)), stat= "count")+
geom_text(aes(label = scales::percent((..count..)/sum(..count..)),
y= ((..count..)/sum(..count..))), stat="count",
vjust = -.25)
Run Code Online (Sandbox Code Playgroud)
有没有办法将它们舍入到最接近的整数,这样条形标记为47%,38%和16%?
解决方法可能包括手动注释标签或生成摘要data.frame,从中拉出标签.但是,由于我生成了大量的表,我更倾向于在单个ggplot命令中包含我的所有代码.
这是对您当前代码的最小更改,它将执行您想要的操作:
library(ggplot2)
library(scales)
d <- mtcars
g <- ggplot(d, aes(gear)) +
geom_bar(aes(y = (..count..)/sum(..count..), fill=factor(..x..)), stat= "count")+
geom_text(aes(label = scales::percent(round((..count..)/sum(..count..),2)),
y= ((..count..)/sum(..count..))), stat="count",
vjust = -.25)
Run Code Online (Sandbox Code Playgroud)
我已经round(...,2)在你的部门中添加了一个调用,它会在传递之前对比率进行四舍五入percent.
就个人而言,为了清晰的代码,我会在ggplot之外执行此操作.
library(ggplot2)
library(scales)
library(dplyr)
d <- mtcars %>%
group_by(gear) %>%
summarise(Count = n()) %>%
mutate( gear = factor(gear),
Ratio = Count / sum(Count),
label = percent(Ratio %>% round(2)))
g <- ggplot(d, aes(x=gear,y=Ratio,label=label,fill=gear)) +
geom_bar(stat='identity') +
geom_text(vjust=0)
g
Run Code Online (Sandbox Code Playgroud)
当我必须在6个月内回顾并查看它时,弄清楚我做了什么将会容易得多.
我处理了同样的问题,并通过添加解决它accuracy = 1L在scales::percent()它完美地工作:
label = scales::percent(round((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..],
2),
accuracy = 1L))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11607 次 |
| 最近记录: |