Seaborn中位数模式线仅显示在最后一张图中

Bil*_*mer 4 python matplotlib seaborn

我试图显示meanmedianmode线两个图,但他们只是在最后图可见:

#Cut the window in 2 parts
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (0.2, 1)})
#plt.figure(figsize=(10,7));
mean=df[' rating'].mean()
median=df[' rating'].median()
mode=df[' rating'].mode().get_values()[0]
plt.axvline(mean, color='r', linestyle='--')
plt.axvline(median, color='g', linestyle='-')
plt.axvline(mode, color='b', linestyle='-')
plt.legend({'Mean':mean,'Median':median,'Mode':mode})

sns.boxplot(df[" rating"], ax=ax_box)
sns.distplot(df[" rating"], ax=ax_hist)

ax_box.set(xlabel='')
Run Code Online (Sandbox Code Playgroud)

小智 10

较短的一个(使用jupyter notebook):

import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline

sns.distplot(xgb_errors, kde=True, rug=True);
plt.axvline(np.median(xgb_errors),color='b', linestyle='--')
Run Code Online (Sandbox Code Playgroud)


Mr.*_*. T 7

该命令plt使用当前轴,而不是所有定义的轴。要在特定轴上绘制某些东西,您必须告诉matplotlib / seaborn,这是指哪个轴:

from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame({" rating": [1, 2, 3, 4, 6, 7, 9, 9, 9, 10], "dummy": range(10)})

f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {"height_ratios": (0.2, 1)})
mean=df[' rating'].mean()
median=df[' rating'].median()
mode=df[' rating'].mode().get_values()[0]

sns.boxplot(df[" rating"], ax=ax_box)
ax_box.axvline(mean, color='r', linestyle='--')
ax_box.axvline(median, color='g', linestyle='-')
ax_box.axvline(mode, color='b', linestyle='-')

sns.distplot(df[" rating"], ax=ax_hist)
ax_hist.axvline(mean, color='r', linestyle='--')
ax_hist.axvline(median, color='g', linestyle='-')
ax_hist.axvline(mode, color='b', linestyle='-')

plt.legend({'Mean':mean,'Median':median,'Mode':mode})

ax_box.set(xlabel='')
plt.show()
Run Code Online (Sandbox Code Playgroud)

样本输出: 在此处输入图片说明

如果您有一堆子图,则可以循环执行此任务:

f, bunch_of_axes = plt.subplots(200)
...
for ax in bunch_of_axes:
    ax.axvline(mean, color='r', linestyle='--')
    ax.axvline(median, color='g', linestyle='-')
    ax.axvline(mode, color='b', linestyle='-')
Run Code Online (Sandbox Code Playgroud)