JoFrhwld
JoFrhwld

Reputation: 9037

Remove leading zeros in ggplot2 + scales

For a journal submission, I've been told that my figures can't have leading zeros. For example, take this plot:

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

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

enter image description here

The y-axis has the labels

-1.0  -0.5   0.0   0.5   1.0

I need to produce these labels:

-1.0   -.5   0      .5    1.0

I imagine I'll have to use format_format() from the scales package, but I haven't seen anything in the various documentation for format, formatC and sprintf that would produce the necessary labels.

Upvotes: 2

Views: 3007

Answers (3)

Jaap
Jaap

Reputation: 83225

You can write your own function:

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
}

and then plot:

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

which gives the desired result:

enter image description here

Upvotes: 6

Tyler Rinker
Tyler Rinker

Reputation: 109874

I have a GitHub package, numform that can do this (I added control over zeros to the f_num function based on this question):

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

Upvotes: 5

Aaron
Aaron

Reputation: 816

This will work:

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

Unfortunately this requires specifying the format manually for each plot; I don't know off the top of my head how to do the formatting automatically.

Upvotes: 4

Related Questions