How to order x-axis that is date in ascending order?

Asked

Viewed 600 times

2

I have a graph where the x-axis are the dates, but when ordering chronologically, because before it was in alphabetical order, the information of the graph is wrong because the data follows the alphabetical order, in this case starting in Apr/19 and not in Sep/18 and not going from Sep/18 to Sep/19.

I used that code to sort the months:

base_fox2$mês<-factor(base_fox2$mês, levels = c("set/18","out/18","nov/18",

"dez/18","jan/19","fev/19","mar/19","abr/19","mai/19","jun/19","jul/19",
"ago/19","set/19"))

And this to create the chart with the five variables

library(plotly)

plot_ly(data=base_fox2,name='Fox',x=~base_fox2$mês,y=~base_fox2$quantidade,
        type='scatter',mode='lines')%>% 
  add_trace(y=~base_hb202$quantidade,name='HB20',type='scatter',mode='lines')%>% 
  add_trace(y=~base_gol2$quantidade,name='Gol',type='scatter',mode='lines')%>% add_trace(y=~base_palio2$quantidade,name='Palio',type='scatter',mode='lines')%>%
  add_trace(y=~base_punto2$quantidade,name='Punto',type='scatter',mode='lines')
  • 2

    Try to put ordered = TRUE in factor

  • 3

    If you are going to do operations over the months (e.g. calculating the time between lines), it is best to use the Dates class. See help for as.Dates. If this is not the case, sorting the factors (comment above) is a better option.

1 answer

1

It is better to change the class from column to class "Date", not for class "factor".

base_fox2$mês <- as.Date(paste("1", base_fox2$mês, sep = "/"), "%d/%b/%y")

After this, if you just want the month and the year, the function as.yearmon package zoo is the ideal function.

base_fox2$mês <- zoo::as.yearmon(base_fox2$mês)

Example.

This example only changes the column class with the question data, does not create a dataframe or plot the graph.

mes <- c("set/18","out/18","nov/18","dez/18","jan/19",
       "fev/19","mar/19","abr/19","mai/19","jun/19",
       "jul/19","ago/19","set/19")

mes <- as.Date(paste("1", mes, sep = "/"), "%d/%b/%y")
mes
# [1] "2018-09-01" "2018-10-01" "2018-11-01" "2018-12-01" "2019-01-01"
# [6] "2019-02-01" "2019-03-01" "2019-04-01" "2019-05-01" "2019-06-01"
#[11] "2019-07-01" "2019-08-01" "2019-09-01"

Now switch to class "yearmon".

mes <- zoo::as.yearmon(mes)
mes
# [1] "set 2018" "out 2018" "nov 2018" "dez 2018" "jan 2019" "fev 2019" "mar 2019"
# [8] "abr 2019" "mai 2019" "jun 2019" "jul 2019" "ago 2019" "set 2019"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.