Ggplot2: scale _ * _ wrong time format
purpose
Use ggplot2::scale_*_time
to format the time axis in a specific way (with the most recent version ggplot2
).
Minimal reprex
# Example data
tib1 <- tibble::tibble(
x = 1:10,
y = lubridate::as.duration(seq(60, 600, length.out = 10))
)
Using ggplot2::scale_*_time
with format = "%R"
doesn't work - the axes will be formatted with %H:%M:%S
:
# This doesn't work
ggplot2::ggplot(tib1) +
ggplot2::geom_point(ggplot2::aes(x,y)) +
ggplot2::scale_y_time(labels = scales::date_format(format = "%R"))
However, I can add a time ( y
) variable to an arbitrary date and then format the resulting object datetime
:
# This works
tib2 <- tib1 %>%
dplyr::mutate(z = lubridate::ymd_hms("2000-01-01 00:00:00") + y)
ggplot2::ggplot(tib2) +
ggplot2::geom_point(ggplot2::aes(x,z)) +
ggplot2::scale_y_datetime(labels = scales::date_format(format = "%R"))
Obviously, I would prefer not to add an arbitrary date to my time to get the correct axis shape (which I should have done until ggplot2::scale_*_time
it was presented, but hopefully this cannot be avoided now).
source to share
Your durations are gradually transformed into an object hms
that is always displayed as hh:mm:ss
(i.e. hms
). scales::date_format
uses format
which does nothing with objects hms
other than converting them to character vectors. Ideally it would be easy to have a correct method format.hms
that could control how much is shown, but since it's worth it hms:::format.hms
doesn't actually take an argument format
.
The solution is to simply remove the first three characters:
ggplot2::ggplot(tib1) +
ggplot2::geom_point(ggplot2::aes(x,y)) +
ggplot2::scale_y_time(labels = function(x) substring(x, 4))
source to share