日期轴标签不正确

时间:2021-06-11 11:02:48

标签: r ggplot2

我有以下数据:

> 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

我使用以下方法绘制它:

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

这给出:

enter image description here

我不明白为什么轴标签没有正确对齐。例如,第一个柱应该是 Jan(不是二月),最后一个应该是十二月(不是一月)

此处提供数据:

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")

1 个答案:

答案 0 :(得分:2)

默认情况下,月份标签显示为最近的月份。使用 floor_date 将日期设为月份的第一个日期。

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