ggplot2中曲线的颜色刻度

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)

结果图

我想要将线条的颜色与以下图表类似

颜色比例图

使用以下代码创建

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))

我不是 ggplot 用户,但在使用其他绘图时,我会使用彩色线段之类的东西。 - Marc in the box
1个回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接