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

ggplotly绘制美国交互式地图时纵横比异常问题求助

解决Plotly美国地图纵横比失调的问题

方法1:手动设置Plotly布局的宽高比

在ggplotly()之后,通过layout()指定固定宽高比,强制地图保持正确形态:

plotly_plot <- ggplotly(test_plot, tooltip = 'text') %>%
  layout(
    aspectmode = "manual",
    aspectratio = list(x = 1.8, y = 1)  # 可根据地图范围微调比例
  )

plotly_plot

如果包含阿拉斯加、夏威夷等偏远领地,可适当调大x轴比例值。

方法2:使用Plotly原生地理绘图(推荐)

放弃ggplot转Plotly的方式,直接用Plotly原生地理函数,它会自动处理投影与纵横比,交互体验更流畅:

library(urbnmapr)
library(plotly)

# 获取sf格式的领地和州地图数据
states_territory_sf <- get_urbn_map(map = "territories_states", sf = TRUE)

# 用plotly原生函数绘制交互式地图
plot_geo(states_territory_sf) %>%
  add_sf(
    text = ~state_name,
    hoverinfo = "text",
    line = list(color = "#ffffff", width = 0.25)
  ) %>%
  layout(
    geo = list(
      projection = list(type = "albers usa"),  # 美国专属Albers投影
      showland = TRUE,
      landcolor = "lightgray"
    )
  )

这种方式嵌入Shiny时,缩放和响应表现更自然,无需手动调整比例。

方法3:结合ggplot主题参数调整

如果要保留ggplot绘图逻辑,可先在ggplot中设置固定宽高比,再转成Plotly:

states_territory %>%
  ggplot(aes_string(x = 'long', 
             y = 'lat', 
             group = 'group', 
             text = 'state_name')) +
    geom_polygon(color = "#ffffff", size = 0.25) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
    theme(aspect.ratio = 1/1.8)  # 与后续Plotly的比例对应
  -> test_plot

plotly_plot <- ggplotly(test_plot, tooltip = 'text') %>%
  layout(aspectmode = "manual", aspectratio = list(x = 1.8, y = 1))

plotly_plot

另外,关于你提到的ggiraph在Shiny中无法自动缩放的问题,可通过将ggiraph的width/height参数设为"100%",或配合Shiny的outputOptions()调整,但Plotly原生地理图的适配性整体更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:45:34