Joe King
Joe King

Reputation: 3011

Incorrect date axis labels

I have the following data:

> dt
        Month Var
1  2020-01-31 237
2  2020-02-29 205
3  2020-03-31 352
4  2020-04-30 213
5  2020-05-31 455
6  2020-06-30 284
7  2020-07-31 268
8  2020-08-31 273
9  2020-09-30 378
10 2020-10-31 289
11 2020-11-30 346
12 2020-12-31 432

and I plot it using:

dt %>%
  ggplot(aes(x = Month, y = Var, group = 1)) + 
  geom_bar(stat = "identity") +
  scale_x_date(date_labels = "%b")

and this gives:

enter image description here

I don't understand why the axis labels don't align properly. For instance, the first bar should be Jan (not Feb) and the last one should be Dec (not Jan)

Data is available here:

dt <- structure(list(Month = structure(c(18292, 18321, 18352, 18382, 
                                   18413, 18443, 18474, 18505, 18535, 18566, 18596, 18627), class = "Date"), 
               Var = c(237, 205, 352, 213, 455, 284, 268, 273, 378, 289, 
                       346, 432)), row.names = 1:12, class = "data.frame")

Upvotes: 1

Views: 109

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

By default the month labels are shown of the month which are the closest. Use floor_date to make the dates first date of the month.

ggplot(dt, aes(x = lubridate::floor_date(Month, 'month'), y = Var, group = 1)) + 
  geom_col() + 
  scale_x_date(date_labels = "%b", expand = c(0, 0)) + 
  xlab('Month')

enter image description here

Upvotes: 2

Related Questions