如何向每个点添加标签

2024-05-12 19:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我想向各个点添加标签,如下所示:

Matplotlib scatter plot with different text at each data point

我想插入标签的代码如下(https://mplsoccer.readthedocs.io/en/latest/gallery/plots/plot_scatter.html#sphx-glr-gallery-plots-plot-scatter-py):

from mplsoccer.pitch import Pitch
import matplotlib.pyplot as plt
plt.style.use('ggplot')

pitch = Pitch(figsize=(10, 8))
fig, ax = pitch.draw()
sc = pitch.scatter([70, 50, 20, 60, 90], [60, 50, 20, 10, 30],
                   c=['red', 'blue', 'green', 'yellow', 'orange'],
                   s=200, label='scatter', ax=ax)

n = ['21:46','28:52','19:05','82:25'] # Labels for each point

leg = ax.legend(borderpad=1, markerscale=0.5, labelspacing=1.5, loc='upper center', fontsize=15)

如何到达每个点并输入标签


Tags: importplotmatplotlibwithplt标签axgallery
1条回答
网友
1楼 · 发布于 2024-05-12 19:32:24

我编写代码时假设散点图上要标记的标签列表设置为n。但是,每个数据点少了一个标签

from mplsoccer.pitch import Pitch
import matplotlib.pyplot as plt
plt.style.use('ggplot')

pitch = Pitch(figsize=(10, 8))
fig, ax = pitch.draw()
sc = pitch.scatter([70, 50, 20, 60, 90], [60, 50, 20, 10, 30],
                   c=['red', 'blue', 'green', 'yellow', 'orange'],
                   s=200, label='scatter', ax=ax)

n = ['21:46','28:52','19:05','82:25'] # Labels for each point
data = sc.get_offsets()

leg = ax.legend(borderpad=1, markerscale=0.5, labelspacing=1.5, loc='upper center', fontsize=15)

for idx,label in enumerate(n):
    ax.annotate(label, (data[idx][0]+2, data[idx][1]))

enter image description here

相关问题 更多 >