删除ggplot2 + scale中的前导零

时间:2017-03-03 11:55:48

标签: r 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

我想我必须使用scale包中的format_format(),但我在formatformatCsprintf的各种文档中都没有看到任何内容这将产生必要的标签。

3 个答案:

答案 0 :(得分:5)

您可以编写自己的功能:

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

答案 1 :(得分:4)

我有一个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 :(得分: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

不幸的是,这需要为每个情节手动指定格式;我不知道如何自动进行格式化。