【问题标题】:How to show label names in pandas groupby histogram plot如何在熊猫 groupby 直方图中显示标签名称
【发布时间】:2019-10-08 14:13:30
【问题描述】:

我可以使用 pandas 在一个图中绘制多个直方图,但缺少一些东西:

  1. 如何给标签。
  2. 我只能绘制一个图形,如何将其更改为 layout=(3,1) 或其他内容。
  3. 另外,在图 1 中,所有的 bin 都填充了纯色,很难知道哪个是哪个,如何填充不同的标记(例如十字、斜线等)?

这是 MWE:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

df.groupby('species')['sepal_length'].hist(alpha=0.7,label='species')
plt.legend()

输出:

要更改布局,我可以通过关键字使用,但不能给它们颜色

如何赋予不同的颜色?

df.hist('sepal_length',by='species',layout=(3,1))
plt.tight_layout()

提供:

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以解析为groupby:

    fig,ax = plt.subplots()
    
    hatches = ('\\', '//', '..')         # fill pattern
    for (i, d),hatch in zip(df.groupby('species'), hatches):
        d['sepal_length'].hist(alpha=0.7, ax=ax, label=i, hatch=hatch)
    
    ax.legend()
    

    输出:

    【讨论】:

      【解决方案2】:

      在 pandas 1.1.0 版中,您只需将 legend 关键字设置为 true。

      import numpy as np
      import pandas as pd
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      df = sns.load_dataset('iris')
      
      df.groupby('species')['sepal_length'].hist(alpha=0.7, legend = True)
      

      output image

      【讨论】:

        【解决方案3】:

        代码更多,但使用纯 matplotlib 将始终让您更好地控制绘图。对于您的第二种情况:

        import matplotlib.pyplot as plt
        import numpy as np
        from itertools import zip_longest
        
        # Dictionary of color for each species
        color_d = dict(zip_longest(df.species.unique(), 
                                   plt.rcParams['axes.prop_cycle'].by_key()['color']))
        
        # Use the same bins for each
        xmin = df.sepal_length.min()
        xmax = df.sepal_length.max()
        bins = np.linspace(xmin, xmax, 20)
        
        # Set up correct number of subplots, space them out. 
        fig, ax = plt.subplots(nrows=df.species.nunique(), figsize=(4,8))
        plt.subplots_adjust(hspace=0.4)
        
        for i, (lab, gp) in enumerate(df.groupby('species')):
            ax[i].hist(gp.sepal_length, ec='k', bins=bins, color=color_d[lab])
            ax[i].set_title(lab)
        
            # same xlim for each so we can see differences
            ax[i].set_xlim(xmin, xmax)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-07
          • 2021-12-12
          • 2020-03-30
          • 2016-12-16
          • 1970-01-01
          • 2019-06-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多