如何在R中按顺序排列x轴(月)

时间:2018-11-09 09:32:35

标签: r plot data-science data-analysis

我想绘制月份,但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")

enter image description here

我尝试过:

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 个答案:

答案 0 :(得分:1)

在您的代码中使用了格式来提取月份                               但使用基本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

答案 1 :(得分:1)

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

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

然后照常绘制。

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

enter image description here

数据

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