【发布时间】:2020-10-18 00:32:10
【问题描述】:
我正在尝试在烧瓶模板中渲染 matplotlib 和 seaborn 图的图像,如下所示:
from flask import Flask, render_template, make_response
import matplotlib.pyplot as plt
import seaborn as sns
from io import BytesIO
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot():
fig = Figure()
plot= fig.add_subplot(1, 1, 1)
jb=np.array([1.74, 0.82, 0.32, 1.33, 1.03, 0.31, 1.09, 1.0, 0.98, 1.76, 0.73, 0.37, 0.62,
0.24, 0.15, 1.05, 0.99, 1.14, 0.9, 0.29, 0.95,1.41, 0.81])
you=1.4
tipmedian=1.3
ax = jobTip.plot(kind='density', color='black')
ax.set_xlabel('Years in Jobcode')
# vertical dotted line originating at median value
plt.axvline(tipmedian, linestyle='dashed', linewidth=2, color='black')
plt.text(tipmedian, 1.3,'Group Median='+str(tipmedian)+' years(s)',rotation='vertical')
# vertical dotted line originating at current user value
plt.axvline(you, linestyle='dashed', linewidth=2, color='orange')
plt.text(you, 1.3,'You='+str(you)+' years(s)',rotation='vertical')
g=sns.kdeplot(jobTip, color="grey", shade=True)
g.legend_.remove()
canvas = FigureCanvas(fig)
output = BytesIO()
canvas.print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
我正在尝试将绘图作为图像发送到如下模板(在烧瓶 jinja html 中):
<img src="/plot.png" >
这里我不想保存图像以在模板中渲染绘图,因为它会根据用户的请求数据动态生成。我正在努力解决这个问题。如果有人可以帮助我,我将不胜感激。
【问题讨论】:
-
尝试将图像转换为base64格式并在图像元素中使用。
-
你能给我一些参考网址吗,我是python的新手@ParthVerma
标签: python matplotlib flask seaborn