tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.45k stars 2.02k forks source link

User friendly breaks and labels for scale_*_time #5817

Closed llrs closed 5 months ago

llrs commented 5 months ago

I am using ggplot2 to render the daily electricity prices and compare it with the previous day price. Very useful! I show both prices on the same plot covering 24h, but the plot is showing seconds when the accuracy of the data is only hours, because the time is ingested as POSIXct.

It would be nice if scale_{x|y}_time could handle date_label or date_breaks, otherwise I am forced to use some ugly transformation. If the name of the argument is not good as the time is not date it would be nice if the labels or breaks would follow the same principle as in date_label and date_breaks for datetime and other related scale_*time functions

I think this should be posted here and if useful could need some scales change.

library("ggplot2")
library("hms")
packageVersion("ggplot2")
#> [1] '3.5.0'
packageVersion("hms")
#> [1] '1.1.3'
df <- data.frame(time = as_hms(c(3600*0:24)),
           random = rnorm(25))
p <- ggplot(df) +
  geom_point(aes(time, random))
p

p +
  scale_x_time(breaks = df$time[c(TRUE, FALSE)], date_breaks = "2 hours")
#> Error in scale_x_time(breaks = df$time[c(TRUE, FALSE)], date_breaks = "2 hours"): unused argument (date_breaks = "2 hours")
p +
  scale_x_time(breaks = df$time[c(TRUE, FALSE)], date_labels = "%H:%m")
#> Error in scale_x_time(breaks = df$time[c(TRUE, FALSE)], date_labels = "%H:%M"): unused argument (date_labels = "%H:%M")
p +
  scale_x_time(breaks = df$time[c(TRUE, FALSE)], labels = "%H:%M")
#> Error in `scale_x_time()`:
#> ! `breaks` and `labels` must have the same length.
breaks <- df$time[c(FALSE, TRUE)]
labels <- format(as.POSIXct(breaks, tz = "UTC"), "%H:%M")
p +
  scale_x_time(breaks = breaks, labels = labels)

Created on 2024-03-29 with reprex v2.1.0

teunbrand commented 5 months ago

Hi Lluís, is this perhaps a duplicate of #4335?

llrs commented 5 months ago

I searched before posting but didn't find it :man_facepalming: . At least I am consistent, and your solution works.

p + scale_x_time(
    name   = element_none(),
    breaks = breaks_width("2 hours"),
    labels = label_time("%H:%M")
)

Sorry for more notification noise!