31

Why do I get the different order in plotly bar chart than I defined in x and y variables.

E.g.

library(plotly)

plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar"
)

I need bar chart where I see bars in the same order as x variable (categorical) is defined. Is there any trick for that?

Uwe
  • 41,420
  • 11
  • 90
  • 134
martinkabe
  • 1,079
  • 2
  • 12
  • 27

3 Answers3

49

Plotly will order your axes by the order that is present in the data supplied. In case of character vectors alphabetically; in case of factors by the order of levels. To override this behaviour, you need to define categoryorder and categoryarray for the xaxis inside layout:

library(plotly)
xform <- list(categoryorder = "array",
              categoryarray = c("giraffes", 
                                "orangutans", 
                                "monkeys"))

plot_ly(
 x = c("giraffes", "orangutans", "monkeys"),
 y = c(20, 14, 23),
 name = "SF Zoo",
 type = "bar") %>% 
 layout(xaxis = xform)

enter image description here

mtoto
  • 23,919
  • 4
  • 58
  • 71
34

plotly does it in alphabetical order. If you want to change it, just try to change levels of factor. This would be possible if you give your data in the form of data.frame like here:

library(plotly)

table <- data.frame(x = c("giraffes", "orangutans", "monkeys"),
                    y = c(20, 14, 23))
table$x <- factor(table$x, levels = c("giraffes", "orangutans", "monkeys"))

plot_ly(
    data=table,
    x = ~x,
    y = ~y,
    name = "SF Zoo",
    type = "bar"
)
Marta
  • 3,032
  • 3
  • 17
  • 34
  • 10
    If you have a larger dataset, that is allready in the needed order you can use `table$x <- factor(table$x, levels = c(as.character(table$x)))` no need to type in every word. – DanielS Aug 03 '18 at 07:51
11

You can also use reorder if you want to order based on a second variable:

library(plotly)
 x <- c("giraffes", "orangutans", "monkeys")
 y <- c(20, 14, 23)

plot_ly(
  x = ~reorder(x,y),
  y = ~y,
  name = "SF Zoo",
  type = "bar"
  ) 
Joost
  • 123
  • 1
  • 6