簡體   English   中英

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) ,除非在對data.frame的調用中指定stringsAsFactors = FALSE ,否則將Animals角色向量強制轉換為因子。 默認情況下,此因子的級別為字母。
  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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM