在同一坐标轴上绘制年份和月份的图表

3

我有一个数据框,想要在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个回答

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

这部分能够工作,但我可以将图分成按年份的方式吗? - sai saran
@saisaran 没问题,我正在写类似的答案,想着最好和Michal的答案合并。 - zx8754
@zx8754,你有没有完美的解决方案来绘制这种类型的数据? - sai saran
@saisaran 我不确定我是否理解你的意思,但也许这是你需要的答案?ggplot(df1, aes(year(ymd), count, fill = factor(lic))) - Michał Ludwicki
@MichałLudwicki 在进行一些修改和比较后,使用 face_gridfacet_wrap 获得了解决方案。 - sai saran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接