martinkabe martinkabe - 1 month ago 23
R Question

Ordering in r plotly barchart

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.

Answer

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