flexdashboard故事板布局下Tabset Panel中Plotly图表自适应异常问题
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 thetabsetPanelso we can detect when the user switches tabs. - 100% Height for Plot Outputs: Setting
height = "100%"onplotlyOutputensures charts have space to expand into the tab container. - Plotly Proxy Relayout: When a tab is activated,
plotlyProxytells the chart to recalculate its size based on the now-visible container. The smallSys.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

