How to remove leading zero from %m for x axis in ggplot2

Viewed 581

How can I remove leading zeros from the x axis labels WITHOUT MANUALLY adding custom labels?

   p + scale_x_date(date_labels = "%m/%d", #this generated dates like: 02/15, 03/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))
2 Answers

You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Windows

Insert a pound sign (#) before the m:

p + scale_x_date(date_labels = "%#m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))

Unix

Insert a minus sign (-) before the m:

p + scale_x_date(date_labels = "%-m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))

You can use:

p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))

As shown in the following reprex:

library(ggplot2)

p <- ggplot(data.frame(date = seq.Date(as.Date("2020-05-30"), 
                                       as.Date("2020-07-18"), length.out = 50),
                       value = sample(50)), aes(date, value)) + geom_col()
p

p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))

Created on 2020-06-02 by the reprex package (v0.3.0)

Related