【问题标题】:Rotate raster annotation ggplot2旋转栅格注释ggplot2
【发布时间】: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


    【解决方案1】:

    这是我旋转地图的方法,也许稍微调整一下就可以解决您的问题?

    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")
    

    【讨论】:

    • 恐怕不行。该地图旋转有效,因为您将地图对象绘制为多边形,因此您可以将旋转应用为点的变换。但是光栅图像的绘制方式完全不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多