You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib饼图设色触发ValueError: Invalid RGBA参数报错求助

解决Matplotlib饼图Invalid RGBA Argument错误

问题原因

报错ValueError: Invalid RGBA argument: '(153, 153, 0)'的核心问题是:你的dict_langfam2color字典里的颜色值是字符串类型的"(153,153,0)",但Matplotlib的plt.pie()函数要求RGBA参数是数值元组(而非字符串),且RGB值需要是0-1范围的浮点数,或者0-255范围的整数。

解决方案

直接修改颜色字典,把字符串格式的颜色值替换成数值元组即可,两种格式都支持:

方式1:归一化到0-1的浮点元组(官方推荐)

将每个RGB分量除以255,转换为0-1之间的浮点数,这是Matplotlib最标准的颜色参数格式:

dict_langfam2color={
"Anglosphere": (151/255, 0/255, 0/255), # dark red
"EastAsia": (0/255, 102/255, 102/255), # dark turquoise
"Germanic": (96/255, 96/255, 96/255), # grey
"Indo-Iranian": (153/255, 76/255, 0/255), # dark yellow
"Isolate": (153/255, 0/255, 76/255),  # dark pink
"Latin": (153/255, 153/255, 0/255), # dark yellow
"Semetic": (0/255, 102/255, 0/255), # dark green
"Slavic": (0/255, 153/255, 153/255), # dark blue/green
"SubSaharanAfrica": (0/255, 0/255, 153/255), # dark blue
"Turkic": (76/255, 0/255, 153/255) # dark purple 
}

方式2:直接使用0-255的整数元组

如果不想做归一化,直接去掉引号保留整数元组也可以:

dict_langfam2color={
"Anglosphere": (151, 0, 0), # dark red
"EastAsia": (0, 102, 102), # dark turquoise
"Germanic": (96, 96, 96), # grey
"Indo-Iranian": (153, 76, 0), # dark yellow
"Isolate": (153, 0, 76),  # dark pink
"Latin": (153, 153, 0), # dark yellow
"Semetic": (0, 102, 0), # dark green
"Slavic": (0, 153, 153), # dark blue/green
"SubSaharanAfrica": (0, 0, 153), # dark blue
"Turkic": (76, 0, 153) # dark purple 
}

修改后的完整代码

dict_countrycode2info={
"AND": ["1", "Andorra", "AND", "Latin", "1004", "01-06-2018-22-09-2018", "PAPI", "Catalan,English,Spanish,French"],
"ARG": ["2", "Argentina", "ARG", "Latin", "1003", "04-07-2017-19-07-2017", "PAPI", "Spanish"],
# 省略其余国家信息条目
}

# 修改后的RGB颜色映射(这里用归一化浮点元组示例)
dict_langfam2color={
"Anglosphere": (151/255, 0/255, 0/255), # dark red
"EastAsia": (0/255, 102/255, 102/255), # dark turquoise
"Germanic": (96/255, 96/255, 96/255), # grey
"Indo-Iranian": (153/255, 76/255, 0/255), # dark yellow
"Isolate": (153/255, 0/255, 76/255),  # dark pink
"Latin": (153/255, 153/255, 0/255), # dark yellow
"Semetic": (0/255, 102/255, 0/255), # dark green
"Slavic": (0/255, 153/255, 153/255), # dark blue/green
"SubSaharanAfrica": (0/255, 0/255, 153/255), # dark blue
"Turkic": (76/255, 0/255, 153/255) # dark purple 
}

language_families = {
    'AND': 'Latin',
    'ARG': 'Latin',
    'AUS': 'Anglosphere',
    # 省略其余国家-语言家族映射条目
}

from collections import Counter
import matplotlib.pyplot as plt

language_counts = Counter(language_families.values())
colors = [dict_langfam2color[fam] for fam in language_counts.keys()]

plt.pie(language_counts.values(), labels=language_counts.keys(), autopct='%1.1f%%', colors=colors)
plt.show()

内容的提问来源于stack exchange,提问作者Lili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:32:38