使用Flask显示matplotlib图表

5

我希望能够在我的Flask Web项目中可视化绘图(使用SciView)

以下是我的代码:

import matplotlib.pyplot as plt 
# x-coordinates of left sides of bars 
left = [1, 2, 3, 4, 5] 
# heights of bars 
height = [10, 24, 36, 40, 5] 
# labels for bars 
tick_label = ['one', 'two', 'three', 'four', 'five'] 
# plotting a bar chart 
plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green']) 
# naming the y-axis 
plt.xlabel('y - axis') 
# naming the x-axis 
plt.xlabel('x - axis') 
# plot title 
plt.title('My bar chart!') 
# function to show the plot 
plt.show()

我尝试在我的Flask项目中运行此代码,但没有输出。

1
这是我的代码 - 它在哪里? - ForceBru
导入 matplotlib.pyplot as plt

条形图左侧的 x 坐标

left = [1, 2, 3, 4, 5]

条形图高度

height = [10, 24, 36, 40, 5]

条形图标签

tick_label = ['one', 'two', 'three', 'four', 'five']

绘制条形图

plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green'])

命名 x 轴

plt.xlabel('x - axis')

命名 y 轴

plt.ylabel('y - axis')

图表标题

plt.title('My bar chart!')

显示图表函数

plt.show()
- Lamine Sirine
1
请在您的帖子中包含您的代码,并进行格式化 - ForceBru
1
通常你会在 Flask 中使用 Plotly 或 D3.js。Matplotlib 主要用于桌面应用场景。 - OneCricketeer
我还建议几乎所有这些注释都是不必要的。它们会使代码混乱,阅读起来更加困难,而且提供的信息在代码本身中已经包含了,没有新的信息。 - Mihai Chelaru
1个回答

7
一种可能的解决方案是,使用plt.savefig保存图形,并将其附加到HTML <img>标记中。
from flask import Flask, render_template
import matplotlib.pyplot as plt

app = Flask(__name__)

@app.route('/plot')
def plot():
    left = [1, 2, 3, 4, 5]
    # heights of bars
    height = [10, 24, 36, 40, 5]
    # labels for bars
    tick_label = ['one', 'two', 'three', 'four', 'five']
    # plotting a bar chart
    plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green'])

    # naming the y-axis
    plt.ylabel('y - axis')
    # naming the x-axis
    plt.xlabel('x - axis')
    # plot title
    plt.title('My bar chart!')

    plt.savefig('static/images/plot.png')

    return render_template('plot.html', url='/static/images/plot.png')

if __name__ == '__main__':
   app.run()

然后在templates/plot.html中。
<img src={{url}} alt="Chart" height="auto" width="100%">

如何围绕MVC模式重新创建这个简单的应用程序? Flask是否支持MVC模式? - Ashish Jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接