factor not factorizing x axis labels for plotly

2019-07-24 01:42发布

问题:

I have a dataframe imported from excel. one of the column is of the format :

dates
-------
Oct-17
Nov-17
Dec-17
Jan-18
Feb-18
Mar-18
Apr-18
May-18
Jun-18
Jul-18
Aug-18

All other columns are just numbers

When I plot it using plotly (line chart), I am getting my x axis in alphabetical order. I tried factor.But it is not working.

 data_ = read_excel(path="Sample.xlsx",sheet = 'sheet1')
  data = as.data.frame(data_)
 data$dates <- factor(data$dates, levels = data$dates)

What has to be done? Finally I need x axis labelled with months in this format Oct-18,Nov-18

plot code :

pred <- plot_ly(data_, x = ~dates, y = ~exp, name = 'Exp', type = 'scatter', mode = 'lines',
               line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
    add_trace(y = ~acc, name = 'Accumulated', line = list(color = 'rgb(22, 96, 167)', width = 4)) %>%
    add_trace(y = ~sts, name = 'Contract', line = list(color = 'rgb(205, 12, 24)', width = 4, dash = 'dash')) %>%
    add_trace(y = ~stat, name = 'Status ', line = list(color = 'rgb(22, 96, 167)', width = 4, dash = 'dash')) %>%
    layout(title = "Trend",
           xaxis = list(title = "Months"),
           yaxis = list (title = "")"))

回答1:

If you pass the argument ordered = TRUE inside the factor() function, the order of your levels will be the order they appear when you print data$dates. This is also the order they will appear in the plot. The default behaviour if you don't set ordered = TRUE is to arrange character factors by alphabetical order.

EDIT

To programatically get the dates column in the right order, you may try the following code (it depends on dplyr and stringr packages):

levels <- data %>%
  distinct(dates) %>% 
  rowwise() %>% 
  mutate(
    year = stringr::str_split(dates, "-", simplify = TRUE)[2],
    month = stringr::str_split(dates, "-", simplify = TRUE)[1], 
    month = match(month, month.abb)
    ) %>% 
  arrange(year, month) %>% 
  pull(dates)

Now you just pass this levels vector to the levels argument inside factor()