Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在geom_文本中,can";标签=比例::百分比“;四舍五入?_R_Ggplot2 - Fatal编程技术网

R 在geom_文本中,can";标签=比例::百分比“;四舍五入?

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(

我正在制作一系列条形图,其中百分比值位于每个条形图上方。我想把它四舍五入到小数点后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)
库(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))