【问题标题】:Overlay multiple geom_raster plots with different gradients用不同的梯度覆盖多个 geom_raster 图
【发布时间】:2018-10-27 15:00:49
【问题描述】:

我想用gglotgeom_raster 绘制具有2 个不同渐变的2D 图,但我不知道是否有一个快速而优雅的解决方案,我被卡住了。

我想看到的效果本质上是多个geom_raster的叠加。另外,我需要一个可以扩展到 N 个不同梯度的解决方案;让我举一个 N=2 梯度的例子,它更容易理解。

我首先创建一个 100 x 100 的位置 X 和 Y 的网格

# the domain are 100 points on each axis
domain = seq(0, 100, 1) 

# the grid with the data
grid = expand.grid(domain, domain, stringsAsFactors = FALSE)
colnames(grid) = c('x', 'y')

然后我为每个网格点计算一个值;想象一下像这样愚蠢的事情

grid$val = apply(grid, 1, function(w) { w['x'] * w['y'] }

我知道如何用自定义的白色到红色渐变来绘制它

ggplot(grid, aes(x = x, y = y)) +
  geom_raster(aes(fill = val), interpolate = TRUE) +
  scale_fill_gradient(
      low = "white", 
      high = "red", aesthetics = 'fill')

但现在想象我每个网格点都有另一个值

grid$second_val = apply(grid, 1, function(w) { w['x'] * w['y'] + runif(1) }

现在,我如何绘制一个网格,其中每个位置“(x,y)”都用以下颜色覆盖:

  • 1“白到红”渐变,值由val 给出
  • 1 个“白到蓝”渐变,值由second_val 给出

基本上,在大多数应用程序中,valsecond_val 将是两个 2D 密度函数,我希望每个梯度都代表密度值。我需要两种不同的颜色来查看值的不同分布。

我看过这个similar question,但不知道如何在我的情况下使用这个答案。

【问题讨论】:

标签: r ggplot2 gradient geom-raster


【解决方案1】:

您链接到的@Axeman 对我的问题的回答直接适用于您的问题。

注意scales::color_ramp() 使用 0 和 1 之间的值,因此在绘图之前将 val 和 second_val 标准化为 0、1 之间

grid$val_norm <- (grid$val-min(grid$val))/diff(range(grid$val))
grid$second_val_norm <- (grid$second_val-min(grid$second_val))/diff(range(grid$second_val))

现在使用@Axeman's answer 进行绘图。您可以稍后将一个绘制为栅格,然后用注释覆盖第二个。我添加了透明度 (alpha=.5) 否则你只能看到第二层。:

ggplot(grid, aes(x = x, y = y)) +
  geom_raster(aes(fill=val)) + 
  scale_fill_gradient(low = "white", high = "red", aesthetics = 'fill') + 
  annotate(geom="raster", x=grid$x, y=grid$y, alpha=.5,
           fill = scales::colour_ramp(c("transparent","blue"))(grid$second_val_norm))

或者,您可以使用annotate() 绘制两个图层。

# plot using annotate()
ggplot(grid, aes(x = x, y = y)) +
  annotate(geom="raster", x=grid$x, y=grid$y, alpha=.5,
           fill = scales::colour_ramp(c("transparent","red"))(grid$val_norm)) +
  annotate(geom="raster", x=grid$x, y=grid$y, alpha=.5,
           fill = scales::colour_ramp(c("transparent","blue"))(grid$second_val_norm))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    相关资源
    最近更新 更多