添加一个 geom_text_repel 层到 geom_point 颜色 scale_colour_gradient2

Add a geom_text_repel layer to geom_point colored by scale_colour_gradient2

我有一些数据,我想 ggplot 使用渐变着色方案,然后注释一些点。

我的数据:

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)

这里我select有几点我想注释并给它们颜色:

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

有什么想法吗?

基本上有两种方法。一种是在 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")

第二种方法 - 在 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")