[英]R plotly barplot, sort by value
I have a barplot with categories on X axis and counts on Y. Is there a way to sort the bars in descending order on values of Y?我有一个条形图,在 X 轴上有类别,并在 Y 上计数。有没有办法根据 Y 的值按降序对条形进行排序?
this is the sample code这是示例代码
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')
Despite of arranging the data by count before the plot, I still get bars sorted alphabetically by animal names.尽管在绘图之前按计数排列数据,我仍然得到按动物名称字母顺序排序的条形图。
thanks, Manoj谢谢,马诺杰
A couple things: 几件事:
str(data)
, your Animals
character vector is coerced to a factor unless you specify stringsAsFactors = FALSE
in your call to data.frame
. str(data)
,除非在对data.frame
的调用中指定stringsAsFactors = FALSE
,否则将Animals
角色向量强制转换为因子。 The levels of this factor are alphabetic by default. Animals
is made to be a character vector in data
, plot_ly
doesn't know what to do with character variables and so will coerce them to factors. Animals
作为data
的字符向量, plot_ly
也不知道如何处理字符变量,因此会将它们强制转换为因子。 You need to set factor level order to get the descending order you are looking for. 您需要设置因子级别顺序以获得您要查找的降序。
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')
to sort the bars descending by their value, you need to use a layout attribute of xaxis like so:要按其值对条形进行降序排序,您需要使用 xaxis 的布局属性,如下所示:
plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo') %>%
layout(xaxis = list(categoryorder = "total descending"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.