1
有沒有一種方法可以繪製ggplot中的光柵註釋,以指定的角度旋轉(這是而不是必然是90度的倍數)?特別是,我需要圖像的比例不變。旋轉柵格註釋ggplot2
我到目前爲止的嘗試:基於問題How to rotate an image R raster我創建了一個函數來旋轉圖像並將其保存爲臨時文件(似乎是我可以做的唯一的事情來存儲由persp
創建的圖像) ,然後將其加載到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那會更好。
恐怕不是沒有旋轉。因爲您將地圖對象繪製爲多邊形,所以地圖旋轉可以工作,因此您可以將旋轉應用爲點的轉換。但是柵格圖像完全不同。 – Empiromancer