简体   繁体   English

同一个 plot 上的多个箭头使用 Matplotlib

[英]Multiple arrows on the same plot using Matplotlib

I want to have multiple arrows on the same plot using the list I6 .我想使用列表I6在同一个 plot 上设置多个箭头。 In I6[0] , (0.5, -0.5) represent x,y coordinate of the arrow base and (1.0, 0.0) represent the length of the arrow along x,y direction.I6[0]中, (0.5, -0.5)表示箭头基部的 x,y 坐标, (1.0, 0.0)表示箭头沿 x,y 方向的长度。 The meanings are the same for I6[1],I6[2],I6[3] But the code runs into an error. I6[1],I6[2],I6[3]含义相同,但代码运行出错。

import matplotlib.pyplot as plt

I6=[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]

for i in range(0,len(I6)): 
    plt.arrow(I6[i][0], I6[i][1], width = 0.05)
    plt.show()

The error is错误是

in <module>
    plt.arrow(I6[i][0], I6[i][1], width = 0.05)

TypeError: arrow() missing 2 required positional arguments: 'dx' and 'dy'

Instead of plotting arrows in matplotlib with arrow() , use quiver() to avoid issues with list values:不要使用arrow()在 matplotlib 中绘制箭头,而是使用quiver()来避免列表值出现问题:

import matplotlib.pyplot as plt

I6=[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]

for i in range(len(I6)):
    plt.quiver(I6[i][0], I6[i][1], width = 0.05)
plt.show()

In this case, the arrows seem to be too thick and with a small modulus, you can adjust this by changing the input values of your list I6在这种情况下,箭头似乎太粗并且模数很小,您可以通过更改列表I6的输入值来调整它在此处输入图像描述

The solution is to unpack the coordinates and lengths from the data matrix correctly, as解决方案是正确解压数据矩阵中的坐标和长度,如

(x, y), (u, v) = element 

Then, the plot can either be done with quiver or arrow as shown in these two examples below.然后,plot 可以用quiverarrow完成,如下面的两个示例所示。

import matplotlib.pyplot as plt

I6 = [
    [(0.5, -0.5), (1.0, 0.0)], 
    [(0.5, -0.5), (0.0, -1.0)], 
    [(1.5, -0.5), (0.0, -1.0)], 
    [(0.5, -1.5), (1.0, 0.0)]
]

# Solution with arrow
for element in I6:
    (x, y), (dx, dy) = element
    plt.arrow(x, y, dx, dy, head_width=0.02, color="k")

plt.show()

# Solution with quiver
plt.figure()
for element in I6:
    (x, y), (dx, dy) = element
    plt.quiver(x, y, dx, dy, scale=1, units="xy", scale_units="xy")

plt.show()

带有 matplotlib 箭头函数的箭头 带有 matplotlib quiver 函数的箭头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM