Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: display a matrix with negative and positive values [duplicate]

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?

like image 917
Jingtao Avatar asked Jul 07 '14 18:07

Jingtao


Video Answer


2 Answers

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

like image 124
Amro Avatar answered Oct 19 '22 07:10

Amro


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

like image 21
DrV Avatar answered Oct 19 '22 07:10

DrV