在python中的3d矢量

时间:2014-11-25 18:59:06

标签: python matplotlib

下面的代码允许我绘制不同垂直水平的矢量,但这些矢量没有附加箭头。我想知道如何修改此代码,以便我可以在向量的末尾获得箭头?

#!/usr/bin/python

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
import numpy as np
from mpl_toolkits.mplot3d import proj3d

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([0,0.7], [0,0.5],zs=[1,1])
ax.plot([0,-0.3], [0,0.7],zs=[2,2])
ax.plot([0,-0.3],[0,0],zs=[3,3])

ax.set_xlim([0,3])
ax.set_ylim([3,0])
ax.set_zlim([0,4])
plt.show()

1 个答案:

答案 0 :(得分:1)

有一些很好的例子 Putting arrowheads on vectors in matplotlib's 3d plot 并在Python/matplotlib : plotting a 3d cube, a sphere and a vector?

根据它们你必须得到它们,你可以创建继承自FancyArrowPatch的类,并负责用箭头绘制线条。

整个代码看起来像这样:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
import numpy as np
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# lines were replaced by Arrow3D below, so they might be no longer needed
# ax.plot([0,0.7], [0,0.5],zs=[1,1]) 
# ax.plot([0,-0.3], [0,0.7],zs=[2,2])
# ax.plot([0,-0.3],[0,0],zs=[3,3])

ax.set_xlim([0, 3])
ax.set_ylim([3, 0])
ax.set_zlim([0, 4])

a = Arrow3D([0, 0.7], [0, 0.5], [1, 1], mutation_scale=20, lw=1, arrowstyle="->", color="b")
b = Arrow3D([0, -0.3], [0, 0.7], [2, 2], mutation_scale=20, lw=1, arrowstyle="->", color="r")
c = Arrow3D([0, -0.3], [0, 0], [3, 3], mutation_scale=20, lw=1, arrowstyle="->", color="g")
ax.add_artist(a)
ax.add_artist(b)
ax.add_artist(c)
plt.show()

我希望这会有所帮助。 另外,对于更多箭头样式,请访问matplotlib.patches documentation