Color scale for curves in ggplot2

I have some image data plotted using the color bar. I want to select a line from the image and plot the graph in ggplot2 using the same color scale on the curve as on the image. Is it possible?

Suppose I draw my image as follows

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

I want to color the line as in the following image

Color scale plot

Created using the following code

 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)) 
+4
source share
1 answer

It is pretty simple. You just need two things:

  • Specify the variable with which the color changes, in which case y
  • Add a color palette.

So:

 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

+6
source

Source: https://habr.com/ru/post/1484160/


All Articles