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

2
  • 1
    Possible duplicate of Ordering in r plotly barchart ? Commented Jul 1, 2019 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. Commented Jul 1, 2019 at 11:54

1 Answer 1

3

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

layout(yaxis = list(categoryorder = "array", categoryarray = ecomm_yoy2$YOY)) 
Sign up to request clarification or add additional context in comments.

6 Comments

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))
@MatthewAppleyard replace + to a pipe. I will edit my answer to be more specific.
With pipe another error! Error in unique.default(x) : unique() applies only to vectors
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. :-(
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))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.