Pandas pivot table to Bar Chart Preserving Hierarchy

。_饼干妹妹 提交于 2019-12-08 13:11:45

问题


Given the following pivot table:

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.

Currently, if I do this:

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

I get this:

But what I really want is something like this:


回答1:


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



来源:https://stackoverflow.com/questions/37173170/pandas-pivot-table-to-bar-chart-preserving-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!