如何在Matplotlib饼图扇区内添加自动旋转的标签?
实现内部旋转标签的饼图
你不需要借助autopct来实现标签旋转,调整plt.pie()的几个参数就能让标签自动旋转并显示在扇区内部:
labeldistance:设置标签到饼图中心的距离,值小于1时标签会显示在扇区内部(比如设为0.7)rotatelabels=True:保持标签自动旋转,匹配扇区角度- 可选通过
textprops调整字体大小,避免多个标签拥挤重叠
修改后的完整代码:
import matplotlib.pyplot as plt entity_names = ['The Desolation', 'The Corruption', 'The Eye', 'The Web', 'The Stranger', 'The Extinction', 'The Lonely', 'The Vast', 'The End', 'The Hunt', 'The Dark', 'The Buried', 'The Flesh', 'The Slaughter', 'The Spiral'] slice_sizes = [1]*15 # 简化重复值的写法 # 调整参数让标签在内部旋转显示 wedges, texts = plt.pie( slice_sizes, labels=entity_names, rotatelabels=True, labeldistance=0.7, # 标签位置在扇区内部 textprops={'fontsize': 8} # 缩小字体避免拥挤 ) plt.savefig('pie_chart.svg', bbox_inches='tight') # 加bbox_inches避免标签被裁剪
如果需要更精细控制标签的旋转角度或位置,可以遍历texts对象单独调整每个标签的属性,比如:
for text in texts: text.set_rotation(text.get_rotation() + 90) # 额外调整旋转角度
内容的提问来源于stack exchange,提问作者JetSetTime
相关产品推荐
相关产品推荐

