Reputation: 11
I am trying to adjust the x axis in a graph using ggplot in R. My main reason for wanting to use scale_x_datetime is to have larger breaks in the graph. However, when I run the code, I get the following error:
Error: Invalid input: time_trans works with objects of class POSIXct only
I have tried to assign my time data as POSIXct data (using as.POSIXct), and apparently this scale_x_datetime function needs it to be POSIXct. I can only get it to show up as POSIXlt for some reason.
FYI, my data is in HH:MM:SS, no date associated with it, and is listed as a factor w 4660 levels.
Thank you in advance!
Upvotes: 0
Views: 5552
Reputation: 3938
An approach is to add a fake date (YYYY-MM-DD) and not displaying it in the graph.
Here is an example with mock data :
library(tidyverse)
library(scales)
# Mock data
df <- data.frame(time = paste(sprintf("%02d", sample(1:23, 50, replace = TRUE)),
sprintf("%02d", sample(1:59, 50, replace = TRUE)),
sprintf("%02d", sample(1:59, 50, replace = TRUE)),
sep = ":"),
y_value = sample(1:200, 50))
head(df$time)
> 13:28:27 13:10:26 13:38:06 08:20:32 21:57:13 16:07:55
# Plot
df %>%
mutate(., date = as.POSIXct(paste("2000-01-01", time))) %>%
ggplot(., aes(x = date, y = y_value)) +
geom_point() +
scale_x_datetime(date_breaks = "4 hours",
date_minor_breaks = "1 hour",
labels = date_format("%H:%M:%S")) # format defined here
Upvotes: 1