因数未将x轴标签进行因式分解 [英] factor not factorizing x axis labels for plotly

查看:96
本文介绍了因数未将x轴标签进行因式分解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从excel导入的数据框. 列之一的格式为:

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

所有其他列只是数字

当我使用plotly(折线图)进行绘制时,我的x轴按字母顺序排列.我尝试过factor.但是它不起作用.

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)

必须做什么?最后,我需要以Oct-18,Nov-18

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

地块代码:

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

推荐答案

如果在factor()函数中传递参数ordered = TRUE,则级别的顺序将与打印data$dates时出现的顺序相同.这也是它们在绘图中出现的顺序.如果未设置ordered = TRUE,则默认行为是按字母顺序排列字符因子.

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.

编辑

要以正确的顺序以编程方式获取dates列,您可以尝试以下代码(取决于dplyrstringr软件包):

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)

现在,您只需将此levels矢量传递给factor()

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

这篇关于因数未将x轴标签进行因式分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆