7

我有一个pandas.DataFrame,我想绘制一个基于两列的图表:Age(int),Survived(int -01)。现在我有这样的事情:

在此处输入图像描述

这是我使用的代码:

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

所以这显示在两个子图上。这很好,但是对于特定的年龄范围,很难看到列中记录的数量0与列1中的记录数量之间的差异。Survived

所以我想要这样的东西:

在此处输入图像描述

在这种情况下,您可以看到这种差异。有什么方法可以做到seaborn(因为我可以很容易地操作pandas.DataFrame)?matplotlib如果可能的话,我不想用香草

4

2 回答 2

4

只需将总直方图与幸存的 -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()
于 2018-12-22T21:52:14.547 回答
4

从 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")

在此处输入图像描述

于 2020-10-15T20:42:38.310 回答