在同一轴上绘制年和月

时间:2018-11-05 09:48:26

标签: r ggplot2

我有数据框,想要在X轴上绘制年和月,在Y轴上计数。

df1<-data.frame(
  Year=sample(2016:2018,100,replace = T),
  Month=sample(month.abb,100,replace = T),
  category1=sample(letters[1:6],100,replace = T),
  catergory2=sample(LETTERS[8:16],100,replace = T),
  lic=sample(c("P","F","T"),100,replace = T),
  count=sample(1:1000,100,replace = T)
)

图:

ggplot(df1,aes(Year,count,fill=factor(lic)))+geom_bar(stat = "identity",position = "stack")+facet_grid(~category1)

输出:

output

但是我需要一年中的一个月作为一个序列中的一个序列。

1 个答案:

答案 0 :(得分:4)

使用 lubridate 库:

library(lubridate)
library(ggplot2)

df1<-data.frame(
  Year=sample(2016:2018,100,replace = T),
  Month=sample(month.abb,100,replace = T),
  category1=sample(letters[1:6],100,replace = T),
  catergory2=sample(LETTERS[8:16],100,replace = T),
  lic=sample(c("P","F","T"),100,replace = T),
  count=sample(1:1000,100,replace = T)
)

创建 ymd 变量后:

df1$ymd <- ymd(paste0(df1$Year, df1$Month, 1))

然后:

ggplot(df1, aes(ymd, count, fill = factor(lic)))+
  geom_bar(stat = "identity", position = "stack")+
  facet_grid(~category1) +

其他可以帮助您解决问题的选项:

# maybe flip coordinates
coord_flip() +

# set scale on axis for each months      
scale_x_date(date_breaks = "1 month")

# using "scales" library, format the date: "YYYY-Mmm"
scale_x_date(date_breaks = "1 month",
             labels = scales::date_format("%Y-%b")) 

# rotate the xaxis labels 90 degrees.
theme(axis.text.x = element_text(angle = 90, vjust = 0.4))