【问题标题】:How to add legends and title to grouped histograms generated by Pandas如何为 Pandas 生成的分组直方图添加图例和标题
【发布时间】:2015-09-04 07:27:09
【问题描述】:

我正在尝试绘制由另一个属性分组的多个属性的直方图,所有这些属性都在一个数据框中。

question 的帮助下,我可以为情节设置标题。有没有一种简单的方法可以为每个子图打开图例。

这是我的代码

import numpy as np
from numpy.random import randn,randint
import pandas as pd
from pandas import DataFrame
import pylab as pl

x=DataFrame(randn(100).reshape(20,5),columns=list('abcde'))
x['new']=pd.Series(randint(0,3,10))
x.hist(by='new')
pl.suptitle('hist by new')

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    你可以几乎通过做得到你想要的:

    g.plot(kind='bar')
    

    但它会为每组生成一个图(并且没有以组命名图,因此在 IMO 中有点没用。)

    这是一个看起来相当漂亮的东西,但确实涉及很多“手动”matplotlib 工作,每个人都想避免,但没有人可以:

    import numpy.random as rnd
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    x = pd.DataFrame(rnd.randn(100).reshape(20, 5), columns=list('abcde'))
    
    group_col = 'groups'
    groups = ['foo', 'bar', 'baz']
    x[group_col] = pd.Series(rnd.choice(groups, len(x)))
    
    g = x.groupby(group_col)
    num_groups = g.ngroups
    
    fig, axes = plt.subplots(num_groups)
    for i, (k, group) in enumerate(g):
        ax = axes[i]
        ax.set_title(k)
        group = group[[c for c in group.columns if c != group_col]]
        num_columns = len(group.columns)
        colours = cm.Spectral([float(x) / num_columns for x in range(num_columns)])
        ax.hist(group.values, 5, histtype='bar',
                label=list(group.columns), color=colours,
                linewidth=1, edgecolor='white')
        ax.legend()
    
    plt.show()
    

    我认为这可以满足您的需求:


    更新 作为对 cme​​ts 的回应(因为这个答案已经有几年的历史了),我试图将这个答案剥离到最简单的部分。 可能现在有一种方法可以标记groupby 对象的图,但我不知道。

    这是最简单的方法:

    axes = g.plot(kind='hist')
    for i, (groupname, group) in enumerate(g):
        axes[i].set_title(groupname)
    

    【讨论】:

    • 太棒了。因此,如果不使用真正的 matplotlib api,就无法完成这项工作。这应该是熊猫的限制,对吗?
    • 我在寻找直方图?如何将条形图转换为直方图?
    • 我已经更新了使用直方图的答案(并使结果更漂亮。)
    • @LondonRob A. 我不是大熊猫用户,但我用它来管理成绩簿,我需要 vumaasha 的同样帮助。似乎现在,截至 pandas 0.20.3,仍然没有实现这样的自动功能。你知道碰巧知道这是否正确吗?
    猜你喜欢
    • 2021-12-05
    • 2013-02-07
    • 2015-12-17
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2016-08-01
    相关资源
    最近更新 更多