R:geom_image 被 coord_fixed 变形

R: geom_image gets deformed by coord_fixed

我正在尝试将图像放置到需要具有固定坐标的绘图中(x、y 值是 GPS 坐标,我希望地图能够正确缩放)。如果 x 和 y 的范围不匹配,则图像会变平。

我不知道这是错误还是期望的行为。有没有办法制作具有原始纵横比的图像?我唯一想到的就是把不可见的点放在角落里,让情节再次变成正方形。

简单示例如下:

require(tidyverse)
require(ggimage)

plot_image <- function(x_size, y_size) {

  dta_points <- crossing(x = c(-x_size, x_size), y = c(-y_size, y_size))
  dta_img <- data_frame(x = 0, y = 0, image = 'https://www.r-project.org/logo/Rlogo.png')

  ggplot(NULL, aes(x, y)) + 
    geom_point(data = dta_points) +
    geom_image(data = dta_img, aes(image = image), size = 1) +
    ggtitle(paste0('x_size: ', x_size, ', y_size: ', y_size)) +
    coord_fixed()
}

plot_image(x_size = 1, y_size = 1)
plot_image(x_size = 0.1, y_size = 1)
plot_image(x_size = 1, y_size = 0.1)

您可以调整 annotation_custom 内的 xmin/xmax/ymin/ymax 参数,以在确定其宽高比时将图像放置在任何位置:

library(ggplot2)
library(png)
library(grid)

download.file("https://www.r-project.org/logo/Rlogo.png", 'Rlogo.png', mode = 'wb')
image <- readPNG("Rlogo.png")
logo <- rasterGrob(image, interpolate = TRUE)

ggplot() + 
  annotation_custom(logo, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) 

示例:

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + 
  annotation_custom(logo, xmin = 7, xmax = 8, ymin = 2, ymax = 4) +
  geom_point()

跟进您的评论:

您只需指定 xy 美学以保留原始纵横比,size 将在需要时帮助缩放:

library(ggimage)

dta_img <- data.frame(x = 6, y = 3, image = 'https://www.r-project.org/logo/Rlogo.png')

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + 
  geom_image(data = dta_img, aes(x, y, image = image), size = 0.1) +
  geom_point()

另请查看 leaflet,它具有创建类似于您链接的精美地图的内置功能:Leaflet for R

尝试geom_custom,

library(ggplot2)
library(png)
library(grid)
library(egg)

i <- readPNG(system.file("img", "Rlogo.png", package="png"))
img <- data.frame(x = 6, y = 3)
img$g <-  list(rasterGrob(i, width=unit(24,"pt")))

ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + 
  geom_point() +
  geom_custom(data=img, aes(x,y,data=g), grob_fun=identity) +
  coord_fixed()