2013-07-09 49 views
0

我有三個列表,一個包含一組名爲「Atype」的符號(字符),第二個包含一組數字,每個對應於「AType」中元素的位置+1,另一個包含一組名爲「XYcoord」的座標(x,y)。我想在圖中註解AType的字符,將AType的每個元素放在XYCoord中相應(x,y)對指示的位置(在圖上)。這沒有問題,但是我想在兩對點之間的距離小於值「BMax」時在字母之間畫一條連線。
到目前爲止,這是我所:Matplotlib,如果條件滿足,如何連接線條註釋?

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。我以前定義放置一個if語句地方,例如返回點「dist_betwn_points(X1,Y1,X2,Y2)」,所以,我知道之間的距離的函數:

if dist_betwn_points(x1, y1, x2, y2) < BMax: 

會有所幫助,但我已盡力有幾種方式,並且在定義「ax.annate(...)」部分時未能成功地在字母之間畫線。 感謝您的幫助!

回答

2

在這裏你有一個例子。我希望它能幫助你。

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

+0

非常感謝你,它確實幫助了我很多,今天終於我解決我的問題,這是一個很好的例子,我做了一些更改,調整到我的特殊需求,但它指出我在正確的方向。再次感謝! – jealopez