R 在geom_文本中,can";标签=比例::百分比“;四舍五入?
我正在制作一系列条形图,其中百分比值位于每个条形图上方。我想把它四舍五入到小数点后0位,但它默认为小数点后1位。下面是一个使用mtcars的示例R 在geom_文本中,can";标签=比例::百分比“;四舍五入?,r,ggplot2,R,Ggplot2,我正在制作一系列条形图,其中百分比值位于每个条形图上方。我想把它四舍五入到小数点后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(
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)
库(ggplot2)
图书馆(比例尺)
d以下是对当前代码的最小更改,可以实现您想要的功能:
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)
当我必须在6个月后回顾这一点时,我会更容易弄清楚我做了什么。我处理了同样的问题,并通过在scales::percent()
中添加精度=1L
解决了它,它工作得非常完美:
label = scales::percent(round((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..],
2),
accuracy = 1L))
显然,scales::percent()
已经失效。对此答案的更新是scales::label_percent(准确度=1L)
label = scales::percent(round((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..],
2),
accuracy = 1L))