3

I'd like to hide columns with no data in ggplot2. Here is a reproducible example using the nycflights13 library:

library(nycflights13)
library(dplyr)
library(ggplot2)

small_data <- flights %>%
  mutate(date = lubridate::make_date(year, month, day)) %>%
  filter(year == 2013, 
         month ==3)

ggplot(small_data) +
  geom_bar(aes(date)) +
  scale_x_date(date_labels = "%d - %b", date_breaks = "1 day") +
  theme(axis.text.x = element_text(angle = 65, hjust = 1))

geom_bar with additional bars

As yopu can see, although I have only selected data for march, I have column titles for 28 Feb and 01 April.

I have tried the following:

hide missing dates from x-axis ggplot2 (the solution no longer works)

setting (date_)breaks = levels(factor(small_data$date))

Please help me hide the unnecessary bars.

www
  • 38,575
  • 12
  • 48
  • 84
Preston
  • 7,399
  • 8
  • 54
  • 84
  • The option expand=c(0,0) adjust the x scale so it doesn't show unnecesary dates. Add "scale_x_date(date_labels = "%d - %b", date_breaks = "1 day", expand=c(0,0))" – Cris Sep 04 '17 at 13:35

2 Answers2

6

or we could set scale_x_date(..., expand = c(0,0)):

ggplot(small_data) +
    geom_bar(aes(date)) +
    scale_x_date(date_labels = "%d - %b", date_breaks = "1 day",
                 expand = c(0,0)) +
    theme(axis.text.x = element_text(angle = 65, hjust = 1))

enter image description here

Nate
  • 10,361
  • 3
  • 33
  • 40
4

We can specify the date breaks in the breaks argument (not in date_breaks).

ggplot(small_data) +
  geom_bar(aes(date)) +
  scale_x_date(date_labels = "%d - %b", 
               breaks = seq(min(small_data$date), max(small_data$date), by = 1)) +
  theme(axis.text.x = element_text(angle = 65, hjust = 1))
parth
  • 1,571
  • 15
  • 24
www
  • 38,575
  • 12
  • 48
  • 84