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

如何禁用seaborn kdeplot的渐变色,绘制单一橙色图形

问题:如何让Seaborn KDE图显示单一橙色而非渐变色?

运行下方代码后,生成的二维核密度估计图呈现从黑色到橙色的渐变效果,但我希望图中仅显示单一橙色,请问该如何修改代码?

我的代码:

#!/usr/bin/python3
import numpy as np
import pylab as plot
import matplotlib.pyplot as plt
import numpy, scipy, pylab, random
from matplotlib.ticker import MultipleLocator
import matplotlib as mpl
from matplotlib.ticker import MaxNLocator
import seaborn as sns
import pandas as pd

fig, ax = plt.subplots(figsize=(4, 2))

df = pd.read_csv('input.txt', sep="\s\s+", engine='python')
sns.kdeplot(data=df, label = "s1", color = "orange", cmap=None)
plt.xlabel('x', fontsize=7)
plt.ylabel('y', fontsize=7)

for axis in ['top','bottom','left','right']:
  ax.spines[axis].set_linewidth(0.5)

plt.savefig("plot.png", dpi=300, bbox_inches='tight')

input.txt内容:

0.43082    0.45386
   0.35440    0.91632
   0.16962    0.85031
   0.07069    0.54742
   0.31648    1.06689
   0.57874    1.17532
   0.18982    1.01678
   0.31012    0.54656
   0.31133    0.81658
   0.53612    0.50940
   0.36633    0.83130
   0.37021    0.74655
   0.28335    1.30949
   0.11517    0.63141
   0.24908    1.04403
  -0.28633    0.46673
  -0.13251    0.33448
  -0.00568    0.53939
  -0.03536    0.76191
   0.24695    0.92592

生成的图形:一张二维核密度估计图,颜色从中心区域的黑色向外渐变为橙色。


解决方案

问题根源:Seaborn的kdeplot默认绘制二维KDE时,会生成填充的等高线图,默认使用渐变色彩映射,即使设置了color参数,也只是作为渐变的基准色,因此会出现黑橙渐变效果。

根据需求有两种修改方式:

1. 生成单一橙色的填充区域

如果需要保留填充效果但只用单一橙色,需添加fill=True并设置thresh=0(让整个密度区域都被填充),同时可以调整alpha控制透明度:

修改后的kdeplot行代码:

sns.kdeplot(data=df, label="s1", color="orange", fill=True, thresh=0, alpha=0.7)

2. 生成单一橙色的等高线(无填充)

如果只需要橙色的轮廓线,不需要填充,设置fill=False即可:

修改后的kdeplot行代码:

sns.kdeplot(data=df, label="s1", color="orange", fill=False)

完整修改示例代码

以下是第一种情况(填充单一橙色)的完整代码:

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns
import pandas as pd

fig, ax = plt.subplots(figsize=(4, 2))

df = pd.read_csv('input.txt', sep="\s\s+", engine='python')
# 修改kdeplot参数,实现单一橙色填充
sns.kdeplot(data=df, label="s1", color="orange", fill=True, thresh=0, alpha=0.7)

plt.xlabel('x', fontsize=7)
plt.ylabel('y', fontsize=7)

for axis in ['top','bottom','left','right']:
  ax.spines[axis].set_linewidth(0.5)

plt.savefig("plot.png", dpi=300, bbox_inches='tight')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:30:30