首页 > 解决方案 > geom_raster 如何处理重复填充?

问题描述

在此处输入图像描述

我想使用包将一些联合事件的概率呈现为栅格,并想知道在多个像元值的情况下ggplot2如何决定提升哪个值。geom_raster我有一些案例,由于某些原因,这些事件可能具有多个概率。在下面的代码和上面的图片中,我在坐标 (10, 10) 处说明了我的问题点。是否geom_raster考虑最后一个值?有样品吗?

library(ggplot2)

# Normal raster
r <- data.frame(x = 1:10, y = rep(10, 10), value = 1:10)

p1 <- ggplot(r, aes(x, y, fill=value))+
  geom_raster()+
  coord_equal()+
  theme(legend.position = 'bottom')+
  labs(title = 'Normal raster: every cell has one value')

p1

# Assuming that coordinate (10, 10) have values 10 and 0
r <- rbind(r, c(10, 10, 0))

p2 <- ggplot(r, aes(x, y, fill=value))+
  geom_raster()+
  coord_equal()+
  theme(legend.position = 'bottom')+
  labs(title = 'Raster having 2 different values (10 then 0) at coordinates (10, 10)')

p2

标签: rggplot2rastergeom-raster

解决方案


似乎只使用了单元格的最后一个值。逻辑可以在 GeomRaster 的draw_panel 函数的源代码中找到。我们看到这段代码

  x_pos <- as.integer((data$x - min(data$x))/resolution(data$x, 
    FALSE))
  y_pos <- as.integer((data$y - min(data$y))/resolution(data$y, 
    FALSE))
  nrow <- max(y_pos) + 1
  ncol <- max(x_pos) + 1

  raster <- matrix(NA_character_, nrow = nrow, ncol = ncol)
  raster[cbind(nrow - y_pos, x_pos + 1)] <- alpha(data$fill, 
    data$alpha)

所以它所做的是为所有值创建一个包含行和列的矩阵,然后使用矩阵索引进行分配。当您执行此操作时,只有最后一个分配仍然存在。例如

(m <- matrix(1:9, nrow=3))
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
(rowcols <- cbind(c(2,3,2), c(3,1,3)))
#      [,1] [,2]
# [1,]    2    3
# [2,]    3    1
# [3,]    2    3
m[rowcols] <- 10:12
m
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5   12
# [3,]   11    6    9

我们正在做的是创建一个矩阵,然后再次更改单元格 (2,3)、(3,1) 和 (2,3) 的值。仅保留对 (2,3) 的最后一个赋值(10 值被覆盖)。因此,保留的值取决于您的数据传递给 ggplot 对象的顺序。


推荐阅读