使用 ggplot scale_x_yearmon 缺少 yearmon 标签

missing yearmon labels using ggplot scale_x_yearmon

我按月和年对一些数据进行了分组,使用 zoo 将其转换为 yearmon,现在我将其绘制在 ggplot 中。有谁知道为什么缺少一个标记标签,而 2018-07 有一个标记,当时那个月没有数据?

示例数据:

df <-  data.frame(dates = c("2019-01", "2019-02", "2018-08", "2018-09", "2018-10", "2018-11", "2018-12"), values= c(0,1,2,3,4,5,6))
df$dates <- as.yearmon(df$dates)

ggplot(df, aes(x = dates, y = values)) + 
  geom_bar(position="dodge", stat="identity") +      
  theme_light() +
  xlab('Month') +
  ylab('values')+ 
  scale_x_yearmon(format="%Y %m")

我认为这是绘制 zoo 对象的问题。使用标准 Date class 并在 ggplot 中指定日期标签。您需要将日期添加到 dates 列的字符串中。然后你可以使用 scale_x_date 并指定 date_labels.

library(tidyverse)
df <-  data.frame(dates = c("2019-01", "2019-02", "2018-08", "2018-09", "2018-10", "2018-11", "2018-12"), values= c(0,1,2,3,4,5,6)) %>% 
  arrange(dates) %>% 
  mutate(dates = as.Date(paste0(dates, "-01")))


ggplot(df, aes(x = dates, y = values)) + 
geom_bar(position="dodge", stat="identity") +
scale_x_date(date_breaks="1 month", date_labels="%Y %m") +
theme_light() +
xlab('Month') +
ylab('values')

我认为 scale_x_yearmon 用于 xy 图,因为它调用 scale_x_continuous 但我们可以像这样自己调用 scale_x_continuous(只有标记为 ## 的行已更改):

ggplot(df, aes(x = dates, y = values)) + 
 geom_bar(position="dodge", stat="identity") +      
 theme_light() +
 xlab('Month') +
 ylab('values')+ 
 scale_x_continuous(breaks=as.numeric(df$dates), labels=format(df$dates,"%Y %m")) ##