Search code examples
rdatetimeggplot2data-visualizationaxis-labels

ggplot - Custom format for plot axis of time variable


How to define custom format for time variable axis in ?

DF <- data.frame(TIME = c(350,400,250,650,500,750),
                 CATEGORY = c(1:6))


ggplot(data=DF, aes(x=CATEGORY, y=as_datetime(TIME))) +
  geom_col() +
  scale_y_datetime(labels = date_format("%M:%S"))

image

What I want is to remove leading zero at the minute-part. Something like this:

image2

Thanks for your time & effort!


Solution

  • Try this:

    library(ggplot2)
    library(lubridate)
    library(scales)
    DF <- data.frame(TIME = c(350,400,250,650,500,750),
                     CATEGORY = c(1:6))
    
    
    date_lab <- function(x) {
      paste0(minute(x), ":", format(x, "%S"))
    }
    
    ggplot(data=DF, aes(x=CATEGORY, y=as_datetime(TIME))) +
      geom_col() +
      scale_y_datetime(labels = date_lab)
    

    Created on 2020-03-24 by the reprex package (v0.3.0)