R - ggplot轴标签数字格式 - 去除前导零

3

如何在 R ggplot geom_bar 的坐标轴上删除前导零的选项/代码是什么?

例如,我想将0.05显示为.05。

我能找到的只有内置的格式,如百分比、逗号等。

谢谢!


3
需要在某个时候将其强制转换为字符值,因此请使用sub("^0", "", vec)进行操作。 - IRTFM
我想知道你是否可以使用scales()包创建自定义格式。我已经用它来创建百分比或其他格式,并设置了我喜欢的小数位数。然后,您可以在任何地方使用它,例如图表、表格、标签等。 - Mark Neal
2个回答

3

受 m.evans 的回答启发,可以使用 stringr 包轻松地实现删除前导零的简单替代方案。

library(stringr)

dropLeadingZero <- function(l){
  str_replace(l, '0(?=.)', '')
}

ggplot(data=iris, aes(x=Petal.Width, y = Sepal.Length))+
  geom_bar(stat = "identity")+
  scale_x_continuous(breaks = seq(0,2.5, by = 0.5), 
                     labels = dropLeadingZero)

2
你可以编写一个函数,将其调用到绘图的 labels 部分中:
#create reprex
data(iris)
library(ggplot2)

#write the function
dropLeadingZero <- function(l){
  lnew <- c()
  for(i in l){
    if(i==0){ #zeros stay zero
      lnew <- c(lnew,"0")
    } else if (i>1){ #above one stays the same
      lnew <- c(lnew, as.character(i))
    } else
      lnew <- c(lnew, gsub("(?<![0-9])0+", "", i, perl = TRUE))
  }
  as.character(lnew)
}

您可以在ggplot调用中使用此命令。例如:
ggplot(data=iris, aes(x=Petal.Width, y = Sepal.Length))+
  geom_bar(stat = "identity")+
  scale_x_continuous(breaks = seq(0,2.5, by = 0.5), 
                     labels = dropLeadingZero)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接