简体   繁体   中英

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

I wanna plot with month,but the x-axis is not in order,such as"Apr","Aug","Nov"..... But I want the order on x-axis to be like "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")

在此处输入图片说明

I tried this:

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

and:

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

Doesn't work at all.Can someone help me with this?Many thanks.

in ur code used format to extract months but use base r function months u will get solution easily

If u use format output is like :

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

months will extract the month name fully like below :

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

as per ur code do the below :

date_month<-months(date_1)
date_month<-factor(date_month,levels=month.name)

Now plot and try.

sample code :

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 is a built-in 'constant' with all the months' names in long form. To match it to your data use substr() and keep only first three characters.

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

Then plot it as usual.

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

在此处输入图片说明

Data

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM