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

flexdashboard故事板布局下Tabset Panel中Plotly图表自适应异常问题

Fix for Plotly Charts Not Resizing in Tabs with Flexdashboard Storyboard Layout

Hey there, I’ve dealt with this exact problem before when working with flexdashboard’s storyboard layout and tabbed Plotly widgets! The core issue is that hidden tabs don’t provide Plotly with accurate container dimensions during initialization, which breaks adaptive resizing. Here’s a complete solution:

Step 1: Full Working Code (Fixed MRE)

---
title: "MRE"
output: 
  flexdashboard::flex_dashboard:
    storyboard: true
---

```{r setup, include=FALSE}
library(flexdashboard)
library(plotly)
library(shiny)

Test

# Create your Plotly charts
plot1 <- plot_ly(x = 1:5, y = 6:10, type = "scatter")
plot2 <- plot_ly(x = 1:5, y = 1:5, type = "scatter")

# Add an ID to the tabsetPanel to track tab switches
tabsetPanel(
  id = "tab_container",
  tabPanel("Plot 1", plotlyOutput("plot1", height = "100%")),
  tabPanel("Plot 2", plotlyOutput("plot2", height = "100%"))
)

# Render the charts
output$plot1 <- renderPlotly(plot1)
output$plot2 <- renderPlotly(plot2)

# Trigger relayout when tabs are switched
observeEvent(input$tab_container, {
  # Small delay to ensure the tab container has fully rendered
  Sys.sleep(0.1)
  
  # Get the active tab and target its Plotly chart
  active_tab <- input$tab_container
  plotlyProxy(active_tab, session = getDefaultReactiveDomain()) %>%
    plotlyProxyInvoke("relayout", list(width = "100%", height = "100%"))
})

Key Fixes Explained

  • Tabset ID: We added id = "tab_container" to the tabsetPanel so we can detect when the user switches tabs.
  • 100% Height for Plot Outputs: Setting height = "100%" on plotlyOutput ensures charts have space to expand into the tab container.
  • Plotly Proxy Relayout: When a tab is activated, plotlyProxy tells the chart to recalculate its size based on the now-visible container. The small Sys.sleep(0.1) gives the browser time to update the container dimensions before triggering the resize.

Why This Happens

In flexdashboard’s storyboard layout, only the first tab is visible when the page loads. Hidden tabs have their display set to none initially, so Plotly can’t read the actual width/height of their containers during initialization. This causes the charts to use a fixed default size instead of adapting to the container. By triggering a relayout when the tab becomes visible, we force Plotly to recheck the container dimensions and adjust accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:21:39