Pradyparanjpe
Pradyparanjpe

Reputation: 45

Matplotlib: Arrow heads at each vertex in Path

I am trying to plot the path taken by some input function (whose vertices are recorded in a numpy array)

I want to add an arrow-head (any direction marker) for every vertex of the form "→→→→" to track the direction of path.

I know the FancyArrowPatch which adds only one arrow-head a the terminal vertex, of the form: "————>". That's NOT what I want. [for reasons that are outside the scope of this question]

Currently, my code looks like this: Note, we can't guess the direction.

def plot_track(self, verts: np.array) -> None:
    '''Plot followed track: verts is 2D array: x, y'''
    track = Path(verts)
    patch = PathPatch(path=track, edgecolor="#FF0000",
                      fill=False)
    self.axs.add_patch(patch)
    self.fig.canvas.draw()
    self.root.mainloop()

Output-link

Upvotes: 2

Views: 1183

Answers (1)

JohanC
JohanC

Reputation: 80339

matplotlib.patches.Arrow can be used to draw arrows. A loop needs to visit each vertex and its successor. A similar approach can be used with FancyArrowPatch.

import matplotlib.pyplot as plt
from matplotlib.patches import Arrow
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch, Path, Arrow
import numpy as np

def plot_track(verts, ax, **kw_args):
    '''Plot followed track: verts is 2D array: x, y'''
    for xy0, xy1 in zip(verts[:-1], verts[1:]):
        patch = Arrow(*xy0, *(xy1 - xy0), **kw_args)
        ax.add_patch(patch)
    ax.relim()
    ax.autoscale_view()

fig, ax = plt.subplots()
t = np.arange(2, 11, 1)
x = t * np.sin(t)
y = t * np.cos(t)
verts = np.vstack([x, y]).T

plot_track(verts - np.array([7, 0]), ax, color='red', fill=True, width=1)
plot_track(verts + np.array([7, 0]), ax, color='red', fill=False, width=1)
plt.show()

resulting plot

Upvotes: 2

Related Questions