如何为 pandas 生成的分组直方图添加图例和标题 [英] How to add legends and title to grouped histograms generated by Pandas

查看:156
本文介绍了如何为 pandas 生成的分组直方图添加图例和标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to plot a histogram of multiple attributes grouped by another attributes, all of them in a dataframe.

借助此问题,我是能够设置剧情的标题.是否有一种简单的方法可以为每个子图打开图例.

with the help of this question, I am able to set title for the plot. Is there an easy way to switch on legend for each subplot.

这是我的代码

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

推荐答案

您可以通过以下方式几乎获得所需的信息:

You can almost get what you want by doing:

g.plot(kind='bar')

但是它每组产生一个图(并且没有以组为名来命名图,因此它有点无用的IMO).

but it produces one plot per group (and doesn't name the plots after the groups so it's a bit useless IMO.)

这里看起来很漂亮,但是确实涉及很多手动" matplotlib工作,每个人都希望避免,但是没有人能做到:

Here's something which looks rather beautiful, but does involve quite a lot of "manual" matplotlib work, which everyone wants to avoid, but no one can:

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()

我想为您提供您想要的:

Which I think gives you what you want:


更新 为了回应评论(并且这个答案已有几年的历史了),我尝试将这个答案简化为最粗略的内容.现在可能有一种 标记groupby对象图的方式,但我不知道.


Update In response to comments (and as this answer is a few years old) I've tried to strip this answer down to its barest bones. There may now be a way of labelling plots of groupby objects but I don't know of it.

这是最简单的方法:

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

这篇关于如何为 pandas 生成的分组直方图添加图例和标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆