如何在 R ggplot geom_bar 的坐标轴上删除前导零的选项/代码是什么?
例如,我想将0.05显示为.05。
我能找到的只有内置的格式,如百分比、逗号等。
谢谢!
受 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)
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)
sub("^0", "", vec)
进行操作。 - IRTFM