2017-08-24 28 views
2

我正在嘗試使用scale_color_brewer(direction = -1)來顛倒圖的顏色映射。但是,這樣做也會更改調色板。如何顛倒ggplot2的默認調色板

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 = ?) 
+0

已更新標題 – Ben

+0

沒有答案,但默認比例是「scale_color_discrete」,而不是顏色啤酒比例。它調用'discrete_scale'指定調色板爲'scales :: hue_pal',並且* does *採用'direction'參數,但是添加'scale_color_discrete(direction = -1)'不僅僅是改變調色板。現在沒有時間挖掘更多... – Gregor

回答

5

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') 
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'))) 
1

我們可以使用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))