【发布时间】:2017-09-30 23:52:56
【问题描述】:
我的数据框如下所示:
travel_spending
state ethinicity
CA Asian 233.404580
MA Asian 748.117647
NY Asian 350.880000
CA Black 146.898148
MA Black 99.849057
NY Black 125.206897
CA Chinese 387.398601
MA Chinese 119.636364
NY Chinese 263.245283
CA Hispanic 131.156484
MA Hispanic 200.220859
NY Hispanic 175.738589
CA American Indian 36.500000
MA American Indian 67.500000
NY American Indian 81.800000
CA Japanese 365.029703
MA Japanese 28.666667
NY Japanese 241.500000
CA Other 257.953356
MA Other 208.178174
NY Other 255.144436
CA Portuguese 26.000000
MA Portuguese 22.000000
CA White 222.322485
MA White 167.293194
NY White 140.080838
从这个数据框中,我生成子图如下:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.ion()
plt.rcParams['xtick.color']='k'
plt.rcParams['xtick.labelsize']='x-large'
travel_df_new.unstack(level=0).plot(kind='bar', subplots=True, legend=False)
现在我正在尝试使用烧瓶将它们传递给 HTML 页面:
import sqlite3
import pandas as pd
from flask import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from io import BytesIO,StringIO
@app.route("/fig/")
def new_fig():
connection=sqlite3.connect('test.db')
query = "some sql query"
travel_df = pd.read_sql(query,connection)
plt.style.use('ggplot')
plt.ion()
plt.rcParams['xtick.color']='k'
plt.rcParams['xtick.labelsize']='x-large'
travel_df_new.unstack(level=0).plot(kind='bar', subplots=True, legend=False)
fig=plt.figure()
canvas = FigureCanvas(fig)
img = StringIO()
fig.savefig(img)
img.seek(0)
return send_file(img, mimetype='image/png')
@app.route('/image/')
def images():
return render_template("image.html")
下面是image.html
<html>
<head>
<title>{{ title }} - image</title>
</head>
<body>
<img src="/fig/" alt="Image Placeholder">
</body>
</html>
使用matplotlib.figure.Figure 即fig=plt.figure() 对象和StringIO 即img = StringIO() 和fig.savefig(img) 似乎是实现此目的的标准方法。但是我在 HTML 页面上看不到任何图像。
另外,使用plt.figure() 对象是否有助于显示所有子图?
【问题讨论】:
标签: python html pandas matplotlib flask