我是Python的新手,目前我还在为注释情节而苦苦挣扎。我来自R,所以我习惯了用最少的代码轻松地注释散点图。
代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mplurl = ('https://fbref.com/en/share/nXtrf')
df = pd.read_html(url)[0]
df = df[['Unnamed: 1_level_0', 'Unnamed: 2_level_0', 'Play', 'Perf']].copy()
df.columns = df.columns.droplevel()
df = df[['Player','Squad','Min','SoTA','Saves']]
df = df.drop([25])
df['Min'] = pd.to_numeric(df['Min'])
df['SoTA'] = pd.to_numeric(df['SoTA'])
df['Saves'] = pd.to_numeric(df['Saves'])
df['Min'] = df[df['Min'] > 1600]['Min']
df = df.dropna()df.plot(x = 'Saves', y = 'SoTA', kind = "scatter")我已经尝试了许多方法来注释这个情节。我想要点注释与相应的数据从‘球员’列。
我试着使用了一个label_point函数,这个函数是我在尝试寻找解决方法时发现的,但在我尝试的大多数方法中,我都得到了关键错误0。
任何帮助都是很棒的。谢谢。
发布于 2021-02-01 01:16:31
您可以循环遍历每个条目的列和add a text。请注意,您需要保存df.plot(...)返回的ax。
ax = df.plot(x='Saves', y='SoTA', kind="scatter")
for x, y, player in zip(df['Saves'], df['SoTA'], df['Player']):
ax.text(x, y, f'{player}', ha='left', va='bottom')
xmin, xmax = ax.get_xlim()
ax.set_xlim(xmin, xmax + 0.15 * (xmax - xmin)) # some more margin to fit the texts

另一种方法是使用mplcursors库在悬停时(或单击后)显示注释:
import mplcursors
mplcursors.cursor(hover=True)

https://stackoverflow.com/questions/65981684
复制相似问题