Plotly不遵循RMarkdown的out.height参数,求可行解决方案
I’ve run into this exact issue with Slidy and Plotly before— the root problem is that Slidy hides all slides except the active one by default (using display: none). When Plotly initializes, it can’t calculate the height of a hidden container, so it falls back to the default 450px height. Resizing the window works for the current slide because that slide is visible, so Plotly can finally read the container’s dimensions.
Here’s a seamless, no-manual-interaction solution using custom JavaScript to trigger Plotly’s resize logic whenever a slide becomes active, plus an initial load trigger for the first slide:
--- title: "Plotly in Slidy Auto-Height Fix" output: slidy_presentation --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE) suppressMessages(library(plotly)) suppressMessages(library(htmltools))
Slide with Plotly Chart
# Create the plotly object p <- plot_ly(x=~iris[,1], y=~iris[,2], type="scatter", mode="markers") %>% layout(autosize = TRUE) # Wrap the plot and add custom JS to handle auto-resizing tagList( div(p), tags$script(HTML(" // Trigger resize when Slidy switches slides document.addEventListener('slidy:slidechanged', function(event) { const activeSlide = event.detail.currentSlide; const plotDivs = activeSlide.querySelectorAll('.plotly'); plotDivs.forEach(div => { // Force Plotly to recalculate dimensions based on visible container Plotly.relayout(div, {autosize: true}); }); }); // Fix the first slide's chart on initial page load window.addEventListener('load', function() { const firstSlide = document.querySelector('.slide.active'); const plotDivs = firstSlide.querySelectorAll('.plotly'); plotDivs.forEach(div => { Plotly.relayout(div, {autosize: true}); }); }); ")) )
### How This Works: - **Slidy Event Listener**: Slidy emits a `slidy:slidechanged` event every time you switch slides. We listen for this, grab the active slide, and target all Plotly charts inside it. - **Force Relayout**: Calling `Plotly.relayout(div, {autosize: true})` tells Plotly to recalculate the chart dimensions using the now-visible container’s height (which respects your `out.height="95%"` setting). - **Initial Load Fix**: The `load` event listener ensures the first slide’s chart renders correctly immediately, no slide-switching required. If you need more control, you can replace the `autosize: true` line with an explicit height set to the container’s offset height: ```javascript Plotly.relayout(div, {height: div.parentElement.offsetHeight});
This solution preserves full Plotly interactivity and requires zero manual adjustments from users.
内容的提问来源于stack exchange,提问作者user3554004

