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

如何制作含AK、HI嵌入式的移动端友好R交互Choropleth地图?

用ggiraph实现符合需求的美国交互Choropleth地图

是的,ggiraph完全可以实现你需要的所有功能:移动端Pinch-Zoom触摸缩放、点击/触摸触发弹窗,同时保留阿拉斯加(AK)和夏威夷(HI)的嵌入式布局。核心思路是结合usmap的地图布局能力(它已经帮你处理好了AK/HI的嵌入式放置)和ggiraph的交互式SVG渲染能力(原生支持移动端触摸交互)。

实现步骤与代码示例

以下是适配你现有数据结构的完整实现代码:

1. 依赖包加载

首先确保安装并加载所需包:

install.packages(c("usmap", "ggiraph", "dplyr", "ggplot2"))
library(usmap)
library(ggiraph)
library(dplyr)
library(ggplot2)

2. 地图数据处理(复用你的现有逻辑)

# 获取US地图数据(已包含AK/HI嵌入式布局)
tf_usa_map <- us_map(regions = "states")

# 合并你的数据(保持你的原有逻辑)
tf_current_map <- left_join(tf_usa_map, tf_airtable_state_by_year, by=c("abbr" = "state_abb")) %>%
  filter(abbr != "DC") # 移除DC

# 计算2024年总法案数
updated_total_bills <- sum(tf_current_map$`2024`, na.rm = TRUE)

3. 构建交互式地图

# 自定义颜色与断点(复用你的配置)
custom_colors <- c("white", "#ed7fa1", "#DB0044", "#740024", "#410014")
custom_breaks <- c(0, 5, 20, 30, 60)
custom_scale <- scale_fill_gradientn(
  colors = custom_colors,
  breaks = custom_breaks,
  limits = c(min(custom_breaks), max(custom_breaks)),
  name = "Bills"
)

# 构建交互式ggplot对象
p <- ggplot() +
  # 交互式多边形图层:支持点击/触摸事件
  geom_polygon_interactive(
    data = tf_current_map,
    aes(
      x = x, y = y, group = group,
      fill = `2024`,
      # 点击/触摸触发的弹窗内容(支持HTML格式)
      tooltip = paste0(
        State, "<br>",
        "2024年反跨性别法案数: ", `2024`, "<br>",
        "全国总计法案数: ", updated_total_bills
      ),
      # 点击事件(可自定义JS逻辑,比如弹出详情弹窗)
      onclick = paste0("alert('", State, ": ", `2024`, " bills introduced')")
    ),
    color = "#2d0016", # 州界颜色
    size = 0.5 # 州界宽度
  ) +
  # 应用自定义颜色刻度
  custom_scale +
  # 使用usmap的坐标系统,确保AK/HI布局正确
  coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
  # 精简主题,移除冗余元素
  theme_void() +
  theme(
    plot.title = element_text(size = 20, hjust = 0.5),
    plot.margin = margin(10, 10, 30, 10),
    legend.position = "bottom"
  ) +
  labs(
    title = paste0(updated_total_bills, " Anti-Trans Bills Have Been\nIntroduced in 2024"),
    caption = "Data From: Trans Formations Project, LegiScan"
  )

# 渲染为交互式SVG:支持移动端Pinch-Zoom
ggiraph(
  code = print(p),
  # 配置缩放参数:允许最大5倍缩放,原生支持触摸缩放
  opts = list(
    zoom_max = 5,
    zoom_min = 1,
    hover_css = "cursor: pointer;",
    # 优化移动端显示尺寸
    width_svg = 8,
    height_svg = 6
  )
)

关键功能说明

  1. AK/HI嵌入式布局:完全依赖usmap的地图数据,它已经将AK和HI缩放在美国本土地图下方,无需手动调整坐标。
  2. 移动端Pinch-Zoom:ggiraph输出的是原生SVG,移动端浏览器默认支持触摸缩放,配合zoom_max参数可限制最大缩放比例,确保交互流畅。
  3. 点击/触摸弹窗:
    • tooltip参数支持HTML格式文本,鼠标悬停或触摸时会显示自定义信息;
    • onclick参数可绑定JavaScript代码,实现点击触发弹窗、跳转等自定义交互。

对比你之前的方案优势

  • 相比Plotly:无需依赖工具栏的缩放按钮,原生支持移动端触摸缩放;
  • 相比Leaflet:直接复用usmap的成熟AK/HI布局,无需手动调整坐标或添加子地图;
  • 相比DataMaps:基于活跃维护的R包(ggiraph和usmap均持续更新),兼容最新R版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:53:17