使用unstack()进行Pandas Groubpy绘图

时间:2020-07-14 22:32:44

标签: python pandas pandas-groupby

我有以下代码

df = pd.DataFrame({
'type':['john','bill','john','bill','bill','bill','bill','john','john'],
'num':[1006,1004,1006,1004,1006,1006,1006,1004,1004],
'date':[2017,2016,2015,2017,2017,2013,2012,2013,2012],
'pos':[0,0,1,4,0,3,3,8,9],
'force':[5,2,7,10,6,12,4,7,8]})

fig, ax = plt.subplots()

grp=df.sort_values('date').groupby(['type'])

for name, group in grp :
    print(name)
    print(group)
    group.plot(x='date', y='force', label=name)

plt.show()

获得的结果如下:

bill
   type   num  date  pos  force
6  bill  1006  2012    3      4
5  bill  1006  2013    3     12
1  bill  1004  2016    0      2
3  bill  1004  2017    4     10
4  bill  1006  2017    0      6
john
   type   num  date  pos  force
8  john  1004  2012    9      8
7  john  1004  2013    8      7
2  john  1006  2015    1      7
0  john  1006  2017    0      5

[img1_force_Bill] [1] [img2_Force_john] [2]

我如何在每2行中获得4个图:

  • 图1的帐单:line1(x=date , y= force)的{​​{1}} / num(1004)的{​​{1}}

  • 图2的帐单:line2(x=date , y= force)的{​​{1}} / num(1006)的{​​{1}}

  • 约翰的
  • Fig3:line1(x=date , y= pos)的{​​{1}} / num(1004)的{​​{1}}

  • 约翰的
  • Fig4:line2(x=date , y= pos)的{​​{1}} / num(1006)的{​​{1}}

2 个答案:

答案 0 :(得分:0)

让我们尝试一下:

df = pd.DataFrame({
'type':['john','bill','john','bill','bill','bill','bill','john','john'],
'num':[1006,1004,1006,1004,1006,1006,1006,1004,1004],
'date':[2017,2016,2015,2017,2017,2013,2012,2013,2012],
'pos':[0,0,1,4,0,3,3,8,9],
'force':[5,2,7,10,6,12,4,7,8]})

fig, ax = plt.subplots(2,2)
axi=iter(ax.flatten())

grp=df.sort_values('date').groupby(['type'])
for name, group in grp :
#     print(name)
#     print(group)
    group.set_index(['date','num'])['force'].unstack().plot(title=name+' - force', ax=next(axi), legend=False)
    group.set_index(['date','num'])['pos'].unstack().plot(title=name+ ' - pos', ax=next(axi), legend=False)
    
plt.tight_layout()
plt.legend(loc='upper center', bbox_to_anchor=(0, -.5), ncol=2)
plt.show()

输出:

enter image description here


以下每个评论的更新:

dfj = df[df['type'] == 'john']
ax = dfj.set_index(['date','num'])['force'].unstack().plot(title=name+' - force', legend=False)
ax.axhline(y=dfj['force'].max(), color='red', alpha=.8)

图表: enter image description here

答案 1 :(得分:0)

@ Scott Boston ....非常感谢您的帮助。 不幸的是,在将以下代码与大数据结合使用之后,绘制了2条线

for name, group in grp_new:
    axn= group.set_index(['date', 'num'])['pos'].unstack().plot(title= name+' _pos', legend=False)

图看起来像plot2Lines。它们不是连续的图。我试图绘制单线,没关系。