如何反转ggplot2的默认颜色调色板

15

我正在尝试使用scale_color_brewer(direction=-1)来反转一个图的颜色映射。然而,这样做也会改变调色板。

library(ggplot2)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()

# reverse colors
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_brewer(direction = -1)

潜在的解决方案

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
scale_color_brewer(direction = -1, palette = ?)

更新了标题。 - Ben
没有答案,但默认比例尺是scale_color_discrete,而不是颜色酿造器比例尺。它调用discrete_scale指定调色板为scales::hue_pal,并且确实需要一个direction参数,但添加scale_color_discrete(direction = -1)会改变调色板,而不仅仅是反转。现在没有时间深入挖掘... - Gregor Thomas
3个回答

16

ggplot使用的默认调色板是scale_color_hue

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()

等同于

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
  geom_point() + scale_color_hue(direction = 1)

direction = -1会颠倒颜色。但是,您需要在色调环中调整起始点,以便以相反的顺序获得相同的三种颜色。

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_hue(direction = -1, h.start=90)

每个颜色移动色调指针30度。因此我们将起始点设置为90。

色相轮

顺便提一下,为了让 scale_colour_brewer 对类别变量起作用,您需要设置 type = 'qual'

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_brewer(type = 'qual', palette = 'Dark2')

1
而要反转默认的连续颜色比例,您可以使用 scale_color_continuous(trans = 'reverse'),类似于您反转连续轴比例尺的方式。 - joelostblom
我使用“配对”调色板,想要向上移动一个离散跳跃,我该怎么做?我想从深蓝色开始而不是浅蓝色! - canIchangethis

8

我们可以使用 scales 包中的 hue_pal 函数获取颜色名称。然后,使用 scale_color_manual 来指定颜色,使用 rev 来反转从 hue_pal 中获取的颜色顺序。

library(ggplot2)
library(scales)

# Get the colors with 3 classes
cols <- hue_pal()(3)

# Plot the data and reverse the color
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
  geom_point() +
  scale_color_manual(values = rev(cols))

1
我会使用 scale_color_manual() 来更好地控制。以下是两个反转颜色映射的版本。
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
+     scale_color_manual(values = RColorBrewer::brewer.pal(3,'Blues'))

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
+     scale_color_manual(values = rev(RColorBrewer::brewer.pal(3,'Blues')))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接