如何在matplotlib中绘制有向线? [英] How to plot a directed line in matplotlib?

查看:79
本文介绍了如何在matplotlib中绘制有向线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 matplotlib 中,使用 plt.plot(xs, ys, '-'+marker) 从数据点绘制一条线很容易.这为您提供了一条无向线,您无法通过查看结果图分辨出哪一端对应于数据点数组的开头,哪一个对应于数组的结尾.碰巧的是,对于我正在做的事情,重要的是要知道行进的终点是哪个方向,或者等效地,确定行进的方向.为了获得视觉上的区别,推荐的绘制线的方法是什么?

解决方案

以下是一种选择.它是在一条线上添加一些箭头.可以使用

In matplotlib, it's easy to draw a line from data points with plt.plot(xs, ys, '-'+marker). This gets you an undirected line, where you can't tell from looking at the resulting diagram, which end corresponds to the beginning of the arrays of data points and which to the end of the arrays. It happens that for what I'm doing, it's important to be able to tell which end is which, or equivalently, which direction the line is going. What is the recommended way to plot a line so as to obtain that visual distinction?

解决方案

The following would be one option. It is to add some arrow heads along a line. This can be done using a 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()

这篇关于如何在matplotlib中绘制有向线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆