本文介绍了python中的3d向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below allows me to plot vectors at different vertical levels but these vectors do not have arrow heads attached to them. I was wondering how should I modify this code so that I can get arrowheads at the end of the vectors?

#!/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()

推荐答案

这里有一些很好的例子将箭头放在matplotlib的3d图中的向量上并在绘制3d立方体,球体和Matplotlib 中的向量

There is some nice example atPutting arrowheads on vectors in matplotlib's 3d plotand at Plotting a 3d cube, a sphere and a vector in Matplotlib

根据它们,您可以创建从FancyArrowPatch继承的类,该类负责绘制带有箭头的线.

According to them, You can create class that inherits from FancyArrowPatch and is responsible for drawing lines with arrowheads.

整个代码看起来像这样:

Whole code could look like this:

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 文档.

I hope this will help a bit.Also for more arrow styles please visit matplotlib.patches documentation.

这篇关于python中的3d向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:38