How do I use the `scale_*continuous` function with `POSIXct` class variables?

Hi ggplot2 experts,

How do I use the scale_*continuous function with POSIXct class variables?

I aw aware of the the scale_*_datetime functions.

Specifically, I want to understand which trans and labels arguments to use. I cannot see scales::*_trans or scales::label_* functions that relate to datetime POSIXct class??

library(nycflights13)
library(tidyverse)

d <- flights |>
  slice_head(n = 1000) |>
  mutate(date = ymd(paste(year, month, day))) %>%
  mutate(departure = make_datetime(year, month, day, hour, minute))

class(d$departure)
#> [1] "POSIXct" "POSIXt"

p <- d |> 
 ggplot() +
  geom_point(aes(x = departure, y = dep_delay))

p +
  scale_x_continuous(
    trans = "hms",
    labels = scales::label_date_short()
  )
#> Warning: Removed 4 rows containing missing values or values outside the scale range
#> (`geom_point()`).

Created on 2023-12-10 with reprex v2.0.2

Perhaps I'm being dense. Could you explain what you are trying to achieve? That is, what do you want the x axis to display?

I want the X axis to have nice datetime labels, and I want to use scale_x_continuous to achieve this.

So I think it is the trans and labelsarguments that I need to adjust somehow?

Here is code for the default plotting of the data, which seems to provide nice datetime labels, and an example of using scale_x_continuous(). I would use scale_x_datetime() instead but I guess you have a reason for using the *continuous() scale.

library(nycflights13)
library(tidyverse)

d <- flights |>
  slice_head(n = 1000) |>
  mutate(date = ymd(paste(year, month, day))) %>%
  mutate(departure = make_datetime(year, month, day, hour, minute))

#Defaul ggplot result
p <- d |> 
  ggplot() +
  geom_point(aes(x = departure, y = dep_delay))
p
#> Warning: Removed 4 rows containing missing values (`geom_point()`).


#Adjust x-axis with scale_x_continuous()
BREAKS <- ymd_hm(c("2013-01-01 12:00", "2013-01-02 00:00", "2013-01-02 12:00"))
BREAKS_num <- as.numeric(BREAKS)
LABELS <- c("01-01 12:00", "01-02 00:00", "01-02 12:00")
p +
  scale_x_continuous(breaks = BREAKS_num, labels = LABELS )
#> Warning: Removed 4 rows containing missing values (`geom_point()`).

Created on 2023-12-10 with reprex v2.0.2

1 Like

Or like this - thanks @FJCC

p +
  scale_x_continuous(
    trans = scales::transform_time(),
    labels = scales::label_date_short()
    )

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.