平均中值模式线仅显示在 seaborn 的最后一张图中 [英] Mean Median Mode lines showing only in last graph in seaborn

查看:37
本文介绍了平均中值模式线仅显示在 seaborn 的最后一张图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在两个图中显示 meanmedianmode 行,但它们仅在最后一个图中可见:

I am trying to show the mean, median, and mode lines in two graphs but they are only visible in the last graph:

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

推荐答案

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

The command plt uses the current axis, not all defined axes. To plot something on a specific axis, you have to tell matplotlib/seaborn, which axis you mean:

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().values[0]

sns.boxplot(data=df, x=" 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.histplot(data=df, x=" rating", ax=ax_hist, kde=True)
ax_hist.axvline(mean, color='r', linestyle='--', label="Mean")
ax_hist.axvline(median, color='g', linestyle='-', label="Median")
ax_hist.axvline(mode, color='b', linestyle='-', label="Mode")

ax_hist.legend()

ax_box.set(xlabel='')
plt.show()

样本输出:

如果你有一大堆子图,你可以用一个循环来处理这个任务:

If you have a whole bunch of subplots, you approach this task with a loop:

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

2021 年更新:我更改了 Pandas 代码,因为 get_values() 现在已弃用.Seaborn 还弃用了 distplot.替代方案是 displot,一个没有斧头参数或 histplot 的行为与 distplot 略有不同.

Update 2021: I changed the pandas code because get_values() is now deprecated. Seaborn has also deprecated distplot. The alternatives are displot, a figure-level function with no ax parameter, or histplot which behaves slightly different from distplot.

我现在在另一个线程中总结了如何模拟旧的 distplot 行为使用 histplot.

I have summarized now in another thread how to emulate the old distplot behavior with histplot.

这篇关于平均中值模式线仅显示在 seaborn 的最后一张图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆