R plotly barplot,按值排序

R plotly barplot, sort by value

我有一个条形图,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')

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

谢谢, 马诺杰

几件事:

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

要按值降序对条形进行排序,您需要像这样使用 xaxis 的布局属性:

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