如何在R中按月份对x轴进行排序

4

我想使用月份制作图表,但是x轴的顺序并不是按照顺序排列的,例如"Apr","Aug","Nov"...... 但是我希望x轴的顺序是"Jan", "Feb", "Mar"......

#change the format of date
date_month <- format(date_1, "%b")
class(date_month)
[1] "character"

head(date_month)
[1] "Jul" "Jul" "Jul" "Jul" "Jul" "Jul"

plot(table(date_month), xlab = "Month", ylab = "count")

在此输入图片描述

我尝试了这个:

x1  <- factor(date_month, levels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",  "Aug", "Sep", "Oct", "Nov","Dec"))
plot(y ~ x1)

并且:

plot(table(date_month), xlab = "Month", ylab = "count")
axis(date_month,labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",  "Aug", "Sep", "Oct", "Nov","Dec"))

完全不起作用。有人能帮我解决这个问题吗?非常感谢。
2个回答

3

在您的代码中,使用了format来提取月份。但是使用基础的R函数months,您将轻松获得解决方案。

如果您使用format,输出会像这样:

> head(format(date_month$date, "%b"))
[1] "Jun" "Feb" "Mar" "Oct" "Oct" "Aug"

months 将完整提取月份名称,例如:

> head(months(date_month$date))
[1] "June"     "February" "March"    "October"  "October"  "August"  

根据您的代码,执行以下操作:
date_month<-months(date_1)
date_month<-factor(date_month,levels=month.name)

现在进行绘图并尝试。
示例代码:
date_month<-list(date=sample(seq(as.Date('2018/01/01'), 
                              as.Date('2018/11/08'), by="day"), 100))

> head(date_month)
        date
1 2018-06-13
2 2018-02-19
3 2018-03-05
4 2018-10-29
5 2018-10-25
6 2018-08-22

output


2

month.name 是一个内置的“常量”,包含所有月份的长名称。要将其与您的数据匹配,请使用 substr() 并仅保留前三个字符。

date_month <- factor(date_month, levels = substr(month.name, 1, 3))

然后像往常一样将其绘制出来。
plot(table(date_month), xlab = "Month", ylab = "count")

这里输入图片描述

数据

set.seed(42)
date_1 <- as.Date(sample(0:364, 5e5, replace=TRUE), 
                  origin="2018-01-01")

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