簡體   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