r - 因子不分解 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 = "")"))
解决方案
如果您在函数ordered = TRUE
内部传递参数factor()
,则级别的顺序将是它们在您 print 时出现的顺序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()
推荐阅读
- python - 使用朴素贝叶斯对很长的文本进行分类时,避免得到无意义的值(例如 -0.0)
- java - 如何在 Oracle ADF 的 JSFF 页面上添加 BACK 按钮?
- bash - 如何将 2 添加到 bash 中 .txt 文件中大于 100 的所有整数
- python - TypeError: 不支持的操作数类型 //: 'int' 和 'graph'
- json - 如何从同一个json文件中grep两个行值并在另一个文件中并排显示它们?
- html - 试图从我的页面中删除空白
- java - 在 Maven 生命周期中运行 JUnit5 和 Spock
- html - Bootstrap - 列溢出(滚动)
- python - 扩展安装错误:请先安装nodejs 5+和npm再继续安装
- indy - 在 TidHTTPServer 中阻止传入的 IP