Man*_*wal 6 r bar-chart plotly
我有一个在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')
Run Code Online (Sandbox Code Playgroud)
尽管在情节之前按照计数排列数据,我仍然按照动物名称的字母顺序排序.
谢谢,Manoj
Jef*_*ler 13
几件事:
str(data),你的Animals角色向量被强制转换为一个因子,除非你stringsAsFactors = FALSE在你的电话中指定data.frame.默认情况下,此因子的级别为字母.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')
Run Code Online (Sandbox Code Playgroud)
phi*_*ooo 13
要按其值降序对条形进行排序,您需要使用 xaxis 的布局属性,如下所示:
plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo') %>%
layout(xaxis = list(categoryorder = "total descending"))
Run Code Online (Sandbox Code Playgroud)