2017-10-16 214 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