【问题标题】:Seaborn plot displot with hue and dual y-scale (twinx)Seaborn plot displot with hue 和双 y 尺度 (twinx)
【发布时间】:2021-11-29 10:54:23
【问题描述】:

我正在尝试绘制 ML 模型的预测输出,目标有 1,0 类和分数。由于数据集不平衡,所以很少有 1。

当我在色调参数中使用 Target 绘制一个简单的分布图时,该图对于描述 1 是无用的

sns.set_theme()
sns.set_palette(sns.color_palette('rocket', 3))
sns.displot(df, x='Score', hue='Target', bins=30, linewidth=0, height=5, kde=True, aspect=1.6)
plt.show()

我想在同一个图中更改 1 的比例,并在右侧使用 twinx 更改第二个 y 比例。

我尝试了以下代码,可能会解决 2 个图的问题,但 我只需要一个图。我无法使用 twinx。

g = sns.displot(df, x='Score', col='Target', bins=30, linewidth=0, height=5, kde=True, aspect=1.6, facet_kws={'sharey': False, 'sharex': False})
g.axes[0,1].set_ylim(0,400)
plt.show()

g = sns.FacetGrid(df, hue='Target')
g = g.map(sns.displot, 'Score', bins=30, linewidth=0, height=3, kde=True, aspect=1.6)

一个可重复的例子可能是泰坦尼克数据集:

df_ = sns.load_dataset('titanic')
sns.displot(df_, x='fare', hue='survived', bins=30, linewidth=0, height=5, kde=True, aspect=1.6)

g = sns.displot(df_, x='fare', col='survived', bins=30, linewidth=0, height=5, kde=True, aspect=1.6, facet_kws={'sharey': False, 'sharex': False})
g.axes[0,1].set_ylim(0,150)
plt.show()

【问题讨论】:

标签: python seaborn histogram distribution


【解决方案1】:

要比较具有不同观察次数的分布形状,您可以通过设置stat="density" 对其进行归一化。默认情况下,这会使用相同的分母对每个分布进行归一化,但您可以通过设置 common_norm=False 独立地对每个分布进行归一化:

sns.displot(
    titanic, x='fare', hue='survived',
    bins=30, linewidth=0, kde=True,
    stat="density", common_norm=False,
    height=5, aspect=1.6
)

两个分布的峰值不在同一个 y 值上,但这是数据的一个真实特征:幸存者群体分布在更广泛的票价范围内,并且在较低端的聚集度较低。拥有两个独立的 y 轴并缩放它们以使每个分布的峰值高度相等会产生误导。

【讨论】:

  • 谢谢!我刚开始使用 sns,你的解决方案很有意义,这不是我最初想要的,但它是一种更好的方法。
【解决方案2】:

我不确定,但你在找这个吗?

import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
df_ = sns.load_dataset('titanic')
sns.histplot(df_[df_['survived']==1]['fare'], bins=30, linewidth=0, kde=True, color='red')
ax2 = plt.twinx()
sns.histplot(df_[df_['survived']==0]['fare'], bins=30, linewidth=0, kde=True, ax=ax2, color='blue')

【讨论】:

  • 这正是我想要的,坦克很多!我开始用 sns 绘图,但我不知道 histplot 解决了这个问题。
  • 乐于助人。祝你有美好的一天
猜你喜欢
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2021-10-22
  • 2022-08-22
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多