2013-09-28 27 views
13

如何在不同的地塊上將相同的顏色固定在一個值上?ggplot2:如何在相同的因子在不同的地塊使用相同的顏色

說我有兩個data.frames DF1和DF2:

library(ggplot2) 
library(gridExtra) 

set.seed(1) 
df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5, y=runif(5)) 
df2 <- data.frame(c=c('a', 'c', 'e', 'g', 'h'), x=1:5, y=runif(5)) 

當他們使用C作爲顏色指示劑繪製我得到同樣的五種顏色。

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") 
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") 
grid.arrange(g1, g2, ncol=2) 

enter image description here

但我想是c的值相同會得到相同的顏色。

回答

8

我現在寫的,其產生計算色彩其他功能的功能。我不確定這是否是一種好方法。評論贊賞。

library(ggplot2) 
library(gridExtra) 
library(RColorBrewer) 

makeColors <- function(){ 
    maxColors <- 10 
    usedColors <- c() 
    possibleColors <- colorRampPalette(brewer.pal(9 , "Set1"))(maxColors) 

    function(values){ 
    newKeys <- setdiff(values, names(usedColors)) 
    newColors <- possibleColors[1:length(newKeys)] 
    usedColors.new <- c(usedColors, newColors) 
    names(usedColors.new) <- c(names(usedColors), newKeys) 
    usedColors <<- usedColors.new 

    possibleColors <<- possibleColors[length(newKeys)+1:maxColors] 
    usedColors 
    } 
} 

mkColor <- makeColors() 


set.seed(1) 
df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5, y=runif(5)) 
df2 <- data.frame(c=c('a', 'c', 'e', 'g', 'h'), x=1:5, y=runif(5)) 

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df1$c)) 
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df2$c)) 
grid.arrange(g1, g2, ncol=2) 

enter image description here

7

爲了使這種複合地塊,ggplot2具有小面:

df1$id = 'A' 
df2$id = 'B' 
df_all = rbind(df1, df2) 
ggplot(df_all, aes(x=x, y=y, fill=c)) + 
    geom_bar(stat="identity") + 
    facet_wrap(~id) 

enter image description here

當使用小面,ggplot2處理二者的圖解爲一個整體,保持色值映射相同的。

+2

只是在我的例子中,我把兩個地塊在一起。我真正的問題是由許多獨立的情節組成。 – JerryWho

11

您可以使用scale_fill_manual來設置自己的填充比例。我創建一個帶有顏色和不同值「c」的命名向量。

dd <- union(df1$c,df2$c) 
dd.col <- rainbow(length(dd)) 
names(dd.col) <- dd 

然後:

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + 
    geom_bar(stat="identity") + 
    scale_fill_manual("Legend", values = dd.col) 
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + 
    geom_bar(stat="identity") + 
    scale_fill_manual("Legend", values = dd.col) 
grid.arrange(g1, g2, ncol=2) 

enter image description here

+0

所以我必須知道我會使用多少種不同的顏色。在繪製每個繪圖的過程中,是否有辦法「收集」顏色?我的實際問題由許多獨立的情節組成,我不知道在開始時我會得到多少(以及什麼樣的)「c」值。 – JerryWho

相關問題