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

如何在Plotly中合并两张地图并通过下拉菜单切换(Quarto环境)

在Quarto中实现Plotly Choroplethmapbox的下拉菜单切换

核心实现思路

借助Plotly的updatemenus配置下拉菜单,通过切换z字段(健康指数/财富指数)及对应颜色轴设置,实现两张地图的无缝切换,无需重新渲染整个图表。

完整代码示例

假设你的数据框df包含地理编码、健康指数、财富指数及坐标字段,替换为你的真实数据即可:

library(plotly)
library(dplyr)

# 示例数据(替换为你的真实数据)
df <- tibble(
  location = c("US", "CA", "GB", "FR", "DE"),
  healthy_index = runif(5, 0, 100),
  wealthy_index = runif(5, 0, 100),
  lat = c(37.0902, 56.1304, 55.3781, 46.2276, 51.1657),
  lon = c(-95.7129, -106.3468, -3.4360, 2.2137, 10.4515)
)

# 构建带下拉菜单的交互式地图
interactive_map <- plot_ly(df) %>%
  add_trace(
    type = "choroplethmapbox",
    locations = ~location,
    z = ~healthy_index, # 默认显示健康指数
    colorscale = "Viridis",
    colorbar = list(title = "健康指数")
  ) %>%
  layout(
    mapbox = list(style = "carto-positron", zoom = 1),
    updatemenus = list(
      list(
        type = "dropdown",
        active = 0, # 默认选中第一个选项
        buttons = list(
          list(
            label = "健康指数",
            method = "restyle",
            args = list(
              list(z = list(df$healthy_index)),
              list(colorbar = list(title = "健康指数"))
            )
          ),
          list(
            label = "财富指数",
            method = "restyle",
            args = list(
              list(z = list(df$wealthy_index)),
              list(colorbar = list(title = "财富指数"))
            )
          )
        )
      )
    )
  )

interactive_map

关键细节说明

  • restyle方法:仅更新图表的属性(如数值字段、颜色栏标题),比重新渲染整个地图更高效流畅。
  • 数据格式要求:args中的z值需用list()包裹数据列,确保Plotly能正确识别更新的数值数组。
  • 自定义地理边界:如果需要使用自定义GeoJSON边界,只需将geojson参数替换为你的GeoJSON对象,并调整locations字段匹配GeoJSON的ID标识。
  • Quarto适配:直接将代码放入Quarto的R代码块中,渲染后即可得到带下拉菜单的交互式地图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:43:14