【问题标题】:Seaborn stacked histogram/barplotSeaborn 堆叠直方图/条形图
【发布时间】:2022-01-16 07:47:15
【问题描述】:

我有一个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'])

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

所以我想要这样的东西:

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

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    只需将总直方图与幸存的 -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()
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 当使用stat="probability" 时,这不会按预期工作,因为它会增加概率。在人们期望 100% 的地方,它实际上导致了 200%。有什么办法可以克服吗?
      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2021-04-06
      相关资源
      最近更新 更多