R - 平滑颜色并向散点图添加图例

Sta*_*nLe 3 interpolation r legend scatter-plot heatmap

我在R中有一个散点图.每个(x,y)点都根据其z值着色.所以,你可以把每个点为(x,y,z),在(x,y)确定其位置,并z确定其沿彩色渐变色.我想补充两件事

  1. 右侧的图例显示颜色渐变,哪些z值对应于什么颜色
  2. 我想,我想使用某种类型的插值来平滑所有颜色.换句话说,整个绘图区域(或至少大部分绘图区域)应该变为彩色,以使其看起来像一个巨大的热图而不是散点图.所以,在下面的例子中,周围会有很多橙色/黄色,然后是一些紫色斑点.如果需要的话,我很高兴进一步澄清我在这里要解释的内容.

这是我目前的代码,以及它制作的图像.

x <- seq(1,150)
y <- runif(150)
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))
colorFunction <- colorRamp(rainbow(100))
zScaled <- (z - min(z)) / (max(z) - min(z))
zMatrix <- colorFunction(zScaled)
zColors <- rgb(zMatrix[,1], zMatrix[,2], zMatrix[,3], maxColorValue=255)
df <- data.frame(x,y)
x <- densCols(x,y, colramp=colorRampPalette(c("black", "white")))
df$dens <- col2rgb(x)[1,] + 1L
plot(y~x, data=df[order(df$dens),],pch=20, col=zColors, cex=1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ial*_*alm 7

以下是使用该ggplot2包的一些解决方案.

# Load library
library(ggplot2)

# Recreate the scatterplot from the example with default colours
ggplot(df) +
  geom_point(aes(x=x, y=y, col=dens))

# Recreate the scatterplot with a custom set of colours. I use rainbow(100)
ggplot(df) +
  geom_point(aes(x=x, y=y, col=dens)) +
  scale_color_gradientn(colours=rainbow(100))

# A 2d density plot, using default colours
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..level..), geom="polygon") +
  ylim(-0.2, 1.2) + xlim(-30, 180) # I had to twiddle with the ranges to get a nicer plot

# A better density plot, in my opinion. Tiles across your range of data
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE)

# Using custom colours. I use rainbow(100) again.
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE) +
  scale_fill_gradientn(colours=rainbow(100))

# You can also plot the points on top, if you want
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE) +
  geom_point(aes(x=x, y=y, col=dens)) +
  scale_colour_continuous(guide=FALSE) # This removes the extra legend
Run Code Online (Sandbox Code Playgroud)

我也附上了这些情节:

情节