在散点图中添加平滑颜色和图例

3
我在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)

enter image description here

2个回答

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

我附上了图表:

The Plots


(注:该段文本已经是中文,无需翻译)

1
哎呀,忽略掉“平滑”的图表吧。那些并不是使用数据集中给定的z值生成的,而是由(x,y)值的接近程度生成的。 - ialm
这些图表很漂亮。感谢您的回答。我真的想要一些不使用ggplot的东西,因为我不熟悉它。但是这些图表太好看了,我可能需要花几天时间学习ggplot。 - StanLe

1
此外,使用ggplot2,您可以同时使用颜色和大小,例如:
ggplot(df, aes(x=x, y=y, size=dens, color=dens)) + geom_point() + 
scale_color_gradientn(name="Density", colours=rev(rainbow(100))) +
scale_size_continuous(range=c(1,15), guide="none")

这可能会使它更清晰。

注:

  1. 表达式rev(rainbow(100))将彩虹色标尺反转,使得红色与较大的dens值相对应。

  2. 不幸的是,您不能同时使用连续的图例(颜色)和离散的图例(大小),因此通常会得到两个图例。表达式guide="none"隐藏了大小图例。

这是绘图:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接