2014-01-27 76 views
1

我想顯示2 d色的散點圖 - 即,Y與Z的通過驅動2-d散點圖與漸變顏色圖例上最

點顏色X的功能

我想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功能如上,我得到:

enter image description here

我希望是這樣的:

enter image description here

有人能迅速提供scatterPlot2DWithColorLegend功能的增強版本,或點我到現有的包裝/功能,將讓我我想要什麼?即:

  1. 顏色漸變圖例上方的主標題(Y與X與Z顏色)。
  2. Z色梯度圖像較小,高度和寬度。
  3. 底部的Z色梯度Z-範圍(Z-範圍目前未顯示)。
  4. Z-color漸變圖例與Z-color梯度圖像左邊相反的頂部(即legendTitle =「Z」)。
  5. 顯着減少主標題,顏色漸變圖例和主散點圖之間的間距。

顯然,我不太明白R圖形。我對晶格,ggplot和種類都不熟悉 - 選項的數量顯得過於龐大。我想要一些簡單的作品,我可以重複使用來克服這個特定的駝峯,因爲這看起來很基本。

在此先感謝您的幫助。

+0

你已經有了一些很好的'ggplot'下面的答案,但是這也同樣涵蓋在這個[先前的問題(HTTP:// stackoverflow.com/questions/13355176/gradient-legend-in-base/13389693#13389693)。 – thelatemail

回答

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

+0

+1哈哈,快... –

+0

謝謝!這讓我相信我必須學習ggplot! – Patrick

+1

感謝您的反饋。是的,絕對值得'ggplot'一試。 [本**教程**](http://www.cookbook-r.com/Graphs/)可能是一個好的開始。以及所有示例[** here **]的輸出的官方幫助頁面(http://docs.ggplot2.org/current/)。祝你好運! – Henrik