Sean Mackesey
Sean Mackesey

Reputation: 10939

Controlling the Range of a Color Matrix Plot in Matplotlib

I'd like to make a matrix plot like the image below in matplotlib. I can make this a plot like this with this code:

m = numpy.random.rand(100,100)
matplotlib.pyplot.matshow(m)

How can I control the color scale, i.e. set the values corresponding to the "min" and "max" colors?

Upvotes: 6

Views: 22092

Answers (1)

SpinUp __ A Davis
SpinUp __ A Davis

Reputation: 5531

The matshow docs indicate that the options are mostly just passed to imshow (docs). Imshow takes arguments vmin and vmax that determine the min and max colors as you desire. Let's check out an example:

import numpy as np
import matplotlib.pyplot as plt
plt.ion()
A = np.arange(0,100).reshape(10,10)
plt.matshow(A)                        # defaults
plt.matshow(A, vmin=0, vmax=99)       # same
plt.matshow(A, vmin=10, vmax=90)      # top/bottom rows get min/max colors, respectively

Aside:

May I also recommend changing the colormap? eg. cmap='hot'. Though it is the default (why?), the 'jet' colormap is almost never the best choice.

x = np.random.randn(1000)
y = np.random.randn(1000)+5
plt.hist2d(x, y, bins=40, cmap='hot')
plt.colorbar()

output of the examle code with cmap='hot'

Upvotes: 19

Related Questions