如何根据 pandas 列注释散点图中的点

2024-04-27

Wanted 'Age'作为 x 轴,'Pos'作为 y 轴,标签为'Player'名字。但由于某种原因,无法对点进行标记。

Code:

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

Error :

ConversionError:无法将值转换为轴单位:“GK”

This is the plot so far; not able to label these points: This is the plot so far; not able to label these points

EDIT: This is what I wanted but of all points: This is what I wanted, but of all points

另外,任何人都可以帮我重新排序 yaxis 上的标签吗? 就像,我想要 FW,MF,DF,GK 作为我的顺序,但情节是在 MF,DF,FW,GK 中。

Thanks.


描述了类似的解决方案here https://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point。本质上,您想要注释散点图中的点。

我已经剥离了你的代码。请注意,您需要使用以下命令绘制数据matplotlib(并且不与pandas): df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])。通过这种方式,您可以使用annotation()-method.

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()

这是您将得到的输出:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据 pandas 列注释散点图中的点 的相关文章

随机推荐