2017-10-16 7 views
0

그라데이션 채색 체계가있는 ggplot 데이터를 가지고 있으며 일부 포인트에 주석을 달았습니다.geom_point에 geom_text_repel 레이어를 scale_colour_gradient2로 채색하십시오.

내 데이터 : 내가 노력하고있어 ggplot 코드의 여기

df$col[sample(nrow(df), 10, replace = F)] <- rainbow(10) 

을 그리고 :

여기
df <- data.frame(id = rep(LETTERS,100), 
       val1 = rnorm(100*length(LETTERS)), val2 = rnorm(100*length(LETTERS)), 
       sig = runif(100*length(LETTERS),0,1), 
       col = NA,stringsAsFactors = F) 

나는 주석과 색상을 그들에게주고 싶은 몇 가지 포인트를 선택

library(ggplot2) 
library(ggrepel) 
ggplot(df,aes(x=val1,y=val2,color=col))+ 
    geom_point(aes(color=sig),cex=2)+scale_colour_gradient2("Significance",low="darkred",mid="darkblue",high="darkred")+ 
    geom_text_repel(data=dplyr::filter(df,!is.na(col)),aes(x=dplyr::filter(df,!is.na(col))$val1,y=dplyr::filter(df,!is.na(col))$val2,label=dplyr::filter(df,!is.na(col))$id,colour=dplyr::filter(df,!is.na(col))$col))+ 
    theme_minimal()+theme(legend.position="none") 

이 오류가 발생합니다 :

Error: Discrete value supplied to continuous scale 

아이디어가 있으십니까?

답변

3

기본적으로 두 가지 접근 방식이 있습니다. 하나는 연속 변수를 채우기 위해 매핑하고 별개의 텍스트 변수는 aes 호출 내에서 색상을 지정하는 것입니다. 그리고 다른 하나는 연속 변수를 aes 내부의 색상으로 매핑하고 aes 호출 외부에서 텍스트를 수동으로 매핑하는 것입니다.

첫 번째 방법 - 연속 눈금을 채우기로 매핑하고 채우기 미학을 지원하는 모양 (pch = 21)을 사용합니다. scale_fill_gradientn을 사용하고 색상이 데이터 범위에 있어야하는 위치를 수동으로 정의했습니다 (values = scales::rescale(c(min(df$sig), median(df$sig), max(df$sig)))).

그 후에는 개별적인 스케일 (라벨을 물리 치지 않음)을 컬러 미학으로 매핑하는 것이 쉽습니다. 그러나 하나 scale_colour_manual

library(tidyverse) 

ggplot(df,aes(x = val1, y = val2))+ 
    geom_point(aes(fill = sig), cex=2, pch = 21)+ 
    scale_fill_gradientn("Significance",colors = c("darkred", "darkblue","darkred"), values = scales::rescale(c(min(df$sig), median(df$sig), max(df$sig))))+ 
    geom_text_repel(data = dplyr::filter(df,!is.na(col)) %>% 
        mutate(col = factor(col, levels = col)), 
        aes(x = val1, y = val2, label = id, color = col), size = 6)+ 
    scale_colour_manual(values = dplyr::filter(df,!is.na(col))[,5])+ 
    theme_minimal()+ 
    theme(legend.position = "none") 

enter image description here

두번째 접근 방식에 제공된 색상과 일치하는 수준의 순서를 정의 할 필요가있다 -는 AES 호출 외부 geom_text_repel의 색상을 지정합니다.

ggplot(df,aes(x = val1, y = val2)) + 
    geom_point(aes(color= sig), cex=2) + scale_colour_gradient2("Significance",low="darkred",mid="darkblue",high="darkred")+ 
    geom_text_repel(data = dplyr::filter(df,!is.na(col)), aes(x = val1, y = val2, label = id), color = dplyr::filter(df,!is.na(col))[,5], size = 6)+ 
    theme_minimal()+ 
    theme(legend.position = "none") 

enter image description here

+0

덕분에 많이 @missuse. 색 구성표를 이산화하는 것이 유일한 해결책이라고 생각하십니까? – dan

+0

@ 단, 다른 해결책을 추가했습니다. 편집 확인 – missuse