Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot2中曲线的颜色比例_R_Ggplot2 - Fatal编程技术网

R ggplot2中曲线的颜色比例

R ggplot2中曲线的颜色比例,r,ggplot2,R,Ggplot2,我用色标绘制了一些图像数据。我想从图像中选择一条线,并在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,

我用色标绘制了一些图像数据。我想从图像中选择一条线,并在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)
require(ggplot2)

这是相当简单的。你只需要两件事:

  • 指定颜色变化的变量,在本例中为
    y
  • 添加调色板
  • 因此:


    我不是ggplot用户,但在其他绘图中,我使用的是彩色线段的线条。非常感谢!正是我需要的!
    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(dat, aes(x, y)) + 
      scale_y_continuous(limits = lim) +
      geom_line(aes(colour=y)) + 
      scale_colour_gradientn(colours = topo.colors(256))