我有一个从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
地块代码:
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 = "")"))
答案 0 :(得分:2)
如果在ordered = TRUE
函数中传递参数factor()
,则级别的顺序将与打印data$dates
时出现的顺序相同。这也是它们在图中显示的顺序。如果未设置ordered = TRUE
,则默认行为是按字母顺序排列字符因子。
编辑
要以正确的顺序以编程方式获取dates
列,您可以尝试以下代码(取决于dplyr
和stringr
软件包):
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()
自变量