missing yearmon labels using ggplot scale_x_yearmon

我怕爱的太早我们不能终老 提交于 2019-12-02 07:48:06

问题


I have grouped some data by month and year, converted to yearmon using zoo and am now plotting it in ggplot. Does anyone know why one of the ticklabels are missing and there is one for 2018-07, when there is no data for that month?

Example data:

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


回答1:


I think scale_x_yearmon was meant for xy plots as it calls scale_x_continuous but we can just call scale_x_continuous ourselves like this (only the line marked ## is changed):

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




回答2:


I think it's an issue with plotting zoo objects. Use the standard Date class and specify the date label in ggplot. You'll need to add the day into the character string for your dates column. Then you can use scale_x_date and specify the 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')



来源:https://stackoverflow.com/questions/54591625/missing-yearmon-labels-using-ggplot-scale-x-yearmon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!