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

如何让Plotly图表随浏览器窗口大小自动调整尺寸?(Flask+Python实现)

让Flask中的Plotly图表实现响应式(窗口大小自适应)

要让你的Plotly图表在浏览器窗口改变时自动调整尺寸,你可以通过配置Plotly的响应式参数和设置容器元素的样式这两种方式来实现,下面是针对你现有代码的具体修改方案:

方法1:启用Plotly的响应式配置

你只需要在调用Plotly.plot()时,传入包含responsive: true的配置对象(第四个参数),同时确保图表容器的宽度设置为100%。修改你的HTML/JavaScript代码如下:

<!doctype html>
<html>
<body>
    <h1>Plotly chart</h1>
    <!-- 给容器添加宽度100%的样式,确保容器随窗口宽度变化 -->
    <div id='chart' class='chart' style="width:100%;"></div>
</body>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
    var graphs = {{graphJSON | safe}};
    // 第四个参数是Plotly的配置对象,启用responsive属性
    Plotly.plot('chart', graphs, {}, {responsive: true});
</script>
</html>

说明:

  • responsive: true会让Plotly自动监听容器的尺寸变化,实时调整图表大小
  • 给div设置width:100%确保容器能随父元素(浏览器窗口)的宽度变化而自适应

方法2:结合容器样式与自动尺寸

如果你想更灵活控制图表的高度,也可以给容器设置百分比高度(比如基于视口高度),同时在Plotly布局中显式开启autosize: true(默认已开启,但显式设置更稳妥):

<!doctype html>
<html>
<!-- 先设置html和body的基础样式,避免高度塌陷 -->
<style>
    html, body {
        margin: 0;
        padding: 0;
        height: 100%;
    }
    .chart {
        width: 100%;
        height: 80vh; /* 占视口高度的80%,可根据需求调整数值 */
    }
</style>
<body>
    <h1>Plotly chart</h1>
    <div id='chart' class='chart'></div>
</body>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
    var graphs = {{graphJSON | safe}};
    // 显式设置布局的autosize属性,同时启用响应式配置
    var layout = {autosize: true};
    Plotly.plot('chart', graphs, layout, {responsive: true});
</script>
</html>

说明:

  • 设置html, body的高度为100%是为了让vh(视口高度)单位能正常生效
  • height:80vh让图表高度始终是浏览器窗口高度的80%,窗口缩放时会同步调整

这两种方法都能实现你想要的类似{responsive: true}或style="width:100%"的效果,选择哪种取决于你对图表尺寸的具体需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:42:34