2017-03-03 115 views
1

对于期刊提交,我被告知我的数字不能有前导零。例如,利用这个情节:删除ggplot2 +标尺中的前导零

df <- data.frame(x = -10:10, y = (-10:10)/10) 

ggplot(df, aes(x, y))+ 
    geom_point() 

enter image description here

y轴有标签

-1.0 -0.5 0.0 0.5 1.0 

我需要制作这些标签:

-1.0 -.5 0  .5 1.0 

我想象我将不得不使用尺度包中的format_format(),但我没有看到vario中的任何内容我们的文件为format,formatCsprintf,它们将产生必要的标签。

+0

似乎更加一致,其中0有小数点“-1.0 -.5 .0 .5 1.0” –

回答

3

我有一个GitHub的包,numform可以做到这一点(我加控制零到基于这个问题f_num功能):

library(devtools) 
library(ggplot2) 
install_github('trinker/numform') 

df <- data.frame(x = -10:10, y = (-10:10)/10) 

ggplot(df, aes(x, y))+ 
    geom_point() + 
    scale_y_continuous(labels = numform::ff_num(zero = 0)) 

enter image description here

2

这将工作:

ggplot(df, aes(x, y))+ 
geom_point()+ 
scale_y_continuous(breaks = c("-1.0" = -1, "-.5"= -0.5, "0" = 0, ".5" = 0.5, "1.0" = 1)) 

plot with desired y axis labels

不幸的是,这需要为每个绘图手动指定格式;我不知道如何自动完成格式化。

4

您可以编写自己的函数:

no_zero <- function(x) { 
    y <- sprintf('%.1f',x) 
    y[x > 0 & x < 1] <- sprintf('.%s',x[x > 0 & x < 1]*10) 
    y[x == 0] <- '0' 
    y[x > -1 & x < 0] <- sprintf('-.%s',x[x > -1 & x < 0]*-10) 
    y 
} 

然后剧情:

ggplot(df, aes(x, y))+ 
    geom_point() + 
    scale_y_continuous(labels = no_zero) 

这给期望的结果:

enter image description here