2017-10-08 62 views
1

我試圖用Matplotlib從DataFrame顯示數據時遇到了以下問題。這個想法是建立一個線性圖,其中Y軸是每個玩家得分的平均值,而X軸是執行的擊球次數。我已將聚合函數應用於DataFrame中的數據,但生成的圖形看起來不像我預期的那樣。 以下是我迄今所做的:Matplotlib圖以奇怪的方式顯示聚合函數

數據幀

Score  Gamer  Shots 
a 5.0  gamer1  7 
b 3.0  gamer2  2 
c 2.5  gamer1  8 
d 7.1  gamer3  9 
e 1.8  gamer3  2 
f 2.2  gamer3  1 

情節

plt.title('Plot 1', size=14) 
plt.xlabel('Number of Shots', size=14) 
plt.ylabel('Mean Score', size=14) 
plt.grid(b=True, which='major', color='g', linestyle='-') 
x = df[['gamer','shots']].groupby(['gamer']).count() 
y = df[['gamer','score']].groupby(['gamer']).mean() 
plt.plot(x, y) 

enter image description here

回答

1

IIUC,你需要的東西是這樣的:

In [52]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).plot() 
Out[52]: <matplotlib.axes._subplots.AxesSubplot at 0xb41e710> 

enter image description here

對應的數據:

In [54]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}) 
Out[54]: 
     Score Shots 
Gamer 
gamer1 3.75  2 
gamer2 3.00  1 
gamer3 3.70  3 

UPDATE:

我只需要用於顯示平均 得分一個玩家的所述依賴性的單線圖(Y軸)上拍數(X軸)

In [90]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).set_index('Shots').plot() 
Out[90]: <matplotlib.axes._subplots.AxesSubplot at 0xbe749b0> 

enter image description here

UPDATE2:

In [155]: g = df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).sort_values('Shots') 

In [156]: x,y = g['Shots'], g['Score'] 

In [157]: plt.plot(x, y) 
Out[157]: [<matplotlib.lines.Line2D at 0xbdbf668>] 

enter image description here

+0

好吧,我只需要一個單一的線圖上的加號顯示遊戲玩家的平均得分(Y軸)的依賴性(X軸)。 – samba

+0

@samba,請參閱UPDATE ... – MaxU

+0

當試圖顯示由'df.groupby('Gamer')生成的表格的圖形。agg({'Score':'mean','Shots':'count' })'我想在我的文章中使用mathplotlib設計。那麼我會這樣做:plt.plot(x ='Shots',y ='Score')並獲得一個空的圖。 – samba