【问题标题】:Flask Plotly Responsive in BrowserFlask Plotly 在浏览器中响应
【发布时间】:2022-07-04 17:27:36
【问题描述】:

如何在 index.html 中使这个绘图图表响应 - 我创建了一个烧瓶应用程序和 js 函数来渲染绘图,但是,我不知道如何使其响应。变量配置有什么问题 - 它似乎不起作用。

谢谢

烧瓶:

@app.route('/')
def index():

    locations = sorted(df['location'].unique())
    rooms = sorted(df['rooms'].unique())

    # Visualisation
    import json
    import plotly
    import plotly.express as px
    df.rooms = df.rooms.astype(str)
    fig = px.scatter(df, x="m2", y="price", trendline="ols", color="rooms", symbol='rooms',
                                marginal_x="histogram", 
                                marginal_y="rug",
                                template='plotly_dark', hover_data=['price', 'rooms', 'm2', 'location'],
                                title="Real Estate in Vienna")
    
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template('index.html', locations=locations, rooms=rooms, graphJSON=graphJSON)

JavaScript:

                    <!-- Visualisation -->
                    {%block content%}
                    <div class="card mb-4 m-auto" style="width: 90%">
                        <div class="card-body">
                            <div id="chart"></div>
                        </div>
                    </div>
                    {% endblock %}

    <!-- Plotly -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">
        var graphs = {{ graphJSON | safe}};
        var config = {responsive: true};
        Plotly.newPlot("chart", graphs, {}, config);
    </script>

【问题讨论】:

    标签: javascript python flask plotly


    【解决方案1】:

    我认为您使用 Plotly.newPlot() 错误。通过阅读API reference 你会看到,这个函数有不同的签名:

    1. Plotly.newPlot(graphDiv, data, layout, config)
    2. Plotly.newPlot(graphDiv, obj)

    看起来你在使用 Python 函数后就把两者混为一谈了

    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    返回带有 datalayoutconfigframes 的键的单个对象,默认为 {data: [], layout: {}, config: {}, frames: []}

    因此,如果您使用以下 JavaScript 从对象 charts 中提取参数 datalayout 然后使用,那么一切都应该工作

    Plotly.newPlot(graphDiv, data, layout, config)

    而不是

    Plotly.newPlot(graphDiv, obj):

    <!-- Plotly -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">
        var chart = {{graphJSON | safe}};
        var data = chart["data"];
        var layout = chart["layout"];
        var config = {responsive: true};
        Plotly.newPlot("chart", data, layout, config);
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      相关资源
      最近更新 更多