2017-03-03 90 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