【问题标题】:R plotly barplot, sort by valueR plotly barplot,按值排序
【发布时间】:2017-03-06 14:42:37
【问题描述】:

我有一个条形图,在 X 轴上有类别并在 Y 上计数。有没有办法按 Y 值的降序对条形图进行排序?

这是示例代码

Animals <- c("giraffes", "orangutans", "monkeys")
Count <- c(20, 14, 23)
data <- data.frame(Animals, Count)

data <- arrange(data,desc(Count))

plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo')

尽管在绘图之前按计数排列数据,但我仍然得到按动物名称字母顺序排序的条形。

谢谢, 马诺吉

【问题讨论】:

    标签: r bar-chart plotly


    【解决方案1】:

    要按它们的值对条形图进行降序排序,您需要使用 xaxis 的布局属性,如下所示:

    plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo') %>% 
      layout(xaxis = list(categoryorder = "total descending"))
    

    【讨论】:

      【解决方案2】:

      几件事:

      1. 看看str(data),你的Animals 字符向量被强制转换为一个因子,除非你在调用data.frame 时指定stringsAsFactors = FALSE。默认情况下,此因子的级别按字母顺序排列。
      2. 即使将Animals 设为data 中的字符向量,plot_ly 也不知道如何处理字符变量,因此会将它们强制转换为因子。

      您需要设置因子级别顺序才能得到您要查找的降序。

      Animals <- c("giraffes", "orangutans", "monkeys")
      Count <- c(20, 14, 23)
      data <- data.frame(Animals, Count, stringsAsFactors = FALSE)
      data$Animals <- factor(data$Animals, levels = unique(data$Animals)[order(data$Count, decreasing = TRUE)])
      plot_ly(data, x = ~Animals, y = ~Count, type = "bar", name = 'SF Zoo')
      

      【讨论】:

      • 谢谢杰夫,我确实尝试在情节之前使用 tab
      • 如果tab$Category 是一个因素,那么plot_ly 将使用水平顺序作为显示图的顺序。您需要重新排序给定tab$Counttab$Category 的级别。您可能会发现 stats::reorder 功能很有帮助:tab$Category &lt;- reorder(x = tab$Category, X = tab$Count, FUN = sum)
      • 嗨杰夫,我的类别不是因素,表格在情节之前得到正确排序。但是,plot_ly 在生成绘图时按字母顺序对我的类别进行排序。它的发生与下面的示例完全相同,其中动物在图表中按字母顺序显示,尽管在 plot_ly( x = c("giraffes", "orangutans", "monkeys"), y = c(20, 14, 23 ), name = "SF Zoo", type = "bar" )
      • 完美。谢谢杰夫!
      • 这个答案有 tidyverse 友好的版本吗?在生成plot_ly 对象之前在一个语句中使用它会很棒......如上所述,即使arrange(desc(Count)) 用作前一个语句,它也不起作用
      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 2016-09-25
      • 2015-09-10
      • 2017-03-02
      • 2022-06-11
      • 2021-01-29
      • 2021-08-15
      • 2020-05-14
      相关资源
      最近更新 更多