user462015
user462015

Reputation: 13

Adjusting time scale in ggplot

I want to plot date-time relationship but I have some problems with ticks and labels for time-axis. First, I want labels to be in "%H:%M" format instead of "%H:%M:%S". Also, I want ticks to be every 10 minutes instead of every hour. I tried a bunch of methods, but the only one that worked was transforming data from <time> to <chr>. Unfortunately, I also need geom_smooth function for my plot, which doesn't work with characters.

Here's my code with partial dataset.

library(tidyverse)

df <- tibble(
  date=c("08-01","08-02","08-03","08-04","08-05",
         "08-06","08-07","08-08","08-09","08-10",
         "08-11","08-12","08-13","08-14","08-15"),

  a=c("10:10","09:40","09:40","09:40","09:40",
          "09:40","09:40","09:40","09:50","09:40",
          "08:00","09:40","09:40","09:40","09:40"),

  s=c("11:30","11:40","11:30","11:10","",
          "11:30","11:50","11:50","11:30","11:50",
          "","","11:30","12:20","11:20"))

df <- df %>%
  mutate(date = parse_date(str_c("2019", date, sep = "-")),
         a = parse_time(a),
         s = parse_time(s) )

ggplot(df) +
  geom_point(aes(x = date, y = a), color='darkgreen') +
  geom_point(aes(x = date, y = s), color = 'darkblue') + 
  geom_smooth(aes(x = date, y = s), color = 'darkblue') + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m.%d") +
  labs(x = "date", y = "time") +
  theme(axis.text.x = element_text(angle = 90, vjust = 1))

And here's my plot:

And here's my plot

Upvotes: 1

Views: 1323

Answers (1)

Dan Slone
Dan Slone

Reputation: 563

I would suggest working with POSIXct time formats for use with ggplot - sometimes 'hms' objects do not parse correctly with time axes. Try modifying your code as follows: (also incorporating Dave2e's comment)

df <- tibble(...   )

df <- df %>%
  mutate(date = as.Date(paste("2019",date,sep="-"), format="%Y-%m-%d"),
         a = as.POSIXct(a, format="%H:%M"),
         s = as.POSIXct(s, format="%H:%M"))

ggplot(df) +
  geom_point(aes(x = date, y = a), color='darkgreen') +
  geom_point(aes(x = date, y = s), color = 'darkblue') + 
  geom_smooth(aes(x = date, y = s), color = 'darkblue') + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m.%d") +
  scale_y_datetime(date_breaks = "10 min", date_labels = "%H:%M") +
  labs(x = "date", y = "time") +
  theme(axis.text.x = element_text(angle = 90, vjust = 1))

Upvotes: 2

Related Questions