在Matplotlib 2.1.0版本及以上,可以使用pie
函数的autopct
参数来实现标签对齐的饼图。
下面是一个示例代码:
import matplotlib.pyplot as plt
# 饼图数据
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
# 设置标签对齐的饼图
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, counterclock=False, textprops={'ha': 'center'})
# 设置图表标题
ax.set_title('Pie Chart with Aligned Labels')
# 显示饼图
plt.show()
在上述代码中,我们使用pie
函数创建了一个饼图。autopct
参数设置了百分比的显示格式,textprops
参数用于设置标签的对齐方式,这里使用{'ha': 'center'}
将标签居中对齐。startangle
参数设置了饼图的起始角度,counterclock
参数设置了饼图的顺时针方向。
最后,使用set_title
方法设置了图表的标题,并通过plt.show
显示饼图。