我已经通过分组月和年一些数据,转换使用动物园yearmon,我现在在ggplot绘制它。有谁知道为什么ticklabels一人失踪,有一个为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")
我认为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")) ##
我认为这是密谋zoo
对象的问题。使用标准的Date
类和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')