问题
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