Search code examples
rplotlyaxis-labelsx-axis

R plotly x-axis use labels for display


Trying to use R Plotly to graph bar chart. I need the chart x-axis ordered by q_order but need to have the x-axis display the labels from data called title. How would I do this?

Data

enter image description here

Chart

enter image description here

Code

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

Solution

  • You can arrange the factor levels for title based on values in 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

    data

    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))