首页 文章

顶部带有渐变颜色图例的二维散点图

提问于
浏览
1

我试图显示一个二维彩色散点图 - 即Y作为X的函数,由Z驱动的点颜色 .

我希望Z颜色渐变图例位于顶部,理想情况下位于主图 Headers 之下 .

我从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 函数,我得到:

enter image description here

我想要的东西:

enter image description here

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

  • 颜色渐变图例上方的主 Headers (Y与X颜色为Z颜色) .

  • Z色渐变图像更小,高度和宽度 .

  • 底部的Z颜色渐变Z范围(当前未显示Z范围) .

  • Z颜色渐变图像左侧的Z颜色渐变图例而不是顶部(即legendTitle = "Z") .

  • 显着减少主 Headers ,颜色渐变图例和主散点图之间的间距 .

显然,我不太了解R图形 . 我不熟悉格子,ggplot和种类 - 选项的数量似乎是压倒性的 . 我想要一些简单的工作,我可以重复使用,以克服这个特定的驼峰,因为这似乎是非常基本的 .

在此先感谢您的帮助 .

1 回答

  • 2

    这是一个 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")
    

    enter image description here

相关问题