python怎么创建饼图
时间: 2023-03-02 14:22:38 浏览: 76
在 Python 中创建饼图,可以使用 `matplotlib` 库。以下是使用 `matplotlib` 库创建饼图的基本步骤:
1. 导入 `matplotlib` 库
```python
import matplotlib.pyplot as plt
```
2. 准备数据,例如以下示例数据:
```python
labels = ['A', 'B', 'C', 'D'] # 饼图各部分的标签
sizes = [30, 20, 25, 25] # 饼图各部分的大小,总和应为 100
```
3. 创建饼图
```python
plt.pie(sizes, labels=labels)
```
4. 可选:设置标题和保存图像
```python
plt.title('Pie Chart Example')
plt.savefig('pie_chart.png')
```
完整示例代码如下:
```python
import matplotlib.pyplot as plt
# 准备数据
labels = ['A', 'B', 'C', 'D']
sizes = [30, 20, 25, 25]
# 创建饼图
plt.pie(sizes, labels=labels)
# 设置标题和保存图像
plt.title('Pie Chart Example')
plt.savefig('pie_chart.png')
# 显示饼图
plt.show()
```
执行上述代码,即可创建一个简单的饼图,并将其保存为一个名为 `pie_chart.png` 的图像文件。