2017-08-31 108 views
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那會更好。

回答

0

下面是我如何旋轉地圖,也許調整它有點會解決您的問題?

library(tidyverse) 
rotate.axis <- function(xy,theta){ 
     pimult <- (theta * 2 * pi)/360 
     newx <- c(cos(pimult), sin(pimult)) 
     newy <- c(-sin(pimult), cos(pimult)) 
     XY <- as.matrix(xy) %*% cbind(newx, newy) 
     as.data.frame(XY) 
} 

ak <- map_data('world','USA:Alaska') 

newd <- data.frame(longitude=ak$long, latitude=ak$lat) 
rotate <- rotate.axis(newd,30) 
newak <- bind_cols(ak,rotate) 

對象

newak %>% 
    filter(long<0) %>% 
    ggplot() + geom_polygon(aes(long,lat,group=group),fill=8,color="black") 

旋轉對象

newak %>% 
    filter(long<0) %>% 
    ggplot() + geom_polygon(aes(newx,newy,group=group),fill=8,color="black") 
+0

恐怕不是沒有旋轉。因爲您將地圖對象繪製爲多邊形,所以地圖旋轉可以工作,因此您可以將旋轉應用爲點的轉換。但是柵格圖像完全不同。 – Empiromancer