lupi
lupi

Reputation: 1

Seconds and scale_x_time - HH:MM instead of HH:MM:SS

Input data is structured like

Price Seconds Date
11111 6443 2022-01-03
22222 7400 2022-01-04
ggplot(data=d.2,aes(x=Seconds, y=Price)) + 
  geom_path(colour="blue") + 
  ylab("Price") + 
  xlab("Date") +
  coord_cartesian(xlim = c(7*3600+5*60, 15*3600+25*60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time()

Right now I got the following output

enter image description here

Tried manipulating the scale_x_time in some ways I found on here, but can't seem to get it right.

I would like to display time of the day just in hours and minutes, such that it fits my lowre x axis better.

Upvotes: 0

Views: 229

Answers (1)

stefan
stefan

Reputation: 125627

Under the hood scale_x_time converts your seconds to a hms object. Unfortunately I have not found an option to format an hms to show only the hours and minutes directly. But one option would be to convert to a datetime first:

library(ggplot2)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

d.2 <- data.frame(
  Price = c(11111L, 22222L),
  Seconds = c(6443L, 7400L),
  Date = c("2022-01-03", "2022-01-04")
)

ggplot(data = d.2, aes(x = Seconds, y = Price)) +
  geom_path(colour = "blue") +
  ylab("Price") +
  xlab("Date") +
  coord_cartesian(xlim = c(7 * 3600 + 5 * 60, 15 * 3600 + 25 * 60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time(
    labels = \(x) format(as_datetime(x, tz = "UTC"), "%H:%M")
  )
#> `geom_path()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?
#> `geom_path()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?

Upvotes: 0

Related Questions