Custom dash/dot line styles in matplotlib

I’ve recently been polishing a number of graphs to get them up to publication quality (coming soon!), and one of the necessary customisations that came up was the style of dashed/dotted lines. Matplotlib’s default dotted and dash/dotted line styles aren’t very clear in a lot of plots, and can be difficult to distinguish (e.g. the dash/dotted style looks too much like dots).

Happily, you can make your own custom line styles, using a sequence (list) of numbers and the set_dashes() method of the Line2D object. To do this:

import pylab as P
P.subplot(111)
line = P.plot(x, y) # 'line' is actually a list of lines. We want line[0]
seq = [2, 4, 7, 4]
line[0].set_dashes(seq)

Here, seq is the alternating sequence of dashes and spaces. seq[0] draws a line of length 2, seq[1] draws a space (i.e. no line) of length 4, seq[2] a line of length 7, and seq[3] a space of length 4.

You can carry on this sequence indefinitely if you like; even indices are drawn as lines, odd indices as spaces. For example, seq = [2, 2] would look like dots, and seq = [7, 4, 3, 4] is a clearer dash-dotted line than the default. You can even use float lengths for the dashes, rather than integers.

(There’s a rather spartan example on the matplotlib website too.)

About Phil Bull

I'm a theoretical cosmologist, currently working as a NASA NPP fellow at JPL/Caltech in Pasadena, CA. My research focuses on the effects of inhomogeneities on the evolution of the Universe and how we measure it. I'm also keen on stochastic processes, scientific computing, the philosophy of science, and open source stuff. View all posts by Phil Bull

3 responses to “Custom dash/dot line styles in matplotlib

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: