2017-10-16 221 views
0

我有數據,我想用ggplot用漸變着色方案,然後註釋一些要點。將geom_text_repel圖層添加到由scale_colour_gradient2着色的geom_point

我的數據:

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) 

在這裏,我選擇了幾個點,我想註釋,給他們顏色:

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

而這裏的ggplot代碼我想:

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

@dan,增加了另一種解決方案。檢查了它 – missuse