gpt4 book ai didi

python - 使用 Flask 显示 matplotlib 图

转载 作者:行者123 更新时间:2023-12-01 07:57:03 24 4
gpt4 key购买 nike

我想在我的 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 项目中运行此代码,但没有输出。

最佳答案

一个可能的解决方案是使用 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%">

关于python - 使用 Flask 显示 matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com