【问题标题】:Plotting seaborn histogram from each column in different subplots (facetgrid)从不同子图中的每一列绘制 seaborn 直方图(facetgrid)
【发布时间】:2019-07-30 19:41:36
【问题描述】:

我的结构遵循 pandas DataFrame:

n    X              Y          Z
0   1.000000    1.000000    1.014925    
1   1.000000    1.000000    1.000000    

我想从每列创建 M 个单独的子图(直方图)。一个直方图来自 X,一个来自 Y,最后一个来自 Z。

我希望它有单独的情节。我正在研究https://seaborn.pydata.org/generated/seaborn.FacetGrid.html,但我不明白如何从我的数据中绘制它的语法/逻辑。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    使用seaborn.FacetGrid 可能需要您重组数据。

    让我们看一个例子:

    np.random.seed(0)
    df = pd.DataFrame(np.random.randn(1000, 3), columns=['X', 'Y', 'Z'])
    print(df.head(10))
    
              X         Y         Z
    0  1.764052  0.400157  0.978738
    1  2.240893  1.867558 -0.977278
    2  0.950088 -0.151357 -0.103219
    3  0.410599  0.144044  1.454274
    4  0.761038  0.121675  0.443863
    5  0.333674  1.494079 -0.205158
    6  0.313068 -0.854096 -2.552990
    7  0.653619  0.864436 -0.742165
    8  2.269755 -1.454366  0.045759
    9 -0.187184  1.532779  1.469359
    
    df_melted = df.melt(var_name='column')
    
    print(df_melted.head(10))
    
      column     value
    0      X  1.764052
    1      X  2.240893
    2      X  0.950088
    3      X  0.410599
    4      X  0.761038
    5      X  0.333674
    6      X  0.313068
    7      X  0.653619
    8      X  2.269755
    9      X -0.187184
    
    
    g = sns.FacetGrid(df_melted, row='column')
    g.map(plt.hist, 'value')
    

    [出]

    【讨论】:

      【解决方案2】:

      您可以使用 pandas 数据框的内置 plot 方法和选项 subplots=True 按列绘制

      from io import StringIO
      import pandas as pd
      import matplotlib.pyplot as plt
      plt.style.use('seaborn')
      
      # Here I read your example data in
      df = pd.read_fwf(StringIO("""
          X              Y          Z
      0   1.000000    1.000000    1.014925    
      1   1.000000    1.000000    1.000000
      """), header=1, index_col=0)
      
      # Plotting as desired
      df.plot.hist(subplots=True, legend=False)
      

      df.plot 需要许多其他参数来让您轻松更改情节,例如

      df.plot.hist(subplots=True, legend=True, layout=(1, 3))
      

      【讨论】:

      • 两个答案都是正确的,我接受你的答案,因为你是第一个回答这个问题的人。
      【解决方案3】:

      sns.pairplot(your_df) 会这样做,但是它还会向您显示每列的成对散点图,所以是的,它会比您需要的更多?在进行探索性数据分析时很好。您还可以通过在通话中添加corner=True 来使其更简洁。

      或者类似的东西:

      # Update as needed
      n_rows=1
      n_cols=3
      
      # Create the subplots
      fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=(10, 10))
      for i, column in enumerate(df):
          sns.histplot(df, ax=axes[i // n_cols, i % n_cols]).set_title(column)
      

      https://seaborn.pydata.org/generated/seaborn.pairplot.htma

      【讨论】:

        猜你喜欢
        • 2018-12-09
        • 1970-01-01
        • 2016-11-09
        • 2021-04-17
        • 1970-01-01
        • 2015-06-17
        • 2018-08-26
        • 1970-01-01
        • 2022-10-12
        相关资源
        最近更新 更多