簡體   English   中英

如何在R中按順序排列x軸(月)

[英]How to put x-axis in order(Month) in R

我想繪制月份,但x軸的順序不正確,例如“ Apr”,“ Aug”,“ Nov” .....但是我希望x軸的順序像“ Jan”, “二月”,“三月” ........

#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"))

根本不起作用,有人可以幫我嗎?非常感謝。

用您的代碼使用格式提取月份,但使用基本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

產量

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM