A. Stam
A. Stam

Reputation: 2222

Show weekdays and times on the x-axis in ggplot

I have a dataset with events. These events have a start time and a duration. I want to create a scatter plot with the start time on the x-axis and the duration on the y-axis, but I want to alter the x-axis so that it displays the course of a week. That is, I want the x-axis to start on Monday 00:00 and run through Sunday 23:59.

All the solutions I've found online show me how to perform group-by-and-sum over weekdays, which is not what I want to do. I want to plot all data points individually, I simply want to reduce the date-axis to weekday and time.

Any suggestions?

Upvotes: 2

Views: 2046

Answers (2)

SamuelR
SamuelR

Reputation: 131

Maybe late, but for others searching:
there is a solution with

scale_x_date(date_labels = '%a')

described here: Weekdays below date on x-axis in ggplot2

Upvotes: 0

amatsuo_net
amatsuo_net

Reputation: 2448

This does what you need. What it does is to create a new variable by putting every observation in one week, and then generate a scatter plot in a necessary format.

library(lubridate)
library(dplyr)

set.seed(1)
tmp <- data.frame(st_time = mdy("01-01-2018") + minutes(sample(1e5, size = 100))) 
tmp <- tmp %>% 
    mutate(st_week = floor_date(st_time, unit = 'week')) %>% # calculate the start of week
    mutate(st_time_inweek = st_time - st_week) %>% # calculate the time elapsed from the start of the week
    mutate(st_time_all_in_oneweek = st_week[1] + st_time_inweek) %>% # put every obs in one week
    mutate(duration = runif(100, 0, 100)) # generate a random duration variable

This is how to generate the plot. The part "%a %H:%M:%S" could be just "%a" as the time portion is not informative.

library(ggplot2)
ggplot(tmp) + aes(x = st_time_all_in_oneweek, y = duration) +
    geom_point() + scale_x_datetime(date_labels = "%a %H:%M:%S", date_breaks = "1 day")

With "%a" the plot look like this:

enter image description here

Upvotes: 4

Related Questions