如何在Matplotlib的ax.bar()中应用ListedColormap?
解决Matplotlib中ax.bar()应用自定义ListedColormap的错误
错误原因
ax.bar()的color参数不接受ListedColormap对象,它需要的是具体的颜色值(如十六进制字符串、RGB元组)或颜色序列。直接传入Colormap对象时,Matplotlib会尝试获取其长度来匹配数据,而ListedColormap没有len()属性,因此触发TypeError。
解决方案
你可以通过两种方式正确使用自定义Colormap:
方法1:直接提取Colormap中的颜色列表
自定义的ListedColormap内置了colors属性,会返回你定义的颜色数组,直接按循环索引取对应颜色即可:
import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap cmap_cblind = ListedColormap(['#D1BBD7', '#4EB265']) species = ('Adelie', 'Chinstrap', 'Gentoo') sex_counts = { 'Male': np.array([73, 34, 61]), 'Female': np.array([73, 34, 58]), } fig, ax = plt.subplots() bottom = np.zeros(3) # 遍历同时获取索引,匹配对应颜色 for i, (sex, sex_count) in enumerate(sex_counts.items()): p = ax.bar(species, sex_count, bottom=bottom, color=cmap_cblind.colors[i]) bottom += sex_count plt.show()
方法2:通过Colormap映射数值生成颜色
如果后续类别数量可能变化,可以通过传入0-1之间的数值调用Colormap,动态生成对应颜色:
import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap cmap_cblind = ListedColormap(['#D1BBD7', '#4EB265']) species = ('Adelie', 'Chinstrap', 'Gentoo') sex_counts = { 'Male': np.array([73, 34, 61]), 'Female': np.array([73, 34, 58]), } fig, ax = plt.subplots() bottom = np.zeros(3) category_num = len(sex_counts) for i, (sex, sex_count) in enumerate(sex_counts.items()): # 按索引比例生成0-1之间的数值,映射到Colormap的颜色 color = cmap_cblind(i / (category_num - 1)) p = ax.bar(species, sex_count, bottom=bottom, color=color) bottom += sex_count plt.show()
内容的提问来源于stack exchange,提问作者Stücke
相关产品推荐
相关产品推荐

