1

I often have to print out graphs on a black and white printer and if I want to show different datasets on the same graph the default different colours used by matplotlib doesn't help me.

Is there a way to change the matplotlib defaults to cycle through a range of different variations of dashed lines, as often seen in technical publications, instead of cycling through different colored lines?

I would greatly appreciate help on this.

Jonny
  • 1,270
  • 5
  • 19
  • 31

2 Answers2

3

You can use the itertools module to cycle over linestyles

import matplotlib.pyplot as plt
import itertools

# put all the linestyles you want in the list below (non exhaustive here)
style=itertools.cycle(["-","--","-.",":",".","h","H"])


# assuming xseries and yseries previously created (each one is a list of lists)
for x,y in zip(xseries,yseries):
    plt.plot(x,y,"b"+style.next())
plt.show()
manu190466
  • 1,557
  • 1
  • 9
  • 17
  • Exactly what I want, thanks! – Jonny Mar 20 '15 at 11:38
  • 1
    It is better to pass the color and linestyle via kwargs `ax.plot(x, y, color='b', linestyle=style.next())`. The MATLAB like style strings are good for interactive use, but for scripts it is better to be explicit. – tacaswell Mar 20 '15 at 13:17
  • `itertools.cycle().next()` was removed in python3 to favor `next(itertools.cycle())` – ibci Mar 22 '20 at 10:00
1

The Matplotlib docs have a pretty good example of changing the shape of the lines:

http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties

It wouldn't be overly difficult to build a function which returns or yields one of the values from a list in a cyclic matter.

From the example in the docs:

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Generates three different coloured and shaped lines on a graph.

NDevox
  • 4,056
  • 4
  • 21
  • 36
  • This means you need to type each one in my hand. – tacaswell Mar 20 '15 at 13:18
  • not specifically your hand. \jk. I was intending the sample code as an example of how to change the line type. This was accompanied by `It wouldn't be overly difficult to build a function which returns or yields one of the values from a list in a cyclic matter.` which was intended to suggest designing a function much like @manu190466 made. – NDevox Mar 20 '15 at 14:01