首页 > 解决方案 > 在更改 geom_bar 顺序时保持一致的颜色?

问题描述

在根据另一个值订购 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 包(v0.3.0)于 2020 年 8 月 31 日创建

标签: rggplot2forcats

解决方案


这种方法最终对我有用:

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

推荐阅读