1

When i use a barplot to plot hourly data, the bars are divided by the x-axis tickmark at X o´clock sharp. The data corresponds to 6-7 o´clock, 7-8 o´clock and so on. I want each bar to start at x o´clock sharp and not at x - 0:30 min.

enter image description here

Code example:

install.packages("nycflights13")
library(nycflights13)
data <- flights %>% select(time_hour, hour) %>% 
                    mutate(flightdate = floor_date(time_hour, "day")) %>% 
                    filter(flightdate == as_date("2013-01-01")) %>% group_by(flightdate,hour) %>% tally() %>%
                    mutate(flightdatetime = as_datetime(paste(flightdate + hours(hour)))) %>%
                    select(flightdatetime,n)

ggplot() +
  geom_col(aes(x=flightdatetime, y = n), 
           data = data, color = "black", fill = "black") +
  ggplot2::scale_x_datetime(labels = date_format("%H:%M", tz = "Europe/Berlin"), date_breaks = "1 hour")  +
  theme_minimal() + labs(title ="Flights per hour")
Niels
  • 150
  • 3
  • 11
  • One, maybe a bit clumsy, option would be to not use the time directly as the x-axis variable, but rather use an index variable. Then you can assign the tick marks not to 1, 2, 3 ... n but rather to 1.5, 2.5, ... n + 0.5 and just use the time as labels. – Mojoesque Aug 23 '18 at 13:59

1 Answers1

0

How about this:

ggplot() +
      geom_bar(aes(x=flightdatetime, y = n),stat="identity",
               data = data, color = "black", fill = "black") +
      ggplot2::scale_x_datetime(labels = date_format("%H:%M", tz = "Europe/Berlin"), date_breaks = "1 hour", expand=c(0, .9))  +
      theme_minimal() + labs(title ="Flights per hour") +
      theme(axis.text.x = element_text(hjust=1.5))

I used theme(axis.text.x = element_text(hjust=1.5)) to move the labels to the left and expand=c(0, .9) inside scale_x_datetime to cut the first and last axis labels. You can play with this two and see if it fits.

enter image description here

RLave
  • 8,144
  • 3
  • 21
  • 37