所以我想出了如何做到这一点。我将从seaborn图中检索x和y数组,然后使用fill_between
来着色曲线下方。
points = sns.kdeplot(data['numbers'], shade=True).get_lines()[0].get_data()
x = points[0]
y = points[1]
plt.fill_between(x,y, where = x >=0.75, color='r')
plt.fill_between(x,y, where = x <=0.1, color='g')
plt.fill_between(x,y, where = (x<=0.75) & (x>=0.1), color='y')
自原回答发布以来唯一的区别是需要将shade=True
更改为shaded=False
。
我还想分享一个稍微更完整的答案,供那些想要复制粘贴的人参考。
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
mean = 0
std = 1
np.random.seed(0)
x = np.random.normal(loc=mean, scale=std, size=10000)
points = sns.kdeplot(x, shade=False, bw_method=1.0, color='black').get_lines()[0].get_data()
x = points[0]
y = points[1]
plt.fill_between(x, y, color='y')
plt.fill_between(x, y, where = (x<=0.5*std) & (x >= -0.5 * std), color='g') #
plt.fill_between(x, y, where = (x>=2*std) | (x<=-2*std), color='r')