Search code examples
pythonmatplotlib

Why won't Matplotlib's imshow plot 0.5 as grey?


I remember this working. Zero meant fully dark and one meant fully lit up and in-between meant some shade of grey for plotting with pyplot.imshow. I remember plotting the MNIST data of handwritten digits like that. I wrote the following,

import numpy as np
import matplotlib.pyplot as plt


matrix = 0.5*np.identity(5)
plt.imshow(matrix, cmap='grey')
plt.show()

If I do not multiply the identity matrix with a half, I get what I expect. But--multiplying it with a half, I expected to see greys along the diagonal. However, it still plots whites there.

Am I missing some small detail? Is there a way to get the behaviour that I expect?


Solution

  • You probably want this -

    import numpy as np
    from matplotlib import pyplot as plt
    
    
    matrix = 0.5*np.identity(5)
    plt.imshow(matrix, cmap='gray', vmin=0, vmax=1)
    plt.show()
    

    It looks like your program is defaulting to a vmax of 0.5 (and makes the value of 0.5 essentially identical to values of 1) when the inputs is 0.5 identity matrix, setting the bounds seems to fix that issue