以post请求如何将matplotlib画出的图输出到网页上显示,并编写相应代码
时间: 2024-03-27 20:39:28 浏览: 11
要将matplotlib画出的图输出到网页上显示,可以使用Python的Flask框架。具体步骤如下:
1. 安装Flask和matplotlib库
```python
pip install Flask matplotlib
```
2. 编写Flask应用程序
```python
from flask import Flask, render_template, Response
import matplotlib.pyplot as plt
import io
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot.png')
def plot_png():
# 生成一张图片
fig = plt.figure()
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
# 将图片保存至内存中
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
# 将图片转换为Flask Response对象
return Response(buf, mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True)
```
3. 编写网页模板
```html
<!DOCTYPE html>
<html>
<head>
<title>Matplotlib Plot</title>
</head>
<body>
<img src="/plot.png" alt="Matplotlib Plot">
</body>
</html>
```
4. 运行Flask应用程序
```python
python app.py
```
5. 在浏览器中打开http://localhost:5000,即可看到matplotlib画出的图像。