【问题标题】:remove the weird whitespace around the plotly chart (Javascript)删除 plotly 图表周围的奇怪空白(Javascript)
【发布时间】:2021-09-03 17:37:34
【问题描述】:

我正在使用 plotly 库 (Javascript) 来绘制饼图,我正在使用 flexbox 进行布局。图表右侧有一个巨大的空白,如下图所示:

在上图中,您可以在饼图右侧看到空白。我使用了 flexbox 属性 : flex-grow 来利用所有可用空间。为什么 flex-grow 在这里不起作用?

Codepen

index.html

<!DOCTYPE html>
<html lang="en">
<head>
        <title>plotly test</title>
        <link rel="stylesheet" href="style.css">
</head>
<body>
        <div id="maincontainer" class="mc">
                <div id="heading">Test plotly</div>
                <div id="row1" class="mc-item">
                        <div id="chart1" class="r1"></div>
                        <div id="chart2" class="r1"></div>
                        <div id="chart3" class="r1"></div>
                </div>
        </div>
        <script src="https://cdn.plot.ly/plotly-2.0.0.min.js"></script>
        <script src="chart.js"></script>
</body>
</html>

style.css

body {
        margin: 0px;
        padding: 0px;
}

#maincontainer{
        display: flex;
        flex-direction: column;
        height: 60vh;
}

#heading {
        font-size: 35px;
        font-weight: 600;
        text-align: center;
}

.mc-item { /* row1 */        
        flex-grow: 1;
        display: flex;
        border: 1px solid blue;
}

.r1 {
        border: 1px solid red;
        flex-grow: 1;
}

chart.js

document.addEventListener('DOMContentLoaded', function(){
        width = document.querySelector('#chart1').offsetWidth
        height = document.querySelector('#chart1').offsetHeight

        make_pie(height, width, 'chart1')
})

let make_pie = (height, width, chart_id)=>{
        var data = [{
                values: [19, 26, 55],
                labels: ['Residential', 'Non-Residential', 'Utility'],
                type: 'pie'
              }];
              
              var layout = {
                height: height,
                width: width,
                showlegend: false,
                paper_bgcolor: "#000",

              };
              
              Plotly.newPlot(chart_id, data, layout, {displayModeBar: false});
}

【问题讨论】:

    标签: javascript flexbox plotly plotly.js


    【解决方案1】:

    这是因为您在第一个 .r1 项目内设置了图形的宽度。弹性盒子项目并不意味着有一个固定的宽度,即使它是从弹性盒子布局计算出来的。

    如果您在 DOMContentLoaded 处理程序中调用 make_pie() 之前稍等片刻,您可以看到布局与预期的一样,直到您绘制图形。

    要解决这个问题,您可以为弹性项目(尤其是那些包含固定宽度元素的项目)添加相对宽度属性,例如。

    .r1 {
        border: 1px solid red;
        flex-grow: 1;
        width: 100%;
    }
    

    【讨论】:

    • 请解释为什么会这样?
    • 发生这种情况是因为您在第一个 .r1 项目内设置了图形的宽度。弹性盒子项目并不意味着有一个固定的宽度,即使它是从弹性盒子布局计算出来的(这里是 1*flex-grow/3items)。如果在 DOMContentLoaded 处理程序中调用 make_pie() 之前稍等片刻,您可以看到布局是正确的,直到您绘制图形。
    猜你喜欢
    • 2020-11-10
    • 2019-09-29
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    相关资源
    最近更新 更多