在ggplot中将日期显示为x轴

时间:2019-05-07 03:56:47

标签: r dataframe ggplot2

我的数据的格式为

["201301",1111],["201302",1111],["201702",2222],["201603",3333].

但是,当我尝试将其绘制为条形图时,由于x值被视为数字,因此它看起来不太好。几年之间有很大的差距。 enter image description here

是否可以消除差距?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,OP将显示月数据,其中变量V1中以“ YYYYMM”格式编码年和月。

我可以通过以下方式重现该问题

# create sample data
years <- 2013:2017
DF <- data.frame(V1 = 100 * rep(years, each = 12) + rep(1:12, length(years)),
                 V2 = rep(1:12, length(years)))

library(ggplot2)
ggplot(DF, aes(V1, V2)) +
         geom_col()

enter image description here

要绘制这些月度数据,需要将V1转换为完整的日期,例如201304成为日期2013-04-01。因此,每个年月都映射到该月的第一天。

借助lubridate软件包,我们得到了

ggplot(DF, aes(lubridate::ymd(V1, truncated = 1L), V2)) +
  geom_col()

enter image description here

ggplot()认识到x轴现在是Date类,并相应缩放。使用Date缩放比例的好处是即使缺少数据点也可以正确缩放。

相关问题