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

R语言plotly绘制欧洲Choropleth地图显示为正方形的解决方法

解决plotly绘制欧洲地图时图表为正方形无法完整显示的问题

问题描述

使用R语言plotly包(版本plotly_4.10.0)绘制欧洲Choropleth地图,输出图表始终为正方形,无法完整显示欧洲区域。尝试过plot_ly(width = 800)和plot_ly(sizes = c(1, 600))均无效果。

解决方案

问题核心是未给图表设置适配欧洲形状的宽高比及尺寸,需通过layout参数调整:

  • 在layout中直接指定图表的width和height,强制改变整体尺寸
  • 调整geo组件的aspectratio参数,适配欧洲的横向延伸形状

修改后的代码

library(plotly)
trace1 <- list(
  geo = "geo", 
  type = "choropleth", 
  z = c("6", "4", "5"), 
  showscale = TRUE, 
  locationmode = "country names", 
  locations = c("Germany", "France", "Italy"), 
  autocolorscale = TRUE
)
layout <- list(
  width = 1200,  # 设置图表整体宽度
  height = 700,  # 设置图表整体高度
  geo = list(
    scope = "europe", 
    domain = list(
      x = c(0, 1), 
      y = c(0, 1)
    ), 
    lataxis = list(range = c(35.0, 70.0)), 
    lonaxis = list(range = c(-9.0, 38.0)), 
    showland = TRUE, 
    landcolor = "rgb(229, 229, 229)", 
    showframe = TRUE, 
    projection = list(type = "Mercator"), 
    resolution = 50, 
    countrycolor = "rgb(255, 0, 255)", 
    coastlinecolor = "rgb(0, 255, 255)", 
    showcoastlines = TRUE,
    aspectratio = list(x = 1.6)  # 调整地图区域宽高比,适配欧洲横向形状
  ), 
  title = "map of Europe", 
  legend = list(traceorder = "reversed")
)
p <- plot_ly()
p <- add_trace(p, geo=trace1$geo, type=trace1$type, z=trace1$z, showscale=trace1$showscale, locationmode=trace1$locationmode, locations=trace1$locations, autocolorscale=trace1$autocolorscale)
p <- layout(p, geo=layout$geo, title=layout$title, legend=layout$legend, width=layout$width, height=layout$height)

说明

  1. layout中的width和height参数会强制图表整体尺寸,覆盖plot_ly()中的设置,这是之前尝试无效的原因
  2. geo组件的aspectratio参数可以单独调整地图区域的宽高比例,让欧洲的横向范围完整展示,无需缩小视图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:25:23