如何在R中制作渐变颜色填充的时间序列图 [英] How to make gradient color filled timeseries plot in R

查看:870
本文介绍了如何在R中制作渐变颜色填充的时间序列图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用渐变颜色在(sp)线下和上方填充区域

How to fill area under and above (sp)line with gradient color?

此示例包含在Inkscape中绘制-但我需要垂直渐变-不是水平。

This example has been drawn in Inkscape - BUT I NEED vertical gradient - NOT horizontal.


零开始的间隔变为阳性 ==从白色变为红色

==从白色红色

是否有任何 软件包 可以做到这一点?

Is there any package which could do this?

我捏造了一些源数据。 ...

I fabricated some source data....

set.seed(1)
x<-seq(from = -10, to = 10, by = 0.25)
data <- data.frame(value = sample(x, 25, replace = TRUE), time = 1:25)
plot(data$time, data$value, type = "n")
my.spline <- smooth.spline(data$time, data$value, df = 15)
lines(my.spline$x, my.spline$y, lwd = 2.5, col = "blue")
abline(h = 0)


推荐答案

这是在 base R中的一种方法,我们用渐变色的矩形填充整个绘图区域,然后用白色填充感兴趣区域的反面。

And here's an approach in base R, where we fill the entire plot area with rectangles of graduated colour, and subsequently fill the inverse of the area of interest with white.

shade <- function(x, y, col, n=500, xlab='x', ylab='y', ...) {
  # x, y: the x and y coordinates
  # col: a vector of colours (hex, numeric, character), or a colorRampPalette
  # n: the vertical resolution of the gradient
  # ...: further args to plot()
  plot(x, y, type='n', las=1, xlab=xlab, ylab=ylab, ...)
  e <- par('usr')
  height <- diff(e[3:4])/(n-1)
  y_up <- seq(0, e[4], height)
  y_down <- seq(0, e[3], -height)
  ncolor <- max(length(y_up), length(y_down))
  pal <- if(!is.function(col)) colorRampPalette(col)(ncolor) else col(ncolor)
  # plot rectangles to simulate colour gradient
  sapply(seq_len(n),
         function(i) {
           rect(min(x), y_up[i], max(x), y_up[i] + height, col=pal[i], border=NA)
           rect(min(x), y_down[i], max(x), y_down[i] - height, col=pal[i], border=NA)
         })
  # plot white polygons representing the inverse of the area of interest
  polygon(c(min(x), x, max(x), rev(x)),
          c(e[4], ifelse(y > 0, y, 0), 
            rep(e[4], length(y) + 1)), col='white', border=NA)     
  polygon(c(min(x), x, max(x), rev(x)),
          c(e[3], ifelse(y < 0, y, 0), 
            rep(e[3], length(y) + 1)), col='white', border=NA)      
  lines(x, y)
  abline(h=0)
  box()  
}

以下是一些示例:

xy <- curve(sin, -10, 10, n = 1000)
shade(xy$x, xy$y, c('white', 'blue'), 1000)

或使用颜色渐变调色板指定的颜色:

Or with colour specified by a colour ramp palette:

shade(xy$x, xy$y, heat.colors, 1000)

< img src = https://i.stack.imgur.com/3u5UD.png alt = pic2>

并应用于您的数据,尽管我们首先将这些点插值到更精细的分辨率(如果不这样做,则渐变将不会紧跟其穿过零的线)。

And applied to your data, though we first interpolate the points to a finer resolution (if we don't do this, the gradient doesn't closely follow the line where it crosses zero).

xy <- approx(my.spline$x, my.spline$y, n=1000)
shade(xy$x, xy$y, c('white', 'red'), 1000)

这篇关于如何在R中制作渐变颜色填充的时间序列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆