Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - Pandas Plotting with Multi-Index

After performing a groupby.sum() on a DataFrame I'm having some trouble trying to create my intended plot.

grouped dataframe with multi-index

import pandas as pd
import numpy as np

np.random.seed(365)
rows = 100
data = {'Month': np.random.choice(['2014-01', '2014-02', '2014-03', '2014-04'], size=rows),
        'Code': np.random.choice(['A', 'B', 'C'], size=rows),
        'ColA': np.random.randint(5, 125, size=rows),
        'ColB': np.random.randint(0, 51, size=rows),}
df = pd.DataFrame(data)

     Month Code  ColA  ColB
0  2014-03    C    59    47
1  2014-01    A    24     9
2  2014-02    C    77    50

dfg = df.groupby(['Code', 'Month']).sum()

              ColA  ColB
Code Month              
A    2014-01   124   102
     2014-02   398   282
     2014-03   474   198
     2014-04   830   237
B    2014-01   477   300
     2014-02   591   167
     2014-03   522   192
     2014-04   367   169
C    2014-01   412   180
     2014-02   275   205
     2014-03   795   291
     2014-04   901   309

How can I create a subplot (kind='bar') for each Code, where the x-axis is the Month and the bars are ColA and ColB?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the unstack(level) method to work perfectly, which has the added benefit of not needing a priori knowledge about how many Codes there are.

ax = dfg.unstack(level=0).plot(kind='bar', subplots=True, rot=0, figsize=(9, 7), layout=(2, 3))
plt.tight_layout()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...