Search code examples
rplotdata-sciencedata-analysis

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

enter image description here

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.


Solution

  • in u r 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 u r 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
    

    output