Reputation: 6284
I want to create multiple images of a matrix. I have modified the code at Drawing grid pattern in matplotlib which uses the cmap property "set_bad" to set Nan values to transparent white.
Is there a way to avoid to set "set_bad", "set_upper" and "set_lower" as well as telling the color map exactly what colors to show for a matrix value?
If my matrix is 2x2 filled with zeros I want an all black image:
.
If my matrix is 2x2 filled with ones I want an all white image like this:
This is the problem. When the matrix values are all 1.0 the image is completely black. (I guess because all the values are the same the cmap renders with the first value (black)?).
If my matrix is 2x2 with ones on the diagonal I want this image:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
N = 2
# make an empty data set
data = np.zeros((N, N))
for i in range(N):
for j in range(N):
# when all elements are 0 I want it to be black.
# Currently works how I want it to
#data[i,j] = 0
# When all elements are 1 I want it to be white but it is all black.
# This isn't working like I want it to.
data[i,j] = 1
# here I want to have white squares in the top left and bottom right.
# Currently works how I want it to
#data[0,0] = 1
#data[1,1] = 1
print(data)
# make a figure + axes
fig, ax = plt.subplots(1, 1, tight_layout=True)
# make color map
my_cmap = matplotlib.colors.ListedColormap(['black', 'white'])
# draw the grid
for x in range(N + 1):
ax.axhline(x, lw=2, color='k', zorder=5)
ax.axvline(x, lw=2, color='k', zorder=5)
# draw the boxes
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0)
# turn off the axis labels
ax.axis('off')
plt.show()
Upvotes: 0
Views: 729
Reputation: 101
imshow
scales the data before mapping to colors.
The normalization can be controlled with the norm
parameter.
From the documentation:
By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used.
So, you have to pass a custom Normalize
instance.
In your code you'll have to do the following:
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0, norm=Normalize(0,1))
to explicitly map to the [0,1] interval.
Upvotes: 1
Reputation: 13465
You need to make sure colormap you've just created is scaled correctly. For this just add the argument 'vmin' and 'vmax' to your plot instruction. Like this:
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0, vmin=0, vmax=1)
This will correct the problem:
Upvotes: 0