Bluetail
Bluetail

Reputation: 1291

How to set time intervals on a monthly time series in R ggplot?

My data is like this

  dep_delay   date
1  47         2013-01-01
2  1          2013-01-01
3  1          2013-01-01
...
36 4          2013-01-02
37 5          2013-01-02
38 11         2013-01-02
...
911   4       2013-05-15
912   1       2013-05-15
...
3009  17      2013-12-30
3010  28      2013-12-30

I run this code to get a line chart like this. enter image description here


df %>% group_by(date) %>%
  summarise(dep_delay= mean(dep_delay)) %>%
  ggplot() +
  aes(x=date, y= dep_delay) +
# scale_x_date(labels = lbls, breaks = brks) +
  geom_line()

I want to have all months like 'January', 'February',..,'December' displayed under the x-axis with ticks instead of just 'Jan 2013', 'April 2013','Jul 2013', 'Oct 2013' and 'Jan 2014'.

I have tried to add scale_x_date(labels = lbls, breaks = brks)

and

brks <- df$date[seq(1, unique(month(df$date), 12))]
lbls <- lubridate::month(brks)

which does not work as intended.

Upvotes: 0

Views: 314

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can use the arguments date_labels and date_breaks in scale_x_date:

df %>% 
  group_by(date) %>%
  summarise(dep_delay= mean(dep_delay)) %>%
  ggplot() +
  aes(x=date, y= dep_delay) +
  scale_x_date(date_labels = "%B", date_breaks = 'month') +
  geom_line()

enter image description here


Data used

df <- data.frame(date = seq(as.Date('2013-01-01'), by = 'day', length = 365),
                 dep_delay = rpois(365, 40))

Upvotes: 1

Related Questions