Ordering in r plotly barchart

半世苍凉 提交于 2019-12-28 06:19:06

问题


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?


回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/40149556/ordering-in-r-plotly-barchart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!