一、前言
饼状图(Pie Chart)是一种常用的数据可视化图表,用于展示数据中各部分的占比关系。Python 中有多种库可以用于绘制饼状图,比较常用的包括 matplotlib
、pyecharts和 plotly
等。
二、使用 matplotlib
绘制饼状图
import matplotlib.pyplot as plt
# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25] # 每部分的占比
colors = ['gold', 'orange', 'lightgreen', 'lightcoral'] # 颜色
explode = (0.1, 0, 0, 0) # 突出显示第一部分
# 绘制饼状图
plt.figure(figsize=(8, 6))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title('Fruit Distribution') # 图表标题
plt.axis('equal') # 使饼状图长宽相等
plt.show()
说明:
1)labels
是各部分的标签。</