pandas 数据透视表到条形图保存层次结构 [英] Pandas pivot table to Bar Chart Preserving Hierarchy

查看:125
本文介绍了 pandas 数据透视表到条形图保存层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数据透视表:

df=pd.DataFrame({'A':['a','a','a','a','a','b','b','b','b'],
                 'B':['x','y','z','x','y','z','x','y','z'],
                 'C':['a','b','a','b','a','b','a','b','a'],
                 'D':[7,5,3,4,1,6,5,3,1]})
table = pd.pivot_table(df, index=['A', 'B','C'],aggfunc='sum')
table

            D
A   B   C   
a   x   a   7
        b   4
    y   a   1
        b   5
    z   a   3
b   x   a   5
    y   b   3
    z   a   1
        b   6

我想创建一个水平条形图,该条形图保留索引的层次结构.

I'd like to create a horizontal bar chart which preserves the hierarchical layout of the indices.

当前,如果我这样做:

%matplotlib inline
a=table.plot(kind='barh')
a.show()

我明白了:

但是我真正想要的是这样的东西:

But what I really want is something like this:

推荐答案

它可以保留层次结构,但是它与您绘制的图形并不完全相同:

well it preserves hierarchy, but it's not exactly what you've plotted as your desired graph:

orig_index = table.index

idx = (a.apply(lambda row: '{} {} {}'.format(
                    row['a'] if a.shift(1).ix[row.name, 'a'] != row['a'] else ' ',
                    row['b'] if a.shift(1).ix[row.name, 'b'] != row['b'] else ' ',
                    row['c']), axis=1)
)

table.index = idx[::-1]

table.plot.barh()

这篇关于 pandas 数据透视表到条形图保存层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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