R plotly x 轴使用标签进行显示

问题描述

尝试使用 R Plotly 绘制条形图。我需要按 q_order 排序的图表 x 轴,但需要让 x 轴显示来自名为 title 的数据的标签。我该怎么做?

数据

enter image description here

图表

enter image description here

代码

 fig <- plot_ly(
  data = ybq,x = ~q_order,y = ~t_put,type = "bar"
) %>%
  layout(xaxis=list(
               autorange="reversed",type="category"
               ))

解决方法

您可以根据 title 中的值排列 q_order 的因子水平。

library(plotly)

ybq$title <- factor(ybq$title,ybq$title[order(ybq$q_order)])

plot_ly(
  data = ybq,x = ~title,y = ~q_order,type = "bar"
)

enter image description here

数据

ybq <- data.frame(title = c('21-Jan','Q4 2020','Q3 2020','Q2 2020'),t_put = c(1606,11419,10882,6525),q_order = c(112021,42020,32020,22020))