如何根据 pandas 列注解散点图中的点? [英] How to annotate points in a scatterplot based on a pandas column?

查看:42
本文介绍了如何根据 pandas 列注解散点图中的点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望'Age'作为x轴,'Pos'作为y轴,标签为'Player'名称。但由于某些原因,无法对这些点进行标注。

编码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import adjustText as at



data = pd.read_excel("path to  the file")
fig, ax = plt.subplots()
fig.set_size_inches(7,3)

df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])

df.plot.scatter(x='Age',
                y='Pos',
                c='DarkBlue', xticks=([15,20,25,30,35,40]))

y = df.Player
texts = []
for i, txt in enumerate(y):
    plt.text()
at.adjust_text(texts, arrowprops=dict(arrowstyle="simple, head_width=0.25, tail_width=0.05", color='black', lw=0.5, alpha=0.5))

plt.show()

数据汇总:

df.head()

             Player Pos  Age
0  Thibaut Courtois  GK   28
1     Karim Benzema  FW   32
2      Sergio Ramos  DF   34
3    Raphael Varane  DF   27
4       Luka Modric  MF   35

错误:

ConversionError:无法将值转换为轴单位:‘gk’

这是到目前为止的情况;无法标记这些点:

编辑: 这就是我想要的,但最重要的是:

另外,有人能帮我重新排序yAxis上的标签吗? 就像,我想要FW,MF,DF,GK作为我的顺序,但情节是MF,DF,FW,GK。

谢谢。

推荐答案

描述了类似的解决方案here。实际上,您希望为散点图中的点添加批注。

我已经删除了您的代码。注意,您需要使用matplotlib(而不是pandas):df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])绘制数据。这样,您就可以使用annotation()-方法。

import matplotlib.pyplot as plt
import pandas as pd

# build data
data = [
['Thibaut Courtois', 'GK', 28],
['Karim Benzema', 'FW', 32],
['Sergio Ramos','DF', 34],
['Raphael Varane', 'DF', 27],
['Luka Modric', 'MF', 35],
]
# create pandas DataFrame
df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])


# open figure + axis
fig, ax = plt.subplots()
# plot
ax.scatter(x=df['Age'],y=df['Pos'],c='DarkBlue')
# set labels
ax.set_xlabel('Age')
ax.set_ylabel('Pos')

# annotate points in axis
for idx, row in df.iterrows():
    ax.annotate(row['Player'], (row['Age'], row['Pos']) )
# force matplotlib to draw the graph
plt.show()

以下是您将获得的输出:

这篇关于如何根据 pandas 列注解散点图中的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆