使用matplotlib Set1色板前N色绘制聚类散点图报错求助
解决Matplotlib聚类可视化中Set1色板切片报错问题
问题原因
你当前的代码把Set1色板转换成了RGBA颜色数组,但scatter函数的cmap参数要求传入Colormap对象,而非直接的颜色值数组,这才触发了ValueError。
解决方案1:直接使用颜色列表(推荐)
Set1是离散色板,可直接提取前k种颜色,用color参数替代cmap:
import matplotlib.cm as cm # 获取Set1色板的前k种颜色 colors = cm.get_cmap('Set1').colors[:k] # 将聚类标签转为整数索引,对应颜色列表 points = ax.scatter(data['PC1'], data['PC2'], c=data['cluster'].astype(int), color=colors, alpha=0.7) ax.legend(*points.legend_elements(), title='test')
注:如果聚类标签是字符串或非连续数字,需先将其映射为0到k-1的整数索引,比如用pd.factorize(data['cluster'])[0]处理。
解决方案2:创建自定义离散Colormap
若坚持使用cmap参数,可将截取的颜色包装为合法的Colormap对象:
from matplotlib.colors import ListedColormap import matplotlib.cm as cm # 提取Set1前k种颜色并生成自定义色板 set1_slice = cm.get_cmap('Set1').colors[:k] custom_cmap = ListedColormap(set1_slice) points = ax.scatter(data['PC1'], data['PC2'], c=data['cluster'], cmap=custom_cmap, alpha=0.7) ax.legend(*points.legend_elements(), title='test')
内容的提问来源于stack exchange,提问作者Dizzy
相关产品推荐
相关产品推荐

