如果我设置shade_lowest = False,则颜色栏仍包含最低级别(purple-ish).有没有通用的方法来完全删除它?
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0,1,100)
b = np.random.normal(0,100)
fig,ax = plt.subplots()
sns.kdeplot(a,b,shade = True,shade_lowest = False,cmap = "viridis",cbar = True,n_levels = 4,ax = ax)
plt.show()
最佳答案
一个解决方案肯定不会从一开始就创建这个级别.
在这里,我们根据定位器选择最多5个级别,并在调用contourf图时删除最低级别,这样这个级别甚至不存在于第一位.然后自动颜色栏创建工作完美无缺.
import numpy as np; np.random.seed(5)
import matplotlib.pyplot as plt
from matplotlib import ticker
from scipy import stats
x = np.random.normal(3,100)
y = np.random.normal(0,2,100)
X,Y = np.mgrid[x.min():x.max():100j,y.min():y.max():100j]
positions = np.vstack([X.ravel(),Y.ravel()])
values = np.vstack([x,y])
kernel = stats.gaussian_kde(values)
Z = np.reshape(kernel(positions).T,X.shape)
N=4
locator = ticker.MaxNLocator(N + 1,min_n_ticks=N)
lev = locator.tick_values(Z.min(),Z.max())
fig,ax = plt.subplots()
c = ax.contourf(X,Y,Z,levels=lev[1:])
ax.scatter(x,y,s=9,c="k")
fig.colorbar(c)
plt.show()