matplotlib, set color of lines along a grayscale using numbers from 0. (white) to 1. (black)

Saullo G. P. Castro picture Saullo G. P. Castro · Jun 21, 2013 · Viewed 9.3k times · Source

I've been trying to follow the instructions here to set the color of many lines along a grayscale using floats from 0. (white) to 1. (black). The function line.set_color() accepts the floats, but the error below appears when I do plt.show():

ValueError: to_rgba: Invalid rgba arg "1.0"
to_rgb: Invalid rgb arg "1.0"
cannot convert argument to rgb sequence

In this answer it is explained how to do that using plt.cm.RdYlBu(i). Is there any equivalent for grayscale?

Answer

Joe Kington picture Joe Kington · Jun 21, 2013

For historical reasons, matplotlib expects "floats" to be interpreted as grayscale values to be passed in as strings, which is the reason for your error.

For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10), color="0.5")
plt.show()

enter image description here

Also, for a grayscale colormap, just use plt.cm.gray or plt.cm.gray_r (reversed). There's a full list of colormaps here: http://matplotlib.org/examples/pylab_examples/show_colormaps.html