如何反转ggplot2的默认调色板

时间:2017-08-24 18:29:08

标签: r ggplot2

我正在尝试使用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 = ?)

3 个答案:

答案 0 :(得分:6)

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.

BTW,为了让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 :(得分:2)

我们可以使用hue_pal包中的scales函数来获取颜色的名称。之后,使用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))

答案 2 :(得分:0)

我会使用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')))