Deaton Deaton - 1 year ago 125
Python Question

How do I specify an arrow-like linestyle in Matplotlib?

I would like to display a set of xy-data in Matplotlib in such a way as to indicate a particular path. Ideally, the linestyle would be modified to use an arrow-like patch. I have created a mock-up, shown below (using Omnigraphsketcher). It seems like I should be able to override one of the common

declarations (
, etc) to this effect.

Note that I do NOT want to simply connect each datapoint with a single arrow---the actually data points are not uniformly spaced and I need consistent arrow spacing.

enter image description here

Answer Source

Here's a starting off point:

  1. Walk along your line at fixed steps (aspace in my example below) .

    A. This involves taking steps along the line segments created by two sets of points (x1,y1) and (x2,y2).

    B. If your step is longer than the line segment, shift to the next set of points.

  2. At that point determine the angle of the line.

  3. Draw an arrow with an inclination corresponding to the angle.

I wrote a little script to demonstrate this:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.add_subplot(111)

# my random data
scale = 10 
x = np.random.random(10)*scale
y = np.random.random(10)*scale

# spacing of arrows
aspace = .1 # good value for scale of 1
aspace *= scale

# r is the distance spanned between pairs of points
r = [0]
for i in range(1,len(x)):
    dx = x[i]-x[i-1]
    dy = y[i]-y[i-1]
r = np.array(r)

# rtot is a cumulative sum of r, it's used to save time
rtot = []
for i in range(len(r)):

arrowData = [] # will hold tuples of x,y,theta for each arrow
arrowPos = 0 # current point on walk along data
rcount = 1 
while arrowPos < r.sum():
    x1,x2 = x[rcount-1],x[rcount]
    y1,y2 = y[rcount-1],y[rcount]
    da = arrowPos-rtot[rcount] 
    theta = np.arctan2((x2-x1),(y2-y1))
    ax = np.sin(theta)*da+x1
    ay = np.cos(theta)*da+y1
    while arrowPos > rtot[rcount+1]: 
        if arrowPos > rtot[-1]:

# could be done in above block if you want
for ax,ay,theta in arrowData:
    # use aspace as a guide for size and length of things
    # scaling factors were chosen by experimenting a bit


This example results in this figure: enter image description here

There's plenty of room for improvement here, for starters:

  1. One can use FancyArrowPatch to customize the look of the arrows.
  2. One can add a further test when creating the arrows to make sure they don't extend beyond the line. This will be relevant to arrows created at or near a vertex where the line changes direction sharply. This is the case for the right most point above.
  3. One can make a method from this script that will work across a broader range of cases, ie make it more portable.

While looking into this, I discovered the quiver plotting method. It might be able to replace the above work, but it wasn't immediately obvious that this was guaranteed.