You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言地图右上角插入图片?附尝试代码与示例

在R语言地图右上角插入图片的解决方法

需求说明

想在R语言用ggplot2绘制的地图右上角插入图片,尝试了annotation_custom但未成功,希望得到可行的实现方案,示例无需使用提供的Shapefile数据。

你的尝试代码

library(tidyverse)
library(rgdal)
library(sf)
library(ggsn)
library(jpeg)
library(grid)
library(cowplot)
library(magick)
library(png)
library(ggplot2)

shp = st_read("USA_Detailed_Water_Bodies.shp")
shp

# 处理数据
shp$OBJECTID <- as.factor(shp$OBJECTID)
shp_subset <- filter(shp, OBJECTID %in% c('245511'))

# 绘制地图
Plot <- ggplot(data = shp_subset) + 
  geom_sf()+ 
  coord_sf()+
  theme_bw() + 
  ggsn::scalebar(data=shp_subset, dist=5, dist_unit="km", height=0.01, 
                 transform=TRUE, model="WGS84",location="bottomleft", 
                 anchor=c(x=-94.7, y=47.50), st.bottom=FALSE, 
                 st.size=2.5, st.dist=0.015)

# 读取图片
img <- readJPEG("Rplot01.jpg", native = TRUE)

# 尝试插入图片(未成功)
Plot + annotation_custom(rasterGrob(img), xmin = 94.3, xmax = 94.2, ymin = 47.4, ymax = 47.5)

当前效果与期望效果

当前地图效果
期望地图效果

问题分析与解决方案

问题原因

  1. 坐标错误:你使用的xmin=94.3和xmax=94.2顺序颠倒(xmin必须小于xmax),且地图的经度是西经,应为负数(比如xmin=-94.3,xmax=-94.2)。
  2. coord_sf下的坐标适配问题:annotation_custom依赖绝对地理坐标,在带投影的地图中容易出现位置偏移,不如相对位置的方法可靠。

推荐方案:使用cowplot的draw_image

cowplot的draw_image支持用相对画布位置添加图片,无需关心地理坐标,操作更简单。

完整示例代码

library(ggplot2)
library(sf)
library(cowplot)
library(magick)

# 1. 创建示例地图(用内置的北卡罗来纳州数据,可替换为你的地图)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"))
map_plot <- ggplot(nc) + 
  geom_sf(fill = "#87CEEB") + 
  theme_bw()

# 2. 读取图片(替换为你的图片路径)
# 本地图片:
img <- image_read("Rplot01.jpg")
# 若需测试,可使用在线图片:
# img <- image_read("https://picsum.photos/200/200")

# 3. 在地图右上角插入图片
final_plot <- ggdraw(map_plot) +
  draw_image(
    img,
    x = 0.95,        # 相对画布的x位置(0=最左,1=最右)
    y = 0.95,        # 相对画布的y位置(0=最下,1=最上)
    hjust = 1,       # 水平对齐方式(1=右对齐)
    vjust = 1,       # 垂直对齐方式(1=上对齐)
    width = 0.15     # 图片相对画布宽度的占比(可根据需要调整)
  )

# 查看结果
print(final_plot)

关键参数说明

  • x/y:控制图片在画布上的相对位置,0.95表示距离右侧/顶部5%的位置。
  • hjust=1/vjust=1:确保图片的右上角对齐到设置的x/y位置。
  • width:调整图片大小,取值范围0-1,代表相对画布宽度的比例。

若坚持使用annotation_custom的修正方法

如果一定要用annotation_custom,需修正坐标并确保和地图范围匹配:

# 获取地图的坐标范围
bbox <- st_bbox(shp_subset)

# 计算右上角的坐标范围(比如取右上角10%的区域)
x_range <- bbox$xmax - bbox$xmin
y_range <- bbox$ymax - bbox$ymin

img_grob <- rasterGrob(img)

Plot + annotation_custom(
  img_grob,
  xmin = bbox$xmax - 0.1*x_range,  # 右侧10%区域的左边界
  xmax = bbox$xmax,                # 右边界
  ymin = bbox$ymax - 0.1*y_range,  # 顶部10%区域的下边界
  ymax = bbox$ymax                 # 上边界
)

内容的提问来源于stack exchange,提问作者confusedindividual

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:01:01