因数未将x轴标签分解为因数

时间:2018-11-06 05:41:03

标签: r dataframe ggplot2 rstudio plotly

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

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。但是它不起作用。

 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

格式的标有月份的x轴

地块代码:

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 个答案:

答案 0 :(得分:2)

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

编辑

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

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向量传递到levels内的factor()自变量