0

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()
jms1980
  • 1,017
  • 1
  • 21
  • 37

1 Answers1

2

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

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()

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

Drop
  • 410
  • 5
  • 15