matplotlib 画点到点的箭头 quiver

这个quiver的构造方法还挺蛋疼的,很多时候我们想要点对点的箭头,下面提供一种快速获得点到点箭头的方法

import matplotlib.pyplot as plt

实例:
dx = x2 - x1
dy = y2 - y1
plt.quiver(x1, y1, dx, dy, angles='xy', scale=1, scale_units='xy')
plt.quiver(X, Y, U, V, angles='xy', scale=1, scale_units='xy')

参数解释:
X : 箭头(向量)起点x坐标
Y : 箭头(向量)起点y坐标
U : 箭头终点坐标为 X+U 
V : 箭头终点坐标为 Y+V

注意,这样点到点的箭头,需要将
scale       参数设置为 1
scale_units 参数设置为 'xy'

示例

我们还可以基于点到点的箭头,输入点坐标,画出按照x,y排序的点的序列,这些序列的箭头指向下一个点
在这里插入图片描述

代码

import matplotlib.pyplot as plt

'''
10
0 8
17 80
6 81
26 43
63 14
32 48
41 33
28 70
50 0
68 87
'''

class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def cmpx(p1, p2):
    if(p1.x==p2.x):
        return (p1.y<p2.y)
    return (p1.x<p2.x)

def sort(points, cmp):
    n = points.__len__()
    for i in range(n):
        for j in range(n-1):
            if cmp(points[j], points[j+1]) == False:
                points[j],points[j+1] = points[j+1], points[j]

if __name__ == '__main__':
	# 输入点
    points = []
    n = int(input())
    for i in range(n):
        x, y = map(int,input().split(' '))
        points.append(point(x, y))
        
	# 按xy排序
    sort(points, cmpx)

	# 设置画布
    fig = plt.figure()
    plt.xlim(-10, 90)
    plt.ylim(-10, 100)

	# 画点
    for p in points:
        plt.plot(p.x, p.y, "o")
		
	# 画箭头
    for i in range(n-1):
        dx = points[i+1].x - points[i].x
        dy = points[i+1].y - points[i].y
        plt.quiver(points[i].x, points[i].y, dx, dy, angles='xy', scale=1.03, scale_units='xy', width=0.005)

    plt.show()
发布了262 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/105352402