基于距 0:0 行的距离的颜色渐变散点图

Scatter plot with color gradient based on distance from 0:0 lines

我目前正在尝试更改散点图中各点的颜色。我希望颜色从白色变为另一种颜色(红色、蓝色......),同时这些点远离 0 水平和垂直轴。这是一个绘制的例子! This is what kind of colors I want.

y <- c(rnorm(5000, mean = 0), rnorm(500, mean = 0))
df <- data.frame(x, y)
plot(df$x ~ df$y,xlim=c(-4,4),ylim=c(-4,4))
abline(h=0,lty=2);abline(v=0,lty=2)

我尝试处理线性模型的残差,但我不知道如何达到我想要的效果。 我更喜欢基本的 R,因为我不使用 ggplot。

非常感谢!

这个 base-R 解决方案可能适合您:

df <- data.frame(x = rnorm(500, mean = 0),
                 y = rnorm(500, mean = 0))
dist <- sapply(1:nrow(df),function(i){min(abs(df[i,c('x','y')]))})
dist <- dist/max(dist)
df$lightness <- (1-round(dist,2))
df$color <- with(df,ifelse(x >0, 
                           ifelse(y >0,rgb(lightness,1,lightness),rgb(1,lightness,lightness)),
                           ifelse(y >0,rgb(lightness,lightness,1),rgb(1,lightness,1))))

plot(df$x ~ df$y,xlim=c(-4,4),ylim=c(-4,4),col = df$color,pch =20)
abline(h=0,lty=2);abline(v=0,lty=2)


编辑:

如果像这样设置 alpha 值可能会更好:

df <- data.frame(x = rnorm(500, mean = 0),
                 y = rnorm(500, mean = 0))
dist <- sapply(1:nrow(df),function(i){min(abs(df[i,c('x','y')]))})
dist <- dist/max(dist)
df$lightness <- round(dist,2)
df$color <- with(df,ifelse(x >0, 
                           ifelse(y >0,rgb(.7,0,0,lightness),rgb(.8,.6,0,lightness)),
                           ifelse(y >0,rgb(.1,.4,.7,lightness),rgb(.1,.5,.1,lightness))))

plot(df$x ~ df$y,xlim=c(-4,4),ylim=c(-4,4),col = df$color,pch =20)
abline(h=0,lty=2);abline(v=0,lty=2)

这样您就可以完全自由地选择颜色了。


编辑 2

并使用矢量化最小值(来自 here)以提高效率:

library(tidyverse)
df <- data.frame(x = rnorm(10000, mean = 0),
                 y = rnorm(10000, mean = 0))
dist <- pmin(abs(df$x), abs(df$y))
dist <- dist/max(dist)
df$lightness <- round(dist,2)
df$color <- with(df,ifelse(x >0, 
                           ifelse(y >0,rgb(.7,0,0,lightness),rgb(.8,.6,0,lightness)),
                           ifelse(y >0,rgb(.1,.4,.7,lightness),rgb(.1,.5,.1,lightness))))

plot(df$x ~ df$y,xlim=c(-4,4),ylim=c(-4,4),col = df$color,pch =20)
abline(h=0,lty=2);abline(v=0,lty=2)