首页 > 解决方案 > 因子不分解 x 轴标签的情节

问题描述

我有一个从 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 轴按字母顺序排列。我试过因素。但它不起作用。

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

必须做什么?最后我需要以这种格式标有月份的x轴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 = "")"))

标签: rdataframeggplot2rstudioplotly

解决方案


如果您在函数ordered = TRUE内部传递参数factor(),则级别的顺序将是它们在您 print 时出现的顺序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()


推荐阅读