繁体   English   中英

使用R中的自定义颜色绘制光栅图像

[英]Plotting raster images using custom colours in R

这可能听起来像一个奇怪的过程,但它是我能想到的最好的控制相对于离散对象(点,线,多边形)的光栅化颜色渐变。 我95%那里,但不能正确绘图。

这应该说明概念证明:

require(raster)
r = matrix(56:255, ncol=20)         # reds
b = t(matrix(56:255, ncol=10))      # blues
col = matrix(rgb(r, 0, b, max=255), ncol=20) # matrix of colour strings
ras = raster(r)                     # data raster object
extent(ras) = extent(1,200,1,100)   # set extent for aspect
plot(ras, col = col, axes=F, asp=T) # overwrite data with custom colours

在此输入图像描述

在这里,我想将栅格剪切为三角形,并根据它们与其中一个边的距离创建内部像素的颜色渐变。 抱歉长度,但它是我可以设计的最小的例子。

require(raster); require(reshape2); require(rgeos)
# equilateral triangle
t_s = 100                            # half side
t_h = floor(tan(pi*60/180) * t_s)    # height
corners = cbind(c(0, -t_s, t_s, 0), c(t_h, 0, 0, t_h))
trig = SpatialPolygons(list(Polygons(list(Polygon(corners)),"triangle")))

# line to measure pixel distances to
redline = SpatialLines(list(Lines(Line(corners[1:2,]), ID='redline')))
plot(trig); plot(redline, add=T, col='red', lwd=3)

在此输入图像描述

# create a blank raster and clip to triangle
r = raster(mat.or.vec(nc = t_s*2 + 1, nr = t_h))
extent(r) = extent(-t_s, t_s, 0, t_h)
r = mask(r, trig)
image(r, asp=T)

在此输入图像描述

# extract cell coordinates into d.f.
cells = as.data.frame(coordinates(rasterToPoints(r, spatial=T)))

# calculate distance of each pixel to redline with apply
dist_to_line = function(xy, line){
  point = readWKT(paste('POINT(', xy[1], xy[2], ')'))
  gDistance(point, line) / t_h
}

cells$dists = apply(cells, 1, dist_to_line, line=redline)
cells$cols = rgb(1 - cells$dists, 0, 0)
length(unique(cells$cols)) # count unique colours

# use custom colours to colour triangle pixels
image(r, col = cells$cols, asp=T)
plot(r, col = cells$cols, asp=T)

在此输入图像描述

如您所见,绘图无法像第一个示例中那样覆盖,但数据似乎很好。 尝试转换为矩阵也会失败:

# try convertying colours to matrix
col_ras = acast(cells, y~x, value.var='cols')
col_ras = apply(col_ras, 1, rev) # rotate acw to match r
plot(r, col = col_ras, asp=T)

非常感谢任何有关出错的帮助。


编辑:

要显示Spacedman的plotRGB方法:

b = brick(draster, 1-draster, 1-draster)
plotRGB(b, scale=1)
plot(trig, col=NA, border='white', lwd=5, add=T)

在此输入图像描述

简单的方法是从你的点到空间像素数据框到光栅,然后进行颜色映射......

从...开始:

> head(cells)
           x     y        dists
1  0.0000000 172.5 0.0014463709
2  0.0000000 171.5 0.0043391128
3 -0.9950249 170.5 0.0022523089
4  0.0000000 170.5 0.0072318546
5  0.9950249 170.5 0.0122114004

兑换:

> coordinates(cells)=~x+y
> draster = raster(as(cells,"SpatialPixelsDataFrame"))

colourise:

> cols=draster
> cols[!is.na(draster)]= rgb(1-draster[!is.na(draster)],0,0)
> plot(cols, col=cols)

在此输入图像描述

我不确定这是做正确事情的正确方法,如果你想要精细的色彩控制,你可能最好创建一个RGB光栅堆栈并使用plotRGB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM