【问题标题】:2-D Scatter Plot with Gradient Color Legend on Top顶部带有渐变颜色图例的二维散点图
【发布时间】:2014-02-18 23:52:56
【问题描述】:

我正在尝试显示二维彩色散点图 - 即 Y 作为 X 的函数,点颜色由 Z 驱动。

我希望 Z 颜色渐变图例位于顶部,最好位于主情节标题下方。

我从this SO 中启发了自己,在右侧使用 Z 颜色渐变导出以下函数:

library(grDevices)
library(colorRamps)

# 2-dim scatter plot with color gradient legend on top.
scatterPlot2DWithColorLegend <- function(x, y, z, colorGradient, legendTitle=""
                                         , main="", xlab="", ylab="", pch=16, cex=1)
{
  parPrev <- par()
  nColorGradient <- length(colorGradient)
  labelRange <- zRange <- range(z)
  layout(matrix(1:2, nrow=2), widths = c(1), heights = c(1, 2), FALSE) # 2 plots, one above the other.
  # Plot legend first on top.
  plot(c(0, 1), c(0, 0.05), type = 'n', axes = F, xlab = '', ylab = '', main = legendTitle, cex.main=0.5)
  legend_image <- as.raster(matrix(colorGradient, nrow = 1))
  text(x = seq(0, 1, l = 5), y = 0.1 , labels = seq(labelRange[1], labelRange[2], l = 5), pos=1)
  rasterImage(legend_image, 0, 0, 1, 1)
  # Main plot second on bottom.
  if (1 < length(unique(zRange)))
    colVec = colorGradient[as.numeric(cut(z, nColorGradient))]
  else
    colVec = colorGradient[1]
  plot(x, y, col = colVec
       ,    main = main, xlab = xlab, ylab = ylab, pch = pch, cex = cex)
  par(parPrev)
}

这是一个简单的测试代码:

# Test data.
mdf <- data.frame(X=c(0:10))
mdf$Y <- mdf$X * 3
mdf$Z <- (mdf$X-5)^2

# Color gradient function.
colorGradient <- colorRampPalette(c("blue", "green", "yellow", "red"))(4)

# 2-D colored scatter plot.
scatterPlot2DWithColorLegend(mdf$X, mdf$Y, mdf$Z, colorGradient
                             , legendTitle="Z", main="Y vs. X with Z-Color", ylab="Y", xlab="X"
                             , pch=16, cex=0.7)

使用上面的scatterPlot2DWithColorLegend 函数,我得到:

我想要这样的东西:

有人可以快速提供 scatterPlot2DWithColorLegend 函数的增强版本,或者将我指向一个现有的包/函数,它可以得到我想要的吗?即:

  1. 颜色渐变图例上方的主标题(Y 与 X 与 Z-Color)。
  2. Z 色渐变图像更小,高度和宽度。
  3. 底部的 Z 色渐变 Z 范围(Z 范围当前不显示)。
  4. Z 色渐变图例位于 Z 色渐变图像左侧,而不是顶部(即,legendTitle="Z")。
  5. 显着缩小主标题、颜色渐变图例和主散点图之间的间距。

显然,我不太了解 R 图形。我也不熟悉 lattice、ggplot 和种类——选项的数量似乎是压倒性的。我想要一些简单的东西,我可以重复使用它来克服这个特定的问题,因为这看起来很基本。

提前感谢您的帮助。

【问题讨论】:

  • 您在下面有一些很好的ggplot 答案,但previous question 也同样涵盖了这一点。

标签: r plot


【解决方案1】:

这是ggplot 替代方案:

ggplot(data = mdf, aes(x = X, y = Y, col = Z)) +
  geom_point() +
  scale_colour_gradientn(colours = colourGradient) +
  theme_bw() +
  theme(legend.position = "top") +
  ggtitle("Y vs. X with Z-Color")

【讨论】:

  • 感谢您的反馈。是的,绝对值得一试ggplot。 This tutorial 可能是一个好的开始。以及带有所有示例输出的官方帮助页面here。祝你好运!
猜你喜欢
  • 2012-02-12
  • 1970-01-01
  • 2023-03-08
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 2017-07-19
相关资源
最近更新 更多