【发布时间】:2017-08-31 17:00:00
【问题描述】:
有没有办法可以在 ggplot 中绘制光栅注释,以指定的角度旋转(不是必须是 90 度的倍数)?特别是,我需要图像的比例保持不变。
到目前为止我已经尝试过:基于问题How to rotate an image R raster 我创建了一个函数来旋转图像并将其保存为临时文件(似乎是我唯一能做的存储由@ 创建的图像987654322@),然后用ggplot2::annotation_raster 加载它。
raster_rotate <- function(img, theta, width) {
# only works with square imgs right now
theta <- theta %% 90
b <- cos(theta) + sin(theta)
x1 <- 0:ncol(img)
y1 <- 0:nrow(img)
z <- matrix(1, nrow = length(x1), ncol = length(y1))
col_mat <- t(apply(matrix(rgb(getValues(img)/255), nrow=nrow(img), byrow=TRUE), 2, rev))
tmppath = tempfile(pattern = "img", fileext = ".png", tmpdir = "tmp/imgrot")
side = round(b * width)
png(filename = tmppath, width = side, height = side)
persp(x1, y1, z, zlim = c(0, 2), theta = theta, phi = 90,
col = col_mat, scale = FALSE, border = NA, box = FALSE)
dev.off()
}
因为在相同大小的画布内旋转图像会在角度接近 45 度时缩小图像,所以我必须在旋转时将画布大小重新缩放 cos(theta) + sin(theta)。但是,当我将此缩放添加到 png 函数时,我收到一个错误:
Error in png(filename = tmppath, width = side, height = side) :
invalid 'width' or 'height'
我会接受这个错误的解决方案来帮助我修复我的混乱黑客,但如果有一种更简洁的方法可以直接在 ggplot 中执行此操作,那就更好了。
【问题讨论】:
标签: r ggplot2 raster image-rotation r-raster