2017-03-19 7 views
2

私のデータのいくつかのサブグループを1つのプロットで比較し、他のサブグループを別のプロットで比較したいと考えています。すべてのサブグループをプロットして1つのプロットを作成すると、図が圧倒され、個々の比較が難しくなります。私は、与えられたサブグループがすべてのプロットで同じ色であれば、読者にはもっと意味があると思います。各プロットで未使用のレベルを落としながら、どのようにggplotsに配色を維持できますか?

これは私が試みた2つのことですが、ほとんど動作しますが、どちらも動作しません。彼らは私がMWEに来ることができるほど近いです!

間違ったすべての3つのレベルが凡例のドロップの考えと一致して未プロットレベルは依然として凡例に表示されていること

library(tidyverse) 

# compare first and second species 
ggplot(data = iris %>% filter(Species != 'virginica'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_discrete(drop = FALSE) 


# compare second and third species 
ggplot(data = iris %>% filter(Species != 'setosa'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_discrete(drop = FALSE) 

注(図示されているので= FALSE)。

間違っ左プロットsetosa =赤とvirginicaの中に第2のプロットは、最初のプロットによって確立された種のカラーマッピングを

# compare first and second species 
ggplot(data = iris %>% filter(Species != 'virginica'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_manual(values = c('red', 'forestgreen', 'blue'), 
        breaks = unique(iris$Species)) 


# compare second and third species 
ggplot(data = iris %>% filter(Species != 'setosa'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_manual(values = c('red', 'forestgreen', 'blue'), 
        breaks = unique(iris$Species)) 

注意を維持しないため=緑色ですが、右側のプロットではマッピングが変更されています。

答えて

1

最も効果的な方法は、各レベル(種)ごとに名前のついた変数を設定し、それを各プロットで使用することです。ここで

、あなたは上記使用したのと同じ色を使用することができますが、変数に名前を追加することによって、あなたは彼らが常に正しく一致していることを確認してください。

irisColors <- 
    setNames(c('red', 'forestgreen', 'blue') 
      , levels(iris$Species) ) 

setosa  versicolor  virginica 
"red" "forestgreen"  "blue" 

そしてを与えますそれを使用して色を設定することができます:

すべての色で最初に:

ggplot(data = iris, 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_manual(values = irisColors) 

enter image description here

次に、あなたの質問からサブセットのそれぞれ:

ggplot(data = iris %>% filter(Species != 'virginica'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_manual(values = irisColors) 

enter image description here

ggplot(data = iris %>% filter(Species != 'setosa'), 
     mapping = aes(x = Sepal.Length, 
        y = Sepal.Width, 
        color = Species)) + 
    geom_point() + 
    scale_color_manual(values = irisColors) 

enter image description here

+0

完璧 - ありがとう! – rcorty

関連する問題