【问题标题】:Creating a colour gradient around zero in filled.contour在filled.contour 中创建一个围绕零的颜色渐变
【发布时间】:2014-05-28 09:44:28
【问题描述】:

我是 R 新手,正在努力寻找我认为相对常见的问题的答案。我正在使用 fill.contour 创建一个变量的世界地图。例如:

z=matrix(rnorm(7008),nrow=96)
x=seq(-176.25,180, by=3.75)
y=seq(-90,90, by=2.5)
filled.contour(x,y,z, plot.axes={axis(1); axis(2); map(add=TRUE, interior=FALSE)} )

其中x & y 为经纬度,z 为数据矩阵。我已经花时间应用我自己的颜色和级别,但是我想要一个颜色渐变,白色分配为零。通过绿色和黄色,负数分级为深蓝色,正数分级为深红色。

我已尝试使用“plotrix”包中的 color.scale 函数

cellcol=matrix(rep("#000000",7008),nrow=96) # replicating the size of my matrix z
cellcol[z>0]=color.scale(z[z>0], c(0,1,1),c(1,1,0),0) # values above zero grading to red 
cellcol[z<0]=color.scale(z[z<0], 0, 0,c(0,1)) # values below zero grading to blue

但是现在我被卡住了。这是最好的方法吗?如果是这样,我如何将其输入到上面的filled.contour 代码中?我敢肯定它很简单,但不能让它工作。

提前感谢您的帮助。

【问题讨论】:

  • 你确定color.scale 不在plotrix 包中吗?
  • 道歉我已经编辑并试图使我的问题更可重复
  • 如果您的数据是,例如在您的示例中以零为中心,您可以使用filled.contour(x,y,z, plot.axes={axis(1); axis(2)}, color.palette=colorRampPalette(c("red","white","blue"))),但我想它们不是。
  • 不,恐怕不会。感谢以下建议,我已经在 ggplot2 中完成了,但假设必须有一种方法来填充。轮廓
  • 我设法用 fill.contour 做到了。

标签: r colors contour


【解决方案1】:

我只是使用ggplot2 实现了你想要的。

您可以尝试以下方法(我以淹没火山数据为例):

library(ggplot2)
library(reshape2)

## Just an example, I subtract the mean to have positive and negative values for z 
dd <- volcano-mean(volcano)

## Creates a data.frame with columns x, y, z
dd <- melt(dd)
names(dd) <- c('x','y','z')

## Does the contour plot
d <- ggplot(dd, aes(x,y,z=z))
d + geom_tile(aes(fill=z))  + scale_fill_gradient2(low="blue", high="red")


我写了一个小函数来做你想要实现的:

myFilled.contour <- function(x = seq(0, 1, length.out = nrow(z)),
                             y = seq(0, 1, length.out = ncol(z)),
                             z, nlevels=30, ...) {
  ma <- max(abs(z))
  lvls <- seq(-ma, ma, length.out = nlevels)
  cols <- colorRampPalette(c("blue","white","red")) (nlevels - 1)
  filled.contour(x, y, z, plot.axes={axis(1); axis(2)},
                 col=cols, levels=lvls, ...)
}

使用filled.contour 并再次使用水下火山dd

myFilled.contour(z=d)

使用您的数据:

myFilled.contour(x,y,z)

警告:图例包括等高线图中未使用的级别。

希望对你有帮助,

亚历克斯

【讨论】:

  • 嗨,Alex,非常感谢您为此付出的帮助和时间。最后我想我可能会回到 ggplot2,因为它显然更通用,但看起来不太好!
  • 作为一个快速的问题来节省我一些时间,你知道我如何像使用 map(add=TRUE) 那样为填充的轮廓添加世界地图吗?
  • 检查 ggmap 包,我认为它可以满足您的需求。
猜你喜欢
  • 1970-01-01
  • 2014-05-16
  • 2022-01-15
  • 2019-05-14
  • 2014-10-29
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多