如何在Matplotlib半环形饼图的指定位置绘制标签
半环形饼图指定标签标注实现方案
问题背景
现有半环形饼图绘制代码,当前逻辑会为所有标签生成标注。需求为:仅对指定位置的标签(如第一个+最后一个、第一个+第三个)进行标注,且不创建新的标签列表,直接基于原列表的位置提取对应内容完成绘制。
原代码如下:
import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(8,6),dpi=100) ax = fig.add_subplot(1,1,1) pie_labels = ["Label 1", "Label 2", "Label 3"] pie_values = [1,2,3] pie_labels.append("Label 0") pie_values.append(sum(pie_values)) colors = ['red', 'blue', 'green', 'white'] wedges, texts = ax.pie(pie_values, wedgeprops=dict(width=0.35), startangle= -90,colors=colors) for w,lbl in zip(wedges,pie_labels): angle = w.theta2 r=w.r-w.width/2 x = r*np.cos(np.deg2rad(angle)) y = r*np.sin(np.deg2rad(angle)) ax.scatter(x,y) ax.annotate(lbl, xy=(x,y), size=12, color='k', ha='right', va='center', weight='bold')
生成的图表:
解决方案
核心思路是通过索引列表筛选需要标注的目标,直接从原wedges和pie_labels中提取对应位置的元素,无需新建列表。
示例1:标注第一个(索引0)和最后一个(索引-1)标签
修改循环部分代码即可:
# 指定需要标注的标签索引 target_indices = [0, -1] for idx in target_indices: w = wedges[idx] lbl = pie_labels[idx] angle = w.theta2 r = w.r - w.width/2 x = r * np.cos(np.deg2rad(angle)) y = r * np.sin(np.deg2rad(angle)) ax.scatter(x,y) ax.annotate(lbl, xy=(x,y), size=12, color='k', ha='right', va='center', weight='bold')
示例2:标注第一个(索引0)和第三个(索引2)标签
只需修改target_indices为对应索引即可:
# 指定需要标注的标签索引 target_indices = [0, 2] for idx in target_indices: w = wedges[idx] lbl = pie_labels[idx] angle = w.theta2 r = w.r - w.width/2 x = r * np.cos(np.deg2rad(angle)) y = r * np.sin(np.deg2rad(angle)) ax.scatter(x,y) ax.annotate(lbl, xy=(x,y), size=12, color='k', ha='right', va='center', weight='bold')
说明
- 索引从0开始计数,
pie_labels的顺序对应饼图各楔形块的顺序 - 若需要其他组合,只需调整
target_indices中的索引值即可,完全复用原数据,无需额外创建新列表
内容的提问来源于stack exchange,提问作者ruthpozuelo
相关产品推荐
相关产品推荐

