Seaborn堆叠直方图/条形图

14

我有一个 pandas.DataFrame,我想根据两列数据绘制图表: Age (整数类型), Survived (整数类型 - 01)。现在我有类似这样的东西:

enter image description here

这是我使用的代码:

class DataAnalyzer:

    def _facet_grid(self, func, x: List[str], col: str = None, row: str = None) -> None:
        g = sns.FacetGrid(self.train_data, col=col, row=row)
        if func == sns.barplot:
            g.map(func, *x, ci=None)
        else:
            g.map(func, *x)
        g.add_legend()
        plt.show()

    def analyze(self) -> None:
        # Check if survival rate is connected with Age
        self._facet_grid(plt.hist, col='Survived', x=['Age'])

所以这个图表显示在两个子图上。这很好,但是在特定年龄范围内,很难看出具有01Survived列中记录数量之间的差异。

因此,我希望得到类似于以下内容:

enter image description here

在这种情况下,您可以看到这种差异。是否有一种方法可以在seaborn上进行操作(因为我可以轻松地在pandas.DataFrame上进行操作)?如果可能的话,我不想使用vanilla matplotlib。
2个回答

14

从seaborn 0.11.0开始,您可以这样做

# stacked histogram
import matplotlib.pyplot as plt
f = plt.figure(figsize=(7,5))
ax = f.add_subplot(1,1,1)

# mock your data frame
import pandas as pd
import numpy as np
_df = pd.DataFrame({
    "age":np.random.normal(30,30,1000),
    "survived":np.random.randint(0,2,1000)
})

# plot
import seaborn as sns
sns.histplot(data=_df, ax=ax, stat="count", multiple="stack",
             x="age", kde=False,
             palette="pastel", hue="survived",
             element="bars", legend=True)
ax.set_title("Seaborn Stacked Histogram")
ax.set_xlabel("Age")
ax.set_ylabel("Count")

在这里输入图片描述


1
当使用 stat="probability" 时,它并不像预期的那样工作,因为它会将概率相加。在预期应该是100%的地方,实际上结果是200%。有什么方法可以克服这个问题吗? - Anonymous

5

只需将总直方图与幸存-0叠加即可。如果没有数据帧的精确形式,很难给出确切的功能,但这里有一个使用seaborn示例数据集的基本示例。

import matplotlib.pyplot as plt 
import seaborn as sns 
tips = sns.load_dataset("tips") 
sns.distplot(tips.total_bill, color="gold", kde=False, hist_kws={"alpha": 1}) 
sns.distplot(tips[tips.sex == "Female"].total_bill, color="blue", kde=False, hist_kws={"alpha":1}) 
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接