繁体   English   中英

如何使用 zip 分散 plot 中的 label 点和注释

[英]How to label points in a scatter plot using zip and annotate

我正在尝试使用 zip 并进行注释,以便将向量表中的标签添加到使用tlab制作的matplotlib中。 相反,在尝试将标签添加到 plot 时出现错误

TypeError:传递给列表的格式字符串不受支持。 格式

如何使用此方法获得 plot 上的积分?

代码:

import matplotlib.pyplot as plt
import numpy as np

plt.clf()

# using some dummy data for this example
xs = np.arange(0,20,1)
ys = np.random.normal(loc=3, scale=0.4, size=20)
tlab =  ['k=' + str(s) for s in range(20)] # label vector
 
# 'bo' means blue color, round points
plt.plot(xs,ys,'bo')

for x,y in zip(xs,ys):

    label = "{:.2f}".format(tlab)

    plt.annotate(label, # this is the text
                 (x,y), # this is the point to label
                 textcoords="offset points", # how to position the text
                 xytext=(0,10), # distance from text to points (x,y)
                 ha='center')

在此处输入图像描述

在我原来的问题中,我在向量中有标签,它们没有引用坐标。 我知道我也许可以创建一个循环通过 label 向量的计数器,但我想找到最有效的方法来编写它。

您可以只使用带有xsys的标签 zip 。 但是,我不确定您为什么要创建字符串列表并稍后尝试对其进行格式化。 在以下解决方案中,您还可以像在示例中一样创建格式化字符串,然后直接将其用作 label。

tlab = range(0, 20)  # label vector
# tlab =  ['k=' + str(s) for s in range(20)] # label vector

# 'bo-' means blue color, round points, solid lines
plt.plot(xs, ys, 'bo')

for x, y, lab in zip(xs, ys, tlab):
    label = '{:.2f}'.format(lab)

    plt.annotate(label,  # this is the text (put lab here to use tlab as string)
                 (x, y),  # this is the point to label
                 textcoords="offset points",  # how to position the text
                 xytext=(0, 10),  # distance from text to points (x,y)
                 ha='center')

绘制这个:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM