我正在尝试创建一个非常简单的图形,其中一个箭头应该是双头的,而其他箭头不是。我想在 matplotlib 中工作。在我的代码中,我可以使用“枢轴”来更改箭头的方向,但似乎没有选择具有两个方向的箭头。我已经看到这对于 2D 绘图是可能的,但对我来说,重要的是它是在 3D 绘图中。有人有想法吗?将非常感激。这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
# Define vectors
vectors = np.array([[0, 0, 18], [18, 0, 0], [0, 18, 0]])
# Origin point
origin = np.array([0, 0, 0])
# Plot setup`
fig = plt.figure()`
ax = fig.add_subplot(111, projection='3d')
# Define colors for each vector
colors = ['r', 'b', 'g']
# Plot vectors
for vector, color in zip(vectors, colors):
ax.quiver(origin[0], origin[1], origin[2], vector[0], vector[1], vector[2],
length=np.linalg.norm(vector), arrow_length_ratio=0.1, normalize=True,
color=color, pivot='tail')
# Set plot limits
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_zlim([-20, 20])
# Remove axis numbers and ticks
ax.set_axis_off()
# Set labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Adjust the view angle so that arrowheads face towards the user
ax.view_init(elev=29, azim=45)
plt.show()
使用 Matplotlib 在 3D 绘图中创建双头箭头没有直接的功能,但有一个解决方法可以达到所需的效果。它可能感觉有点hacky,但它对于简单的应用程序来说效果很好。具体方法如下:
绘制两个箭头:一个从原点指向向量的末端,另一个从向量的末端开始指向原点。这给出了双头箭头的外观。
这里有一个示例代码片段来说明该方法:
import matplotlib.pyplot as plt
import numpy as np
# Define your vectors
vectors = np.array([[0, 0, 18], [18, 0, 0], [0, 18, 0]])
origin = np.array([0, 0, 0]) # The origin point
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Define colors for each vector
colors = ['r', 'b', 'g']
# Plot each vector
for i, (vector, color) in enumerate(zip(vectors, colors)):
if i == 0: # Assuming the first vector needs a double-headed arrow
# Arrow from the origin to the vector end
ax.quiver(origin[0], origin[1], origin[2], vector[0], vector[1], vector[2],
arrow_length_ratio=0.1, color=color)
# Arrow from the vector end back to the origin
ax.quiver(vector[0], vector[1], vector[2], -vector[0], -vector[1], -vector[2],
arrow_length_ratio=0.1, color=color)
else:
# Single-headed arrows for the other vectors
ax.quiver(origin[0], origin[1], origin[2], vector[0], vector[1], vector[2],
arrow_length_ratio=0.1, color=color)
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_zlim([-20, 20])
ax.set_axis_off()
ax.view_init(elev=29, azim=45)
plt.show()