user541686
user541686

Reputation: 210455

Plotting dashed 2D vectors with matplotlib?

I'm using quiver to draw vectors in matplotlib:

from itertools import chain
import matplotlib.pyplot as pyplot
pyplot.figure()
pyplot.axis('equal')
axis = pyplot.gca()
axis.quiver(*zip(*map(lambda l: chain(*l), [
    ((0, 0), (3, 1)),
    ((0, 0), (1, 0)),
])), angles='xy', scale_units='xy', scale=1)

axis.set_xlim([-4, 4])
axis.set_ylim([-4, 4])
pyplot.draw()
pyplot.show()

which gives me nice arrows, but how can I change their line style to dotted, dashed, etc.?

Upvotes: 9

Views: 8211

Answers (1)

Joe Kington
Joe Kington

Reputation: 284602

Ah! Actually, linestyle='dashed' does work, it's just that quiver arrows are only filled by default and don't have a linewidth set. They're patches instead of paths.

If you do something like this:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis('equal')

ax.quiver((0,0), (0,0), (3,1), (1,0), angles='xy', scale_units='xy', scale=1,
          linestyle='dashed', facecolor='none', linewidth=1)

ax.axis([-4, 4, -4, 4])
plt.show()

enter image description here

You get dashed arrows, but probably not quite what you had in mind.

You can play around with some of the parameters to get a bit closer, but it still doesn't exactly look nice:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis('equal')

ax.quiver((0,0), (0,0), (3,1), (1,0), angles='xy', scale_units='xy', scale=1,
          linestyle='dashed', facecolor='none', linewidth=2,
          width=0.0001, headwidth=300, headlength=500)

ax.axis([-4, 4, -4, 4])
plt.show()

enter image description here

Therefore, another workaround would be to use hatches:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis('equal')

ax.quiver((0,0), (0,0), (3,1), (1,0), angles='xy', scale_units='xy', scale=1,
        hatch='ooo', facecolor='none')

ax.axis([-4, 4, -4, 4])
plt.show()

enter image description here

Upvotes: 11

Related Questions