gpt4 book ai didi

r - 在同一轴上绘制年份和月份

转载 作者:行者123 更新时间:2023-12-04 10:27:00 24 4
gpt4 key购买 nike

我有数据框,想在 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

但我需要将年和月作为单个图中的序列。

最佳答案

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com