Matplotlib绘制饼图遇'tuple'无sum属性错误,求解决方案
问题描述
尝试用Matplotlib绘制饼图时触发AttributeError: 'tuple' object has no attribute 'sum'错误,相关代码及错误回溯如下:
原代码
import matplotlib.pyplot as plt import numpy labels = 'Updated', 'Coverage (overall)', 'last 24 hours', 'Deleted', 'Deleted last 24 hours', 'Banned', 'Banned last 24 hours' sizes = (6, 5.04, 0, 12, 0, 7, 7) colors = ['yellowgreen', 'gold', 'lightskyblue', 'green', 'black', 'red', 'grey'] def absolute_value(val): a = numpy.round(val/100.*sizes.sum(), 0) return a plt.pie(sizes, labels=labels, colors=colors, autopct=absolute_value) plt.axis('equal') plt.show()
错误回溯
AttributeError Traceback (most recent call last) Cell In[46], line 12 9 a = numpy.round(val/100.*sizes.sum(), 0) 10 return a ---> 12 plt.pie(sizes, labels=labels, colors=colors, 13 autopct=absolute_value) 15 plt.axis('equal') 16 plt.show() File ~\AppData\Roaming\Python\Python39\site-packages\matplotlib\pyplot.py:2715, in pie(x, explode, labels, colors, autopct, pctdistance, shadow, labeldistance, startangle, radius, counterclock, wedgeprops, textprops, center, frame, rotatelabels, normalize, data) 2708 @_copy_docstring_and_deprecators(Axes.pie) 2709 def pie( 2710 x, explode=None, labels=None, colors=None, autopct=None, 2711 pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, 2712 radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, 2713 rotatelabels=False, *, normalize=True, data=None): -> 2715 return gca().pie( 2716 x, explode=explode, labels=labels, colors=colors, 2717 autopct=autopct, pctdistance=pctdistance, shadow=shadow, 2718 labeldistance=labeldistance, startangle=startangle, 2719 radius=radius, counterclock=counterclock, 2720 wedgeprops=wedgeprops, textprops=textprops, center=center, 2721 frame=frame, rotatelabels=rotatelabels, normalize=normalize, 2722 **({"data": data} if data is not None else {})) File ~\AppData\Roaming\Python\Python39\site-packages\matplotlib\__init__.py:1423, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs) 1420 @functools.wraps(func) 1421 def inner(ax, *args, data=None, **kwargs): 1422 if data is None: -> 1423 return func(ax, *map(sanitize_sequence, args), **kwargs) 1425 bound = new_sig.bind(ax, *args, **kwargs) 1426 auto_label = (bound.arguments.get(label_namer) 1427 or bound.kwargs.get(label_namer)) File ~\AppData\Roaming\Python\Python39\site-packages\matplotlib\axes\_axes.py:3236, in Axes.pie(self, x, explode, labels, colors, autopct, pctdistance, shadow, labeldistance, startangle, radius, counterclock, wedgeprops, textprops, center, frame, rotatelabels, normalize) 3234 s = autopct % (100. * frac) 3235 elif callable(autopct): -> 3236 s = autopct(100. * frac) 3237 else: 3238 raise TypeError( 3239 'autopct must be callable or a format string') Cell In[46], line 9, in absolute_value(val) 8 def absolute_value(val): ----> 9 a = numpy.round(val/100.*sizes.sum(), 0) 10 return a AttributeError: 'tuple' object has no attribute 'sum'
错误原因
sizes是Python原生**元组(tuple)**类型,元组没有sum()方法,调用sizes.sum()直接触发属性错误。
解决方法
方法1:将元组转为NumPy数组
把sizes定义为NumPy数组,即可调用sum()方法:
sizes = numpy.array([6, 5.04, 0, 12, 0, 7, 7])
方法2:用Python内置sum()函数计算总和
不修改sizes类型,直接用内置sum()函数计算元组总和,修改absolute_value函数:
def absolute_value(val): a = numpy.round(val/100. * sum(sizes), 0) return a
额外优化(可选)
autopct要求返回字符串才能在饼图上正常显示,当前返回数值可能显示异常,建议转为字符串:
def absolute_value(val): a = numpy.round(val/100. * sum(sizes), 0) return f'{a}'
修正后的完整代码
import matplotlib.pyplot as plt import numpy labels = 'Updated', 'Coverage (overall)', 'last 24 hours', 'Deleted', 'Deleted last 24 hours', 'Banned', 'Banned last 24 hours' sizes = (6, 5.04, 0, 12, 0, 7, 7) colors = ['yellowgreen', 'gold', 'lightskyblue', 'green', 'black', 'red', 'grey'] def absolute_value(val): a = numpy.round(val/100. * sum(sizes), 0) return f'{a}' plt.pie(sizes, labels=labels, colors=colors, autopct=absolute_value) plt.axis('equal') plt.show()
内容的提问来源于stack exchange,提问作者maria bandoria
相关产品推荐
相关产品推荐

