如何在海底散点图中绘制核密度估计

时间:2020-04-15 09:11:37

标签: pandas matplotlib seaborn kernel-density

我想绘制与图片中所示相同的图形(但仅绘制红色部分)。曲线是仅基于X值的核密度估计值(y值无关紧要,实际上是所有1,2或3。这里只是像这样绘制以区分红色和蓝色。我已经绘制了散点图,但是如何在散点图上包括内核密度曲线(曲线中的黑色虚线仅是四分位数和中位数)。

import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt
from scipy.stats import norm
from sklearn.neighbors import KernelDensity
%matplotlib inline
# Change plotting style to ggplot
plt.style.use('ggplot')
from matplotlib.font_manager import FontProperties



X_plot = np.linspace(0, 30, 1000)[:, np.newaxis]

X1 = df[df['Zustandsklasse']==1]['Verweildauer'].values.reshape(-1,1)
X2 = df[df['Zustandsklasse']==2]['Verweildauer'].values.reshape(-1,1)
X3 = df[df['Zustandsklasse']==3]['Verweildauer'].values.reshape(-1,1)
#print(X1)



ax=sns.scatterplot(x="Verweildauer", y="CS_bandwith", data=df, legend="full", alpha=1)


kde=KernelDensity(kernel='gaussian').fit(X1)
log_dens = kde.score_samples(X_plot)
ax.plot(X_plot[:,0], np.exp(log_dens), color ="blue", linestyle="-", label="Gaussian Kernel")


ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.invert_yaxis()
plt.ylim(5.5, .5)
ax.set_ylabel("Zustandsklasse")
ax.set_xlabel("Verweildauer in Jahren")


handles, labels = ax.get_legend_handles_labels()
# create the legend again skipping this first entry
leg = ax.legend(handles[1:], labels[1:], loc="lower right", ncol=2, facecolor='silver', fontsize= 7)

ax.set_xticks(np.arange(0, 30, 5))
ax2 = ax.twinx()
#get the ticks at the same heights as the left axis
ax2.set_ylim(ax.get_ylim())


s=[(df["Zustandsklasse"] == t).sum() for t in range(1, 6)]
s.insert(0, 0)

print(s)
ax2.set_yticklabels(s)
ax2.set_ylim(ax.get_ylim())
ax2.set_ylabel("Anzahl Beobachtungen")
ax2.grid(False)

#plt.tight_layout()
plt.show()

Plotting target Whats is plotted with the code above

1 个答案:

答案 0 :(得分:2)

如果使用子图,则容易得多。这是seaborn的泰坦尼克号数据集的示例:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

titanic = sns.load_dataset('titanic')

fig, ax = plt.subplots(nrows=3, sharex=True)
ax[2].set_xlabel('Age')

for i in [1, 2, 3]:
    age_i = titanic[titanic['pclass'] == i]['age']
    ax[i-1].scatter(age_i, [0] * len(age_i))
    sns.kdeplot(age_i, ax=ax[i-1], shade=True, legend=False)
    ax[i-1].set_yticks([])
    ax[i-1].set_ylim(-0.01)
    ax[i-1].set_ylabel('Class ' + str(i))

kde subplots