如何在matplotlib中绘制有向线?

时间:2017-12-03 14:49:53

标签: matplotlib

在matplotlib中,使用plt.plot(xs, ys, '-'+marker)从数据点中绘制一条线很容易。这将为您提供一条无向线,您无法通过查看结果图来判断,哪一端对应于数据点数组的开头,哪些对应于数组的末尾。碰巧的是,对于我正在做的事情,能够分辨出哪一端或哪个等效线路的走向非常重要。绘制线条以获得视觉区别的推荐方法是什么?

1 个答案:

答案 0 :(得分:3)

以下是一个选项。它是沿着一条线添加一些箭头。这可以使用FancyArrowPatch来完成。

import numpy as np ; np.random.seed(7)
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch 

class RL(object):
    def __init__(self, n, d, s=0.1):
        a = np.random.randn(n)*s
        a[0] = np.random.rand(1)*np.pi*2
        self.xy = np.random.rand(n,2)*5
        self.xy[1,:] = self.xy[0,:] + np.array([d*np.cos(a[0]),d*np.sin(a[0])])
        for i in range(2,n):
            (x,y), = np.diff(self.xy[i-2:i,:], axis=0)
            na = np.arctan2(y,x)+a[i]
            self.xy[i,:] = self.xy[i-1,:] + np.array([d*np.cos(na),d*np.sin(na)])
        self.x = self.xy[:,0]; self.y = self.xy[:,1]

l1 = RL(1000,0.005)
l2 = RL(1000,0.007)
l3 = RL(1000,0.005)

fig, ax = plt.subplots()
ax.set_aspect("equal")
ax.plot(l1.x, l1.y)
ax.plot(l2.x, l2.y)
ax.plot(l3.x, l3.y)
ax.plot(l1.x[0], l1.y[0], marker="o")

def arrow(x,y,ax,n):
    d = len(x)//(n+1)    
    ind = np.arange(d,len(x),d)
    for i in ind:
        ar = FancyArrowPatch ((x[i-1],y[i-1]),(x[i],y[i]), 
                              arrowstyle='->', mutation_scale=20)
        ax.add_patch(ar)

arrow(l1.x,l1.y,ax,3)
arrow(l2.x,l2.y,ax,6)
arrow(l3.x,l3.y,ax,10)

plt.show()

enter image description here