Matplotlib,如果满足条件,如何与行注释连接?

2024-06-16 10:49:18 发布

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

我有三个列表,一个包含一组名为“Atype”的符号(字符),第二个列表“el”包含一组数字,每个对应于“Atype”中元素的位置+1,另一个列表包含一组名为“XYcoord”的坐标(x,y)。我想在绘图中注释AType的字符,将AType的每个元素放在XYCoord中对应的(x,y)对所指示的位置(在绘图上)。这不是问题,但我想在两点之间的距离小于值“BMax”时在字母之间画一条连接线。
到目前为止,我得到的是:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
for x in range(1, NCenter+1): # NCenter is the number of elements in AType and XYcoord.
    xposcoord, yposcoord = XYcoord[x-1][0]/100.0, XYcoord[x-1][1]/100.0
    ax.annotate('%s' % (AType[el[x-1]-1]), xy=(xposcoord, yposcoord), 
                xycoords='axes fraction')

plt.show()

我得到一个情节是: Plot showing letters with no connections 现在,我想在字母之间画一条连接线,如果它们之间的距离小于BMax。我以前定义了一个函数,它返回点之间的距离“dist_betwn_points(x1,y1,x2,y2)”,因此,我通过在某处放置if语句来知道,例如:

^{pr2}$

会有帮助,但我尝试了几种方法,但都没有成功地定义“ax.注释(…)“部分,在字母之间画线。 谢谢你的帮助!在


Tags: in元素绘图距离列表字母figplt
1条回答
网友
1楼 · 发布于 2024-06-16 10:49:18

这里有一个例子。我希望这对你有帮助。在

import numpy as np
import matplotlib.pyplot as plt

def make_lines(x,y):
    ax = plt.gca()
    for j in range(len(x)):
        for i in range(j,len(x)):
            distance = np.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)
            if distance < 0.2 and distance > 0:
                ax.annotate('', xy=(x[i], y[i]), xytext=(x[j], y[j]),
                            arrowprops=dict(facecolor='black', 
                                            shrink=0.1,
                                            width=1),
                            textcoords='data',
                            )
n = 30
x,y = np.random.rand(n), np.random.rand(n)

fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)

make_lines(x,y)

ax.plot(x,y,'ro',markersize=10)
plt.show()

enter image description here

相关问题 更多 >