
我想使用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发布于 2020-09-10 08:55:13
似乎只使用了单元格的最后一个值。该逻辑可以在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对象的顺序。
https://stackoverflow.com/questions/63821209
复制相似问题