使用textwrap.shorten处理matplotlib饼图长标签的报错问题求助
解决Matplotlib饼图标签过长的问题
错误原因分析
- 直接给
textwrap.shorten传入列表触发AttributeError:因为textwrap.shorten是处理单个字符串的方法,它内部会调用字符串的strip()方法,而列表没有这个属性。 - 将列表转为字符串后触发
ValueError:此时标签变成了一个单独的长字符串,而plt.pie要求labels参数的长度必须和饼图数据(df.Confronto.value_counts())的长度完全一致,长度不匹配就会报错。
正确解决方案
使用列表推导式,对每个标签单独调用textwrap.shorten处理,生成一个长度匹配的缩短后标签列表:
import textwrap import matplotlib.pyplot as plt # 生成缩短后的标签列表 short_labels = [textwrap.shorten(label, width=10, placeholder="...") for label in df.Confronto.value_counts().index] plt.pie(df.Confronto.value_counts(), labels=short_labels) plt.title(f"Confronto {Mese} - {Mese2}") plt.show()
替代方案(手动截断)
如果不想依赖textwrap,可以直接对字符串进行切片截断:
short_labels = [label[:10] + "..." if len(label) > 10 else label for label in df.Confronto.value_counts().index]
内容的提问来源于stack exchange,提问作者MiusiZ
相关产品推荐
相关产品推荐

