Python: display a matrix with negative and positive values

10,190

Solution 1

Looks like it gets scaled by default using matplotlib's imshow:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1.0,2.0], [-3.0,-2.0]], dtype='float')

plt.imshow(x, interpolation='none')
plt.colorbar()
plt.show()

matrix

Solution 2

imshow accepts color scale minimum and maximum:

import numpy as np
import matplotlib.pyplot as plt

# create some data with both negative and positive values
data = np.random.randn(10,10)

fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(data, vmin=-.2, vmax=.2, interpolation='nearest', cmap=plt.cm.gray, aspect='auto')
fig.colorbar(im)

(Just note that I use the object-oriented notation. If you use the stateful inteface, then naturally it is only imshow(...), etc. The main point is in the keyword arguments.)

Of the keyword arguments vmin and vmax tell the color map scaling, cmap defines the color map, and aspect='auto' makes the image scalable in both dimensions. The interpolation argument is nice to test yourself (just leave it out and see what happens).

In this case the lowest color (values <= -.2) is black and the highest color (values >= .2) is white:

enter image description here

Share:
10,190
Jingtao
Author by

Jingtao

Updated on July 03, 2022

Comments

  • Jingtao
    Jingtao almost 2 years

    I have a matrix m with positive and negative values. I would like to visualize this matrix in Python. In MATLAB, I can display this matrix so that the most negative value gets mapped to 0 while the most positive value gets mapped to 255 through using imshow(m, []);. How can I do this equivalently under python?

  • rayryeng
    rayryeng almost 10 years
    +1 - Nice. I totally forgot matplotlib has imshow. Sweet!
  • Jingtao
    Jingtao almost 10 years
    How to show it in grayscale? :)
  • Amro
    Amro almost 10 years
    set the colormap as such: plt.imshow(.., cmap='gray'). Here is a quick tutorial to get you started: matplotlib.org/users/image_tutorial.html