2017-03-19 3 views
2

한 플롯에서 내 데이터의 일부 하위 그룹과 다른 플롯에서 다른 하위 그룹을 비교하려고합니다. 모든 하위 그룹이 플로팅 된 한 줄을 만들면 그 숫자는 압도적이며 각 개별 비교는 어려워집니다. 주어진 서브 그룹이 모든 플롯에서 같은 색이라면 독자에게 더 이해할 수있을 것입니다.ggplots에서 색상 구성표를 유지하면서 각 플롯에서 사용되지 않는 레벨을 삭제하려면 어떻게해야합니까?

다음은 내가 시도한 두 가지 작업이지만 거의 작동하지 않습니다. 그들은 내가 MWE에 올 수있는만큼 가깝다!

잘못된 세 가지 수준이 범례에 드롭의 생각과 일치되지 않은 플롯 수준은 여전히 ​​범례에 나타납니다

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) 

주 (도시 있기 때문에 = 그릇된).

잘못된 두 번째 플롯은 왼쪽 플롯 setosa에서 = 빨간색과 virginica하는 최초의 음모에 의해

# 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

관련 문제