Robert
Robert

Reputation: 37

How to draw an X axis with time and date in different rows?

I want to create a chart with a two-level X axis.

I have 2 columns, one with dates and the other with values.

Example of dates:

2021-04-13 01:00:00
2021-04-13 01:15:00
2021-04-13 01:30:00
....
2021-04-14 02:00:00
2021-04-14 02:15:00
2021-04-14 02:30:00
...

I would like the hours on the upper level (01:15:00, 01:30:00, ...) and on the lower level I would like the dates (2021-04-13, 2021-04-14, ...).

I tried to use an example like this:

ggplot(df, aes(datetime, value)) +
  geom_line() +
  scale_x_datetime(date_labels=paste(c(rep(" ",11), "%b"), collapse=""), 
               date_breaks="hour", expand=c(0,0)) +
  facet_grid(~ hour(datetime), space="free_x", scales="free_x", switch="x") +
  theme_bw() +
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.border = element_rect(colour="grey70"),
        panel.spacing=unit(0,"cm"))

I am trying to achieve the result as in the example at the end: Multi-row x-axis labels in ggplot line chart

Upvotes: 0

Views: 299

Answers (1)

tamtam
tamtam

Reputation: 3671

You may have a look at the ggh4x package. Multi row axis are named nested relations.

Example Data

library(tidyverse)
library(ggh4x)

df <- data.frame(datetime = seq(as.POSIXct("2021-04-13"), 
                               as.POSIXct("2021-04-15"), 
                               by=60*180),
                value = sample(1:10, 17, replace=TRUE)) %>%
# create separate columns for date and time
  mutate(date = as_date(datetime),
         time = format(datetime, format = "%H:%M:%S"))

Code

ggplot(df, 
       aes(x = interaction(time, date),
           y = value,
           group = 1)) +
  geom_line() +
  guides(x = "axis_nested") +
  theme(axis.text.x = element_text(angle = 90, 
                                   vjust = 0.5, 
                                   hjust=1))

Plot enter image description here

Upvotes: 1

Related Questions