gpt4 book ai didi

python - Matplotlib : how to label points individually?

转载 作者:太空狗 更新时间:2023-10-30 02:31:16 25 4
gpt4 key购买 nike

使用 maptplotlib,我使用 scatter 方法绘制了一些点(参见下面的代码)。我想单独标记每个点。

此代码将用 labels 数组标记每个点,但我希望我的第一个点用 labels[0] 标记,第二个点用 labels[1] 等等。

import numpy as np; import matplotlib.pyplot as plt
y = np.arange(10) # points to plot
labels = np.arange(10) # labels of the points
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.scatter(x=np.arange(10), y=y, label=labels, picker=3)

有什么办法吗?顺便说一句,有什么方法可以遍历 ax 中的点吗? ax.get_children() 方法产生了我不理解的数据。

谢谢!

最佳答案

假设您没有绘制很多散点,您可以为每个点做一个散点:

import numpy as np; import matplotlib.pyplot as plt
y = np.arange(10) # points to plot
x=np.arange(10)
labels = np.arange(10) # labels of the points
fig, ax = plt.subplots(nrows=1, ncols=1)
for x_,y_,label in zip(x,y,labels):
ax.scatter([x_], [y_], label=label, picker=3)

如果您正在绘制数千或数万个点,这将开始滞后,但如果它只是几个,那就没问题了。

要回答问题的第二部分,ax.get_children() 返回组成这些轴的对象列表,例如:

[<matplotlib.axis.XAxis at 0x103acc410>,
<matplotlib.axis.YAxis at 0x103acddd0>,
<matplotlib.collections.PathCollection at 0x10308ba10>, #<--- this is a set of scatter points
<matplotlib.text.Text at 0x103082d50>,
<matplotlib.patches.Rectangle at 0x103082dd0>,
<matplotlib.spines.Spine at 0x103acc2d0>,
<matplotlib.spines.Spine at 0x103ac9f90>,
<matplotlib.spines.Spine at 0x103acc150>,
<matplotlib.spines.Spine at 0x103ac9dd0>]

如果您只是想获得轴上的散点集,最简单的方法是通过 ax.collections。这是一个列表,其中包含绘制在轴上的所有集合实例(散点属于PathCollection)。

In [9]: ax.collections
Out[9]: [<matplotlib.collections.PathCollection at 0x10308ba10>]

如果您为每个点绘制了一个单独的散点图,则遍历这些点非常简单:

# iterate over points and turn them all red
for point in ax.collections:
point.set_facecolor("red")

关于python - Matplotlib : how to label points individually?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23115287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com