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

如何修改kdeplot/scatterplot变量颜色?自定义调色板致散点消失

解决散点添加自定义调色板后消失的问题

问题根源

ax.scatter()是Matplotlib原生绘图函数,不支持palette参数——这个参数是Seaborn专属的。直接给它加palette不仅不会生效,还会因为参数不兼容导致散点渲染异常,最终看不到点。

两种可行解决方案

方案1:用Matplotlib原生方式映射颜色

把月份数据通过自定义调色板字典转换成对应的颜色列表,再传给c参数:

fig,ax=plt.subplots()
kde = sns.kdeplot(data=HR25, x='X', y='Y', shade=True, ax=ax, levels=levels_, cmap="Reds", alpha=0.9)
ax.set_xlim([x_min-10, x_max+10])
ax.set_ylim([y_min-10, y_max+10])

# 把月份映射为对应颜色
colors = [palette[m] for m in months]
# 用转换后的颜色列表绘制散点
ax.scatter(X, Y, c=colors, edgecolors='black', picker=True, s=17)

ax.set_aspect('equal')
plt.show()

方案2:改用Seaborn的scatterplot函数

Seaborn的scatterplot原生支持palette参数,直接指定hue为月份字段即可:

fig,ax=plt.subplots()
kde = sns.kdeplot(data=HR25, x='X', y='Y', shade=True, ax=ax, levels=levels_, cmap="Reds", alpha=0.9)
ax.set_xlim([x_min-10, x_max+10])
ax.set_ylim([y_min-10, y_max+10])

# 替换为seaborn的scatterplot,支持palette参数
sns.scatterplot(data=你的DataFrame名称, x='X', y='Y', hue='Month', palette=palette, 
                edgecolor='black', picker=True, s=17, ax=ax)

ax.set_aspect('equal')
plt.show()

注意:这里需要把你的DataFrame名称替换成你实际存储X、Y、Month的DataFrame变量名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:03:31