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

如何使Shiny中plotly的plot_geo完全适配卡片容器?

Shiny中Plotly地图无法适配Card容器的解决办法

问题描述

在Shiny中使用Plotly创建地图时,地图无法完全适配Card的高度与宽度。以下是最小可复现代码:

library(shiny)
library(plotly)
library(bslib)

ui <- fluidPage(
  card(plotlyOutput("plot", width = "100%", height = "100%"))
)

server <- function(input, output, session) {
  output$plot <- renderPlotly({
      plot_geo(type = 'scattermapbox') %>% 
      layout(
        showlegend = FALSE,
        paper_bgcolor="#F0F9FE",
        geo = list(scope = 'world'))
})
}
shinyApp(ui, server)

期望实现的效果:
期望效果截图

解决办法

问题核心在于默认Card无明确尺寸约束,且Plotly图表自带内边距,导致无法完全填充容器。可通过以下两种方案修改:

方案1:让地图占满整个页面视口

使用fillPage替代fluidPage,给Card添加full_screen参数,同时移除Plotly的内边距:

library(shiny)
library(plotly)
library(bslib)

ui <- fillPage(
  card(
    full_screen = TRUE,
    plotlyOutput("plot", width = "100%", height = "100%")
  )
)

server <- function(input, output, session) {
  output$plot <- renderPlotly({
    plot_geo(type = 'scattermapbox') %>% 
      layout(
        showlegend = FALSE,
        paper_bgcolor="#F0F9FE",
        geo = list(
          scope = 'world',
          fitbounds = "locations",
          projection = list(type = "mercator")
        ),
        margin = list(l = 0, r = 0, t = 0, b = 0) # 移除图表内边距
      )
  })
}
shinyApp(ui, server)

方案2:给Card设置固定尺寸

如果不需要占满整个视口,直接给Card设置明确的高度和宽度,让内部Plotly输出有尺寸参照:

library(shiny)
library(plotly)
library(bslib)

ui <- fluidPage(
  card(
    height = "600px",
    width = "100%",
    plotlyOutput("plot", width = "100%", height = "100%")
  )
)

server <- function(input, output, session) {
  output$plot <- renderPlotly({
    plot_geo(type = 'scattermapbox') %>% 
      layout(
        showlegend = FALSE,
        paper_bgcolor="#F0F9FE",
        geo = list(scope = 'world'),
        margin = list(l = 0, r = 0, t = 0, b = 0)
      )
  })
}
shinyApp(ui, server)

关键修改点说明

  • 给Card设置明确尺寸约束:要么通过full_screen占满父容器,要么设置固定height,让内部plotlyOutput的百分比尺寸有参照
  • 移除Plotly图表默认内边距,避免地图与Card边框间出现空隙
  • 配置geo的fitbounds = "locations",让地图自动适配容器边界(有数据点时效果更明显)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:52:34