Python: display a matrix with negative and positive values
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()
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:
Jingtao
Updated on July 03, 2022Comments
-
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 usingimshow(m, []);
. How can I do this equivalently under python? -
rayryeng almost 10 years+1 - Nice. I totally forgot
matplotlib
hasimshow
. Sweet! -
Jingtao almost 10 yearsHow to show it in grayscale? :)
-
Amro almost 10 yearsset the colormap as such:
plt.imshow(.., cmap='gray')
. Here is a quick tutorial to get you started: matplotlib.org/users/image_tutorial.html