我在尝试使用 Matplotlib 显示 DataFrame 中的数据时遇到了以下问题。这个想法是建立一个线性图,其中 Y 轴是每个玩家的得分平均值,X 轴是执行的射击次数。我已将聚合函数应用于 DataFrame 中的数据,但生成的图表看起来并不像我预期的那样。 这是我到目前为止所做的:
数据框
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)
最佳答案
IIUC,你需要这样的东西:
In [52]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).plot()
Out[52]: <matplotlib.axes._subplots.AxesSubplot at 0xb41e710>
对应数据:
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
更新:
I need just a single line plot for displaying the dependency of mean score of a gamer (Y-axis) on the number of shots(X-axis)
In [90]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).set_index('Shots').plot()
Out[90]: <matplotlib.axes._subplots.AxesSubplot at 0xbe749b0>
更新2:
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>]
关于python - Matplotlib 图形以奇怪的方式显示聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629694/