[英]Ordering in r plotly barchart
Why do I get the different order in plotly bar chart than I defined in x and y variables.为什么我在条形图中得到的顺序与我在 x 和 y 变量中定义的顺序不同。
Eg例如
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.我需要条形图,在那里我看到的条形与定义 x 变量(分类)的顺序相同。 Is there any trick for that?
有什么技巧吗?
Plotly
will order your axes by the order that is present in the data supplied. Plotly
将按照提供的数据中存在的顺序对您的轴进行排序。 In case of character
vectors alphabetically;如果是按字母顺序排列的
character
向量; 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
:要覆盖此行为,您需要为
layout
的xaxis
定义categoryorder
和categoryarray
:
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)
plotly
does it in alphabetical order. plotly
按字母顺序执行。 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:如果您以
data.frame
的形式提供数据,这将是可能的, data.frame
所示:
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"
)
You can also use reorder
if you want to order based on a second variable:如果您想根据第二个变量进行
reorder
也可以使用reorder
:
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"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.