2013-06-03 77 views
4

我使用色階繪製了一些圖像數據。我想從圖像中挑出一條線,並在曲線圖上繪製曲線圖,並使用曲線上的相同色標,如同在圖像中那樣。這可能嗎?ggplot2中曲線的色階

想我繪製我的圖片如下

require(ggplot2) 
n <- 100 # number of observations 
cols <- topo.colors(256) # color scheme 
lim <- c(-10, 10) # limits corresponding to color scheme 

x <- seq(0, 1, length = n) # x-axis 
y <- cumsum(rnorm(n)) # Brownian motion 

dat <- data.frame(x, y) # data 

# Plot 
ggplot(dat, aes(x, y)) + geom_line() + scale_y_continuous(limits = lim) 

Resulting plot

我想同樣顏色的線以下情節

Color scale plot

創建與下面的代碼

colscale <- function(y, cols, ylim) { 
    k <- length(cols) 
    steps <- seq(ylim[1], ylim[2], length = k) 

    result <- sapply(y, function(x) {cols[which.min(abs(x - steps))]}) 
    return(result) 
} 

plot(x, y, ylim = lim, col = colscale(y, cols, lim)) 
+0

我不是一個ggplot用戶,但與其他情節我用彩色沿着線段線的東西。 –

回答

6

這很簡單。你只需要兩樣東西:

  1. 指定變量的顏色變化着,在這種情況下y
  2. 添加調色板。

所以:

ggplot(dat, aes(x, y)) + 
    scale_y_continuous(limits = lim) + 
    geom_line(aes(colour=y)) + 
    scale_colour_gradientn(colours = topo.colors(256)) 

enter image description here

+0

非常感謝!正是我需要的! –