gpt4 book ai didi

r - 按日期子集箱线图,按月排列 x 轴

转载 作者:行者123 更新时间:2023-12-05 01:02:33 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is the most elegant way to split data and produce seasonal boxplots?

(3 个回答)


3年前关闭。




我有跨越两个日历年的一年数据。我想按月为这些数据子集绘制箱线图。

这些图将始终按字母顺序(如果我使用月份名称)或数字(如果我使用月份数字)排序。都不符合我的目的。

在下面的示例中,我希望 x 轴上的月份从 6 月(2013 年)开始,到 5 月(2014 年)结束。

date <- seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "days")

set.seed(100)
x <- as.integer(abs(rnorm(365))*1000)

df <- data.frame(date, x)

boxplot(df$x ~ months(df$date), outline = FALSE)

我可能可以按照我需要的顺序生成月份的向量(例如 months <- months(seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "month")) )

有没有更优雅的方法来做到这一点?我错过了什么?

最佳答案

你在寻找这样的东西吗:

boxplot(df$x ~ reorder(format(df$date,'%b %y'),df$date), outline = FALSE) 
我正在使用 reorder根据日期重新排序您的数据。我还格式化日期以跳过一天部分,因为它是您按月汇总箱线图。
enter image description here
编辑 :
如果你想跳过年份部分(但为什么?我个人觉得这有点令人困惑):
boxplot(df$x ~ reorder(format(df$date,'%B'),df$date), outline = FALSE)
enter image description here
EDIT2 ggplot2 解决方案:
既然你在营销领域,你正在学习 ggplot2 :)
library(ggplot2)

ggplot(df) +
geom_boxplot(aes(y=x,
x=reorder(format(df$date,'%B'),df$date),
fill=format(df$date,'%Y'))) +
xlab('Month') + guides(fill=guide_legend(title="Year")) +
theme_bw()
enter image description here

关于r - 按日期子集箱线图,按月排列 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089617/

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