如何在 ggplots 中维护配色方案,同时删除每个图中未使用的级别?

rco*_*rty 3 r ggplot2 aesthetics

我想比较一个图中我的数据的一些子组和另一个图中的一些其他子组。如果我将所有子组都绘制成一个图,这个数字是压倒性的,每个单独的比较都变得困难。我认为如果给定的子组在所有图中使用相同的颜色,对读者来说会更有意义。

这是我尝试过的两件事,几乎可以工作,但都不太奏效。他们离我最接近 MWE 了!

错误,因为所有三个级别都显示在图例中

library(tidyverse)

# compare first and second species
ggplot(data = iris %>% filter(Species != 'virginica'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_discrete(drop = FALSE)


# compare second and third species
ggplot(data = iris %>% filter(Species != 'setosa'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_discrete(drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

请注意,未绘制的级别仍然出现在图例中(与 drop = FALSE 的想法一致)。

错误,因为第二个图没有保持第一个图建立的物种颜色映射

# compare first and second species
ggplot(data = iris %>% filter(Species != 'virginica'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_manual(values = c('red', 'forestgreen', 'blue'),
                     breaks = unique(iris$Species))


# compare second and third species
ggplot(data = iris %>% filter(Species != 'setosa'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_manual(values = c('red', 'forestgreen', 'blue'),
                     breaks = unique(iris$Species))
Run Code Online (Sandbox Code Playgroud)

请注意,在左图中 setosa = red 和 virginica = green,但在右图中映射发生了变化。

Mar*_*son 5

最有效的方法是为每个级别(物种)设置一个命名的颜色变量,并在每个图中使用它。

在这里,您可以使用与上面相同的颜色,但通过向变量添加名称,您可以确保它们始终正确匹配:

irisColors <-
  setNames( c('red', 'forestgreen', 'blue')
            , levels(iris$Species)  )
Run Code Online (Sandbox Code Playgroud)

setosa     versicolor     virginica 
 "red"  "forestgreen"        "blue"
Run Code Online (Sandbox Code Playgroud)

然后你可以用它来设置你的颜色:

首先是所有颜色:

ggplot(data = iris,
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_manual(values = irisColors)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

然后是您问题中的每个子集:

ggplot(data = iris %>% filter(Species != 'virginica'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_manual(values = irisColors)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

ggplot(data = iris %>% filter(Species != 'setosa'),
       mapping = aes(x = Sepal.Length,
                     y = Sepal.Width,
                     color = Species)) +
  geom_point() +
  scale_color_manual(values = irisColors)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明