Creating a Colormap Legend in Matplotlib


Question

I am using imshow() in matplotlib like so:

import numpy as np
import matplotlib.pyplot as plt
mat = '''SOME MATRIX'''
plt.imshow(mat, origin="lower", cmap='gray', interpolation='nearest')
plt.show()

How do I add a legend showing the numeric value for the different shades of gray. Sadly, my googling has not uncovered an answer :(

Thank you in advance for the help.

Vince

1
32
3/20/2018 6:01:52 PM

Accepted Answer

Simple, just plt.colorbar():

import numpy as np
import matplotlib.pyplot as plt
mat = np.random.random((10,10))
plt.imshow(mat, origin="lower", cmap='gray', interpolation='nearest')
plt.colorbar()
plt.show()
21
6/23/2017 9:05:24 PM

There's a builtin colorbar() function in pyplot.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon