我有一個帶有百分比的堆積條形圖,解釋了有人留下差評的原因。基于這個SO answer,我將我的情節設計為一個單一的堆疊條形圖。但是,我現在想根據選擇該原因的個人百分比來排序條形圖。如果有平局,無論哪個原因先出現都可以,但配色方案需要保持一致(即原因 1 必須始終為黃色)。
我嘗試重新排序資料集 ( arrange(desc(percentage)) %>%),但結果是相同的。我還看到其他答案說要訂購 x 軸,但我的 x 軸變數對于每個人來說都是相同的,這取決于我如何操縱情節。任何幫助,將不勝感激!
library(dplyr)
library(ggplot2)
library(scales)
#Test dataset
test_dataset <- tibble(reason = c("Reason 1", "Reason 2", "Reason 3", "Reason 4", "Reason 5"),
percentage = c(.10, .35, .25, .15, .15),
filler_variable = "filler_variable")
#specifying colors
colors <- c("red", "blue", "green", "orange", "yellow")
#Setting my variables in a set order to link them with their color
test_dataset$reason_factor <- factor(test_dataset$reason, levels= rev(c("Reason 1",
"Reason 2",
"Reason 3",
"Reason 4",
"Reason 5")))
#Making my plot
test_dataset %>%
arrange(desc(percentage)) %>%
ggplot(aes(x = filler_variable, y = percentage, fill = reason_factor))
geom_col(position="fill",width = 0.4)
coord_flip()
scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1))
scale_fill_manual(values = colors, guide = guide_legend(reverse = TRUE, nrow=2, byrow=TRUE))
uj5u.com熱心網友回復:
一種選擇是首先使用一個命名的顏色向量,它將顏色分配給類別。要按百分比訂購條形圖,您reorder可以reason_factor:percentage
colors <- c("red", "blue", "green", "orange", "yellow")
names(colors) <- levels(test_dataset$reason_factor)
# Making my plot
ggplot(test_dataset, aes(y = filler_variable, x = percentage, fill = reorder(reason_factor, percentage)))
geom_col(position = "fill", width = 0.4)
scale_x_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1))
scale_fill_manual(values = colors, guide = guide_legend(reverse = TRUE, nrow = 2, byrow = TRUE))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487257.html
下一篇:如何為每個集群設定不同的顏色
