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

时间:2018-07-19 08:06:49

标签: 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='')

2 个答案:

答案 0 :(得分:1)

命令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()

样本输出: enter image description here

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

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='-')

答案 1 :(得分:1)

第一个人(使用jupyter笔记本):

import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.distplot(xgb_errors, kde=True, rug=True); plt.axvline(np.median(xgb_errors),color='b', linestyle='--')