gpt4 book ai didi

python - 平均中值模式线仅显示在 seaborn 的最后一张图中

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:03 24 4
gpt4 key购买 nike

我试图在两个图中显示 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='')

最佳答案

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().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()

示例输出: 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='-')

如果您没有可用的轴对象(例如,您使用 pandas 绘图或类似工具创建了图形),您可以通过以下方式解决此问题:

....
bunch_of_axes = plt.gcf().axes
for ax in bunch_of_axes:
ax.axvline(mean, color='r', linestyle='--', label="Mean")
....

2021 年更新:我更改了 pandas 代码,因为 get_values() 现已弃用。Seaborn 也弃用了 distplot .备选方案是 displot ,没有 ax 参数的图形级函数,或 histplot它的行为与 distplot 略有不同。

我现在已经在另一个线程中总结了 how to emulate the old distplot behavior with histplot.

关于python - 平均中值模式线仅显示在 seaborn 的最后一张图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51417483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com