通过单独的配色方案为 ggplot2 散点图的第二层着色而不添加到数据框

Coloring a second layer of a ggplot2 scatterplot by a separate color scheme without adding to data frame

我正在尝试开发一个闪亮的小程序,它本质上是一个灰色的散点图,上面有几个突出显示的点以另一种颜色绘制。我需要的是绘制在灰点之上的点遵循由另一个变量确定的特定配色方案。据我所知,通过将这些值合并到数据框中会相对简单,但由于这是一个闪亮的应用程序,因此需要花费大量时间(其中一些数据集有数万个点) ,因为每次更改点子集时都需要重新计算原始数据框(而不是仅使用绘制的不同子集更新绘图本身)。

不知何故,我无法让第二层数据遵循所需的配色方案(见下文,我还尝试了其他具有非用户定义配色方案的 scale_*_ 函数,但它不会'也不要让步)。我也尝试过改变通话的位置。

这是我的代码,没有闪亮的上下文(并且使用通用数据,用于简化的变量示例):

library(ggplot2)
#color scheme I want the highlighted points to be in
jet.colors <- colorRampPalette(c("#7F0000", "red", "#FF7F00", "yellow", "#7FFF7F", "cyan", "#007FFF", "blue", "#00007F"))

#points to plot
test.data <- data.frame(variabs = runif(144*96),means = runif(144*96))

#variable to color highlighted points by (put in a grid the same size as the input data)
lat <- seq(-90,90,by=180/95) #(it's geospatial data)
latyy <- t(matrix(1,96,144)*abs(lat))

#which points to highlight/plot again in color
idx_region <- sample(seq(1:(96*144)),250)

#ggplot setup 
p <-  ggplot(test.data,
          aes_string(x="means",y="variabs")) +
      geom_point(size=0.5,color="grey",show.legend=FALSE) + ## First (gray) points layer
      geom_point(data=test.data[idx_region,], ## Second (highlighted, colored) points layer
                 aes_string(x="means",y="variabs"),
                 color=latyy[idx_region],
                 size=1,show.legend=TRUE) +
      scale_colour_gradientn(colors = jet.colors(18)) + ## My attempt at coloring
      labs(x = "Mean",y = "Variability") + 
      geom_abline(intercept=0,slope=1,linetype='dashed') +
      geom_hline(yintercept=0) + geom_vline(xintercept=0)

提前感谢您的帮助!

您需要在 aes_string 中包含 color=latyy[idx_region] 以指定颜色来自数据(与在 aes_string 之外定义的 `color="grey" 相反):

ggplot(test.data,
             aes_string(x="means",y="variabs")) +
  geom_point(size=0.5,color="grey",show.legend=FALSE) + 
  geom_point(data=test.data[idx_region,], 
             aes_string(x="means",y="variabs",
             color="latyy[idx_region]"),
             size=1,show.legend=TRUE) +
  scale_colour_gradientn(colors = jet.colors(18)) +
  labs(x = "Mean",y = "Variability") + 
  geom_abline(intercept=0,slope=1,linetype='dashed') +
  geom_hline(yintercept=0) + geom_vline(xintercept=0)