3

I have some data that is sorted but in plotly the horizontal bar is only sorting in reverse alphabetical order but I need it to sort by a VALUE which is a number; see image 'YOY' column. enter image description here

ecomm_yoy <- ecomm_data2019 %>%
      inner_join(ecomm_data2018, by = "Brand") %>%
      mutate(YOY = round(((Value.x - Value.y)/Value.y)*100, 2)) 

    ecomm_yoy2 <- ecomm_yoy[order(-ecomm_yoy$YOY),]

    plot_ly(x = ecomm_yoy2$YOY, y = ecomm_yoy2$Brand, type = 'bar', orientation = 'h') 

enter image description here

  • 1
    Possible duplicate of [Ordering in r plotly barchart](https://stackoverflow.com/questions/40149556/ordering-in-r-plotly-barchart) ? – Matt Jul 01 '19 at 11:37
  • No because this is to order data by categories and I am trying to order by the number output as shown by YOY in the image. I tried all the similar posts before posting the question. – Matthew Appleyard Jul 01 '19 at 11:54

1 Answers1

3

Add (using a pipe) this layout to your chart:

layout(yaxis = list(categoryorder = "array", categoryarray = ecomm_yoy2$YOY)) 
  • Error in UseMethod("layout") : no applicable method for 'layout' applied to an object of class "list" plot_ly(x = ecomm_yoy2$YOY, y = ecomm_yoy2$Brand, type = 'bar', orientation = 'h') + layout(xaxis = list(categoryorder = array, categoryarray = ecomm_yoy2$YOY)) – Matthew Appleyard Jul 01 '19 at 11:58
  • @MatthewAppleyard replace + to a pipe. I will edit my answer to be more specific. – José Luiz Ferreira Jul 01 '19 at 12:06
  • With pipe another error! Error in unique.default(x) : unique() applies only to vectors – Matthew Appleyard Jul 01 '19 at 12:07
  • This works for me: data <- mtcars %>% mutate(name = rownames(mtcars)) %>% arrange(-hp) plot_ly(data = data, x = ~hp, y= ~name, type='bar', orientation = 'h') %>% layout(yaxis = list(categoryorder = "array", categoryarray = data$name)) I still don't see how it is different than your case. :-( – José Luiz Ferreira Jul 01 '19 at 12:11
  • @MatthewAppleyard And I forgot the quotes around array... Just edit it... Sorry – José Luiz Ferreira Jul 01 '19 at 12:19
  • 1
    I added an layout x axis as well and it worked. Thanks a lot for your help. Finally it worked like this: plot_ly(x = ecomm_yoy2$YOY, y = ecomm_yoy2$Brand, type = 'bar', orientation = 'h') %>% layout(xaxis = list(dtick = 5)) %>% layout(yaxis = list(categoryorder = "array", categoryarray = ecomm_yoy2$YOY)) – Matthew Appleyard Jul 01 '19 at 12:25