【问题标题】:Flask Matplotlib Python烧瓶 Matplotlib Python
【发布时间】:2018-04-16 02:03:36
【问题描述】:

无法通过用户输入动态更新数据可视化图表。

make_visual 获取信息,创建 matplotlib 视觉效果,然后将它们保存在静态位置。

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

def make_visual(nums):
    a, b, c, d, e, f, g, h = nums
    turn_labels = "A", "B"
    turn_size = [a,b]
    goes_labels = "1", "2"
    goes_size = [c,d]
    method_labels = "Moo", "Bark", "Meow"
    method_size = [g, f, e]
    fig1, ax1 = plt.subplots()
    ax1.pie(turn_size, labels=turn_labels, autopct='%1.1f%%', startangle=90)
    ax1.axis('equal')
    plt.savefig("static/graph.png")
    fig2, ax2 = plt.subplots()
    ax2.pie(goes_size, labels=goes_labels, autopct='%1.1f%%', startangle=90)
    ax2.axis('equal')
    plt.savefig("static/goes.png")
    fig3, ax3 = plt.subplots()
    ax3.pie(method_size, labels=method_labels, autopct='%1.1f%%', startangle=90)
    ax3.axis('equal')
    plt.savefig("static/method.png")

make_visual([0.50, 0.50, 0.4, 0.6, 0.43, 0.3, 0.27, 14.511904761904763])

^ 当它在命令行中独立运行时,它可以工作。 在 Flask 函数中不起作用。 如果我删除 make_visual,信息会按预期传递到 results.html 页面。

我不确定为什么我无法使用静态文件夹中的当前视觉效果动态创建、保存和呈现页面。

@app.route('/results', methods=['POST'])
def results():
    stats = request.form['data']
    info = get_stats(stats)
    unstr = stats.split(',')
    title = make_string(unstr[0], unstr[1])
    make_visual(info)
    return render_template('results.html', stats=title, data=info)

下面是 results.html。

{% block content %}
<div class='container-fluid text-center'>
        <h1 class='p-2 m-2'>Results</h1>
        <h3 class='text-success'>{{ stats }}</h3>
        <h4>{{ data }}</h4>
    <div class="row mt-2">
        <div class="col-lg-4 p-1">
            <img class='img-fluid' src="/static/graph.png">
        </div>
        <div class="col-lg-4 p-1">
            <img class='img-fluid' src="/static/goes.png">
        </div>
        <div class="col-lg-4 p-1">
            <img class='img-fluid' src="/static/method.png">
        </div>
    </div>
{% endblock %}

【问题讨论】:

    标签: python matplotlib flask


    【解决方案1】:

    为了获得最佳结果,请显示演示问题的代码,删除无关的细节并以足够完整的形式运行它。通常这样做就足以找出原因。

    但是,让 matplotlib 与 Flask 一起工作涉及到一个技巧。我猜是之后

    import matplotlib
    

    没有

    matplotlib.use('agg')
    

    不使用 matplotlib 将尝试使用 tkinter 进行渲染,这在尝试使用 Flask 时会导致悲伤。

    【讨论】:

    • 不错的猜测和想法。我在问题中添加了 make_visual 函数。
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2020-10-18
    • 2018-05-24
    相关资源
    最近更新 更多