Matplotlib绘图饼状图实例
时间: 2023-08-13 14:02:21 浏览: 116
下面是一个使用Matplotlib绘制饼状图的实例:
```python
import matplotlib.pyplot as plt
# 饼状图数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# 饼状图颜色
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
# 绘制饼状图
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
# 添加标题
plt.title('Pie Chart Example')
# 显示图形
plt.show()
```
运行代码后,将会绘制出一个带有标签和比例的饼状图。
其中,`labels`和`sizes`是饼状图的数据,`colors`是各个扇形区域的颜色。`autopct`用于设置标签文本的格式,`startangle`用于设置起始角度。通过调整这些参数,可以绘制出不同类型的饼状图。
相关问题
Matplotlib绘图,个人支出实例饼状图。代码并说明图表意义
以下是一个Matplotlib绘制个人支出实例饼状图的示例代码:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['饮食', '住房', '交通', '娱乐', '其他']
sizes = [30, 25, 15, 20, 10]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#ffb3e6']
# 绘图
fig, ax = plt.subplots()
ax.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
# 标题
plt.title('个人支出实例饼状图')
# 显示图表
plt.show()
```
图表意义:
该饼状图展示了一个人在不同支出类别上的支出比例。其中,饮食占总支出的30%,住房占25%,交通占15%,娱乐占20%,其他占10%。通过这个图表,我们可以清晰地了解该人的支出结构,进而进行合理的财务规划。
Matplotlib饼状图
### 如何使用 Matplotlib 创建饼状图
为了展示如何用 `Matplotlib` 绘制饼状图,下面提供了一个详细的实例教程。此例子不仅展示了基本的绘图方法,还包含了自定义颜色、突出显示特定部分以及添加阴影效果等功能。
#### 导入必要的库并准备数据集
首先,导入所需的 Python 库,并准备好要可视化的数据集合:
```python
import matplotlib.pyplot as plt
# 数据准备
labels = ['娱乐', '育儿', '饮食', '房贷', '交通', '其他']
sizes = [1, 4, 5, 8, 13, 14]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99', '#ffb3e6', '#c2c2f0']
explode = (0, 0, 0, 0, 0.1, 0) # 将第五个扇区稍微分离出来以便强调
```
#### 设置图表属性
接着设置一些额外的参数来增强图表的表现力,比如字体样式以支持中文标签[^2]:
```python
plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示中文标签
```
#### 开始绘制饼图
现在可以调用 `pie()` 函数开始绘制饼形图了。这里设置了多个选项来自定义外观,例如百分比格式化方式 (`autopct`) 和起始角度 (`startangle`) 等[^1]:
```python
fig1, ax1 = plt.subplots()
ax1.pie(
sizes,
explode=explode,
labels=labels,
colors=colors,
autopct='%1.1f%%',
startangle=150,
shadow=False
)
```
#### 调整布局使饼图为正圆
为了让最终呈现出来的饼图保持完美的圆形而不是椭圆形,在最后一步调整坐标轴比例一致:
```python
ax1.axis('equal')
```
#### 展示结果
完成上述配置之后就可以通过 `show()` 方法查看生成的结果图像了:
```python
plt.title('生活开销分布情况')
plt.show()
```
以上就是完整的基于 `Matplotlib` 的饼状图制作过程。希望这个案例能够帮助理解如何有效地运用该工具来进行简单的数据分析与表达。
阅读全文
相关推荐















