2013-09-28 30 views
13

どのようにして同じ色を異なるプロットの値に固定できますか?私は同じ5色を取得するカラー指標としてCを使用してそれらをプロットするとggplot2:同じ要素の異なるプロットで同じ色を使用する方法

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

は、私は2 data.frames DF1とDF2を持っていると言います。

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扱い1つの全体としての両方のプロット、同じ色値のマッピングを維持します。

+2

ちょうど私の例では、私は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

関連する問題