在更改 geom_bar 顺序时保持一致的颜色?

Maintain consistent colors while changing geom_bar order?

我在根据另一个值排序 geom_bar() 时努力保持图表之间的颜色一致性。

期望:

实际:

library(tidyverse)
dat <- data.frame(x = c("A","B"), y = c(1,2), z = c(4,3))
# Y
dat %>% 
  mutate(x = fct_reorder(x, y,`.desc` = TRUE)) %>% 
  ggplot(aes(x = x, y = y, fill = x)) + 
  geom_bar(stat = "identity")

# Z
dat %>% 
  mutate(x = fct_reorder(x, z,`.desc` = TRUE)) %>% 
  ggplot(aes(x = x, y = z, fill = x)) + 
  geom_bar(stat = "identity")

reprex package (v0.3.0)

于 2020-08-31 创建

这种方法最终对我有用:

dat %>% 
arrange(desc(z)) %>% 
ggplot(aes(x = reorder(x, desc(z)), y = z, fill = x)) + 
geom_bar(stat = "identity")