r - 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
解决方案
似乎只使用了单元格的最后一个值。逻辑可以在 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 对象的顺序。
推荐阅读
- c# - C# JSON.net 在反序列化时没有正确地将对象创建为字典中的值
- java - 如何查询 CursorLoader?
- r - 使用大于第 9 行的两个变量从 data.frame 中查找第 N 行
- uiview - 反复隐藏和显示另一个 UIViewController 的视图
- python - 从多个不同长度的二维数组中查找平均数组
- matplotlib - subplots_adjust 不可预测地移动轴?
- r - 在相关矩阵中过滤数据
- regex - 如何将正则表达式转换为 grep 格式
- ruby-on-rails - 为什么我无法在 ruby rails 的视图中访问模型的属性?
- javascript - 父页面上的 javascript 可以在 iframe 内记录击键吗?