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

时间:2013-11-20 00:56:52

标签: r interpolation legend heatmap scatter-plot

我在R中有一个散点图。每个(x,y)点都根据其z值着色。因此,您可以将每个点视为(x,y,z),其中(x,y)确定其位置,z沿颜色渐变确定其颜色。我想补充两件事

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

    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 个答案:

答案 0 :(得分: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 :(得分: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. 不幸的是,您无法组合连续的图例(颜色)和a 离散的图例(大小),所以你通常会得到两个传说。该 表达式guide="none"隐藏了大小图例。

  3. 这是情节: