geom_raster 如何处理重复填充?

How does geom_raster handle duplicated fill?

我想使用 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

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

  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 对象的顺序。