在R中绘制一个双变量地图

Phi*_*tin 3 r raster geospatial ggplot2 r-raster

我正在尝试绘制从R中的地图上的栅格数据集中获取的两个变量,以产生看起来像这样的东西:

在此输入图像描述

然而,理想情况下,我希望从左下角到右上角的比例为灰度(从浅灰色到黑色),从而突出显示两个变量几乎没有差异的区域.

到目前为止,这是我到目前为止使用的包装彩色板:

#load packages
require(raster)
require(colorplaner)
require(ggplot2)


#here's some dummy data
r1<- raster(ncol=10, nrow=10)
set.seed(0)
values(r1) <- runif(ncell(r1))
r2<- raster(ncol=10, nrow=10)
values(r2) <- runif(ncell(r2))

#here I create a grid with which I can  extract information on the raster datasets
grid<-raster(ncol=10, nrow=10)
grid[] <- 1:ncell(grid)
grid.pdf<-as(grid, "SpatialPixelsDataFrame")
grid.pdf$r1<-(extract(r1,grid.pdf))
grid.pdf$r2<-(extract(r2,grid.pdf))

#here I convert the grid to a dataframe for plotting in ggplot2
grid.df<-as.data.frame(grid.pdf)
ggplot(data=grid.df,aes(x,y,fill=r1,fill2=r2))+geom_raster()+scale_fill_colourplane("")
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

在此输入图像描述 这个默认的colourscale并不真正适合我的需求 - 我更喜欢这个从这个网站看起来像这样的比例:

在此输入图像描述

但是我发现修改函数中的colourscheme很棘手 scale_fill_colourplane

最接近我想要的颜色是我想要的:

ggplot(data=grid.df,aes(x,y,fill=r1,fill2=r2))+
geom_raster()+
scale_fill_colourplane(name = "",na.color = "white",
color_projection = "interpolate",vertical_color = "#FAE30C",
horizontal_color = "#0E91BE", zero_color = "#E8E6F2",
limits_y = c(0,1),limits=c(0,1))
Run Code Online (Sandbox Code Playgroud)

这给了我这个,但这不是我想要的: 在此输入图像描述

有关于如何修改中使用的colorscales信息scale_fill_colourplane功能,在这里这使得它看起来像我应该可以做我想做的,但我不能完全弄清楚.

有谁知道我怎么能达到我想要的目的?我愿意使用其他软件包,但ggplot2如果可能的话,我更喜欢用于绘图,以便这个数字与我正在为我正在制作的内容制作的其他软件一致.

tim*_*cas 8

你可以通过思考HSV空间来做到这一点. https://en.wikipedia.org/wiki/HSL_and_HSV

沿45度线的距离是值(从浅到深).

该线的距离是饱和度(单色到彩色)

两种不同的颜色只是两种色调选择.

# hsv
# Position along diagonal is value
# Distance from the diagonal is saturation
# upper triangle or lower triangle is hue.

col_func <- function(x, y){

  x[x == 0] <- 0.000001
  y[y == 0] <- 0.000001
  x[x == 1] <- 0.999999
  y[y == 1] <- 0.999999

  # upper or lower triangle?
  u <- y > x

  # Change me for different hues.
  hue <- ifelse(u, 0.3, 0.8)


  # distace from (0,0) to (x,y)
  hyp <- sqrt(x^2 + y^2) 

  # Angle between x axis and line to our point
  theta <- asin(y / hyp)

  # Angle between 45 degree line and (x,y)
  phi <- ifelse(u, theta - pi/4, pi/4 - theta)
  phi <- ifelse(phi < 0, 0, phi)

  # Distance from 45 degree line and (x,y)
  s <- hyp * sin(phi) / sqrt(2)

  # Draw line from (x, y) to 45 degree line that is at right angles.
  # How far along 45 degree line, does that line join.
  v <- 1 - hyp * cos(phi) / sqrt(2)

  # Get hsv values.
  sapply(seq_along(x), function(i) hsv(hue[i], s[i], v[i]))

}



ggplot(data=grid.df,aes(x,y,fill=r1,fill2=r2))+
  geom_raster()+
  scale_fill_colourplane(name = "",
                         na.color = "white",
                         color_projection = col_func,
                         limits_y = c(0,1),limits=c(0,1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述