缺少使用ggplot scale_x_yearmon yearmon标签

问题描述 投票:1回答:2

我已经通过分组月和年一些数据,转换使用动物园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")

enter image description here

r ggplot2 graph zoo
2个回答
3
投票

我认为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")) ##

screenshot


0
投票

我认为这是密谋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')

result plot

© www.soinside.com 2019 - 2024. All rights reserved.