从R:中的scale :: percent()中删除百分号

问题描述 投票:0回答:2

这是我的代码。

my_boxplot <- ggplot(mtcars,aes(x=as.factor(cyl),y=mpg)) + 
  geom_boxplot(aes(fill=cyl,color=cyl)) + xlab('Cylinders') + ylab('Miles per Gallon %')+
  scale_y_continuous(labels = function(x) scales::percent(x, accuracy = 0.01))
my_boxplot

此代码将y轴显示为百分比,我想将精度保持在小数点后两位,并删除百分号。

我也尝试过。它仅删除百分号,但不设置准确性。

scale_y_continuous(labels=function(x) paste0(x*100))有人知道如何将精度保持在所需的小数位并从百分比值中删除百分比符号吗?感谢您的帮助!

r percentage floating-accuracy
2个回答
0
投票

您可以定义一个函数,并将所有格式放入其中。放入scales::percent后,您可以使用str_extract仅提取数字。这应该做您想要的。

library(tidyverse)

my_format <- function(l) {
  l <- scales::percent(l, accuracy = .01)
  l <-str_extract(l,'[ 0-9.]+')
}


ggplot(mtcars,aes(x=as.factor(cyl),y=mpg)) + 
  geom_boxplot(aes(fill=cyl,color=cyl)) + xlab('Cylinders') + ylab('Miles per Gallon %')+
  scale_y_continuous(labels = my_format)

“”

reprex package(v0.3.0)在2020-06-13创建


0
投票

尝试:

my_boxplot <- ggplot(mtcars,aes(x=as.factor(cyl),y=mpg)) + 
  geom_boxplot(aes(fill=cyl,color=cyl)) + xlab('Cylinders') + ylab('Miles per Gallon %')+
  scale_y_continuous(labels = function(x) format(x, digits=2, nsmall=2))
my_boxplot

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.