【问题标题】:Ordering in r plotly barchart在 r plotly 条形图中排序
【发布时间】:2017-03-02 03:59:03
【问题描述】:

为什么我在 plotly 条形图中得到的顺序与我在 x 和 y 变量中定义的顺序不同。

例如

library(plotly)

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

我需要条形图,其中我看到条形的顺序与定义 x 变量(分类)的顺序相同。有什么诀窍吗?

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    Plotly 将按照提供的数据中存在的顺序对您的轴进行排序。如果character 向量按字母顺序排列;在按级别顺序排列的因素的情况下。要覆盖此行为,您需要在 layout 中为 xaxis 定义 categoryordercategoryarray

    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)
    

    【讨论】:

    • 这个答案比根据因素排序更灵活:)
    • 拯救了我的一天!肯定比因素更灵活!
    【解决方案2】:

    plotly 按字母顺序执行。如果你想改变它,只需尝试改变因子的水平。如果您以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"
    )
    

    【讨论】:

    • 如果你有一个更大的数据集,那已经按照需要的顺序你可以使用table$x &lt;- factor(table$x, levels = c(as.character(table$x))),无需输入每个单词。
    【解决方案3】:

    如果您想根据第二个变量订购,也可以使用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"
      ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2020-02-28
      • 2016-09-25
      • 1970-01-01
      • 2018-12-07
      相关资源
      最近更新 更多