python生成饼图并在html中展示
时间: 2024-03-05 14:52:49 浏览: 71
要在Python中生成饼图并在HTML中展示,可以使用Matplotlib和Flask库。
首先,使用Matplotlib生成饼图:
```python
import matplotlib.pyplot as plt
# 创建数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# 绘制饼图
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal')
# 保存图像
plt.savefig('pie_chart.png')
```
然后,使用Flask将生成的图像在HTML中展示:
```python
from flask import Flask, render_template, send_file
app = Flask(__name__)
# 定义路由
@app.route('/')
def index():
# 在HTML中展示饼图
return render_template('index.html', chart='/chart')
# 定义路由
@app.route('/chart')
def chart():
# 返回生成的饼图
return send_file('pie_chart.png', mimetype='image/png')
if __name__ == "__main__":
app.run(debug=True)
```
最后,在HTML模板中展示饼图:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pie Chart</title>
</head>
<body>
<h1>Pie Chart</h1>
<img src="{{ url_for('chart') }}" alt="Pie Chart">
</body>
</html>
```
这样,就可以在本地运行Flask应用程序,并在浏览器中查看生成的饼图了。
阅读全文
相关推荐


















