簡體   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