Lam*_*ine 4 python matplotlib flask python-3.x
我想在我的 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()
Run Code Online (Sandbox Code Playgroud)
我尝试在 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()
Run Code Online (Sandbox Code Playgroud)
然后在模板/plot.html
<img src={{url}} alt="Chart" height="auto" width="100%">
Run Code Online (Sandbox Code Playgroud)