0

我正在尝试将图像放置到需要具有固定坐标的图上(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)

在此处输入图像描述

4

2 回答 2

1

试试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()
于 2018-08-06T09:10:26.603 回答
1

您可以调整xmin/xmax/ymin/ymax内部参数annotation_custom以将图像放置在任何位置,同时决定其纵横比:

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

跟进您的评论:

您只需要指定x&y美学以保留原始纵横比,并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

于 2018-08-05T21:34:05.297 回答