Matplotlib scatterplot; colour as a function of a third variable

Thomas Collett picture Thomas Collett · Nov 20, 2011 · Viewed 236.3k times · Source

I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I've got very close with this:

plt.scatter(w, M, c=p, marker='s')

where w and M are the datapoints and p is the variable I want to shade with respect to.
However I want to do it in greyscale rather than colour. Can anyone help?

Answer

Joe Kington picture Joe Kington · Nov 20, 2011

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()