2016-03-03 194 views
1

我怎樣才能讓ggplot總是利用一個因子相同的顏色映射。例如:ggplot顯示因子水平相同的顏色

library(ggplot) 

## Filter for visual simplification 
diamonds2 <- diamonds[1:10,] 
ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point() 

## Now filtering removes some levels of cut 
diamonds3 <- diamonds[1:5,] 
ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point() 

在第一個散點圖因子級別「公平」是紅色的。在第二個圖表中,因素水平「好」變成了紅色。 我希望保存映射,而不管過濾是否刪除因子級別,以便「公平」始終映射爲紅色等等。

實際上,我的ggplot更復雜得多。我最初的因素有11個等級。

MyPalette <- c("#5DD0B9", "#E1E7E9", "#1f78b4", "#a6cee3", "#de77ae", "#c51b7d", "#8e0152", "#6a3d9a", "#fbdf6f", "#ff7f00", "#fff99") 

,我指的是ggplot

... scale_fill_manual(values = MyPalette, name="") + ...

plot1 plot2

回答

8

只需使用一個名爲向量MyPalettescale_colour_manual()

MyPalette <- c(Fair = "#5DD0B9", Good = "#E1E7E9", "Very Good" = "#1f78b4", Premium = "#a6cee3", Ideal = "#de77ae") 

ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point() + 
    scale_colour_manual(values = MyPalette) 

ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point() + 
    scale_colour_manual(values = MyPalette) 

enter image description here

enter image description here

+0

那麼容易!感謝Stibu。 –