在Shiny运行时的Rmd交互式报告中,如何通过R函数设置Plotly窗口高度为100%以避免内容重叠?
I get exactly what you're dealing with—when you set a custom height for your ggplotly chart in a Shiny runtime Rmd, the Plotly container sticks to its default 400px fixed height, causing the taller chart to spill over and cover the text below. Good news is you don't need CSS hacks to fix this; there are two clean R-only approaches:
Approach 1: Match the Output Container Height to Your Chart
Use the outputArgs parameter in renderPlotly() to explicitly set the height of the Shiny output container to match the height you defined in ggplotly(). This ensures the container expands to fit your chart instead of staying stuck at 400px.
Here's your modified code with this fix:
--- runtime: shiny output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE) library(tidyverse) library(shiny) library(plotly)
fluidRow( column(3, selectInput("myselectorID", "Select:", selected = "setosa", choices = c("setosa", "versicolor", "virginica"))) ) renderPlotly({ data <- iris %>% filter(Species == input[["myselectorID"]]) ggp <- data %>% ggplot(aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() ggplotly(ggp, height = 487) }, outputArgs = list(height = "487px")) # Sync container height with chart height
START TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
END
## Approach 2: Use Plotly's `layout()` to Control Height You can also define the chart height directly via Plotly's `layout()` function, with `autosize = TRUE` to tell Plotly to adjust the container to fit the specified height. This overrides the default 400px constraint without needing to tweak Shiny's output args. Here's how to adjust your render block: ```r renderPlotly({ data <- iris %>% filter(Species == input[["myselectorID"]]) ggp <- data %>% ggplot(aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() ggplotly(ggp) %>% layout(height = 487, autosize = TRUE) # Set chart height and enable auto-sizing })
Why These Work
- Approach 1 ensures the Shiny output container doesn't cap your chart at 400px—it expands to match your chart's exact height, so no spillover.
- Approach 2 leverages Plotly's own layout system to enforce your desired height and automatically resize the container, bypassing the default fixed height entirely.
内容的提问来源于stack exchange,提问作者Patrick

