Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 462
user541686 Avatar asked Mar 12 '13 02:03

user541686


People also ask

How do I make dashed lines in matplotlib?

x: X-axis points on the line. y: Y-axis points on the line. linestyle: Change the style of the line.

How do I make a dashed line in Python?

Drawing a dashed linepenup() function; to tell it to draw again, use turtle. pendown() .


1 Answers

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

like image 196
Joe Kington Avatar answered Oct 28 '22 10:10

Joe Kington