我有数据框,想在 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)
输出:
但我需要在一个单一的情节中作为一个序列的逐月。
最佳答案
使用 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))
关于r - 在同一轴上绘制年和月,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53151879/