1

I try to visualize a numpy array to image. But the array contains negative values or values that out of bound.

I have get an image successfully, but I have some question about gray scale.

How does it interpret through the colormap ?. (In principle, if the array is a float array scaled to 0..1, it should be interpreted as a grayscale image) So, what is the principle?

Thank you very much for your collaboration.

V = np.loadtxt('np.txt')
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)       
ax.matshow(V, cmap = matplotlib.cm.binary)
plt.show()

The np array like:
[ [....]
....
 [  7.47859700e-03  -4.42994573e-03  -3.15871151e-02   4.57486308e-02
    4.58066400e-02   7.81800849e-02   1.41268438e-01   2.67617603e-01
    3.98583385e-01   3.85877649e-01   1.92501545e-01   2.65159152e-01
    2.10979793e-01   2.48940247e-01   1.75112904e-01  -3.06361785e-02
    2.74774650e-01   1.81465161e-01   4.23131349e-03  -3.56762525e-02
   -1.72089055e-02  -4.25273422e-02  -2.63428158e-02  -4.59487077e-02
   -2.30976482e-02  -4.45129524e-02   8.95580352e-03   1.56548770e-03]
...
[...] ]

1 Answer 1

2

The range of values can be set with vmin and vmax and the colormap will be scaled accordingly. This is performed in the matplotlib.colors.Normalize class, passed behind the scenes to the ScalarMappable mixin when creating a colour plot like matshow. The values for the colormap will be obtained from the normalised data by something like (V-vmin)/(vmax-vmin), then mapped to rgb or whatever. The actual code used to do this from matplotlib.colors.Normalize is,

# ma division is very slow; we can take a shortcut
resdat = result.data
resdat -= vmin
resdat /= (vmax - vmin)

If you don't specify vmin or vmax, then they are obtained automatically from the minimum and maximum values of your data vmin=V.min() and vmax = V.max(). As a minimal example of setting these limits,

import numpy as np
import matplotlib.pyplot as plt

#V = np.loadtxt('np.txt')
#Generate random data with negative values
V = np.random.randn(100,100) - 1.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)       
im = ax.matshow(V, cmap = plt.cm.binary, vmin = -3., vmax=3.)
plt.colorbar(im)
plt.show()

Where im here is a ScalarMappable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.