python - Matplotlib 图形以奇怪的方式显示聚合函数

标签 python pandas matplotlib dataframe

我在尝试使用 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)

enter image description here

最佳答案

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

更新:

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>

enter image description here

更新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>]

enter image description here

关于python - Matplotlib 图形以奇怪的方式显示聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629694/

相关文章:

c++ - 在 C 或 C++ 中创建 python 库

python - Selenium Chromedriver 错误代码 : 3221225477

python - 如何将包含短语的 str 列表转换为 int 列表?

python - 按钮在第二个(嵌套)图中不起作用

python - 在没有任何内置 e​​val 函数或外部库的情况下用 python 解决数学问题

python - scikit-learn 的逻辑回归在打印输出时给出关键错误

python - 检查 Pandas 的数据框列中是否包含某个值

python - 矢量化 : Limit the increase in value between two subsequent numbers in Series (or list/array/whatever)

python - 在 seaborn 的分类图上使用不规则间隔的非分类轴

python - 当带有子图的图形从 python3.2 中的 matplotlib 保存为 pdf 时创建的空 pdf