我有一個堆疊條形圖,我想重新排列圖例的顯示方式。我希望圖例在“社會”、“經濟”和“環境”中顯示順序,但保持顏色相同。我一直在嘗試不同的解決方案,但我是一個新手,可能寫錯了東西!
我認為我在正確的軌道上,但它不起作用:
mortality_df$subsystem <- factor(mortality_df$subsystem, levels = c("Social", "Economic", "Environmental"))
沒有重新排序圖例的代碼:
mortality_df <- results_df %>%
pivot_longer(
cols = starts_with("imp_"),
names_to = "mortality",
names_prefix = "imp_",
values_to = "importance"
) %>%
relocate(c(feature, subsystem, mortality, importance, label))
mortality_df
diabetes_plot <- mortality_df %>%
filter(mortality == "diabetes") %>%
filter(importance > 0) %>%
ggplot(aes(x = reorder(label, importance), y = importance, fill = subsystem))
geom_bar(stat = "identity")
coord_flip()
scale_y_continuous(name = "Importance Score")
scale_x_discrete(name = "")
theme_minimal()
theme(aspect.ratio = 1.45)
diabetes_plot
這創造了這個:

通過重構改變順序
這里的關鍵是確保您factor(...) 在繪圖代碼之前使用。如果您嘗試將它們通過管道連接在一起(即%>%)或在繪圖代碼中直接重構,結果將是混合的。
還要注意,與原始圖相比,我們的顏色發生了變化。這是因為根據ggplot每個圖例鍵在levels(...). 換句話說,因子中的第一個級別獲得比例中的第一種顏色,第二個級別獲得第二種顏色,依此類推...
d <- mpg %>% dplyr::filter(class %in% c('compact', 'pickup', 'minivan', 'suv'))
d$class <- factor(d$class, levels=c('compact', 'suv', 'pickup', 'minivan'))
p <-
d %>% ggplot(aes(x=factor(year), fill=class))
geom_bar()
coord_flip()

使用縮放功能更改鍵的順序
The simplest solution is to probably use one of the scale_*_* functions to set the order of the keys in the legend. This will only change the order of the keys in the final plot vs. the original. The placement of the layers, ordering, and coloring of the geoms on in the panel of the plot area will remain the same. I believe this is what you're looking to do.
You want to access the breaks= argument of the scale_fill_discrete() function - not the limits= argument.
p scale_fill_discrete(breaks=c('compact', 'suv', 'pickup', 'minivan'))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315831.html
上一篇:嵌套分類變數作為美學
