Matplotlib colormap: do not resize

I draw a confusion matrix using matplotlib:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

conf_arr_hs = [[90, 74],
                [33, 131]]
norm_conf_hs = []
for i in conf_arr_hs:
    a = 0
    tmp_arr = []
    a = sum(i, 0)
    for j in i:
        tmp_arr.append(float(j)/float(a))
    norm_conf_hs.append(tmp_arr)


confmatmap=cm.binary    
fig = plt.figure()


plt.clf()
ax = fig.add_subplot(111)
res = ax.imshow(np.array(norm_conf_hs), cmap=confmatmap, interpolation='nearest')
for x in xrange(2):
    for y in xrange(2):
        textcolor = 'black'
        if norm_conf_hs[x][y] > 0.5:
            textcolor = 'white'
        ax.annotate("%0.2f"%norm_conf_hs[x][y], xy=(y, x),  horizontalalignment='center', verticalalignment='center', color=textcolor)]

But matplotlib seems to automatically resize the color range: the lower left grid should be light gray, as its corresponding value is 0.2 instead of 0.0. Similarly, the lower right grid should be dark gray, as it is 0.8 instead of 1.

I think I'm skipping the dynamic range assignment step for color matching. I did some research on the matplotlib documentation, but did not find what I want.

+4
source share
1 answer

To explicitly specify a range of color maps, you want to use the command set_clim:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.ion()

conf_arr_hs = [[90, 74],
                [33, 131]]
norm_conf_hs = []
for i in conf_arr_hs:
    a = 0
    tmp_arr = []
    a = sum(i, 0)
    for j in i:
        tmp_arr.append(float(j)/float(a))
    norm_conf_hs.append(tmp_arr)

confmatmap=plt.cm.binary    
fig = plt.figure()

plt.clf()
ax = fig.add_subplot(111)
res = ax.imshow(np.array(norm_conf_hs), cmap=confmatmap, interpolation='nearest')
res.set_clim(0,1) # set the limits for your color map

for x in xrange(2):
    for y in xrange(2):
        textcolor = 'black'
        if norm_conf_hs[x][y] > 0.5:
            textcolor = 'white'
        ax.annotate("%0.2f"%norm_conf_hs[x][y], xy=(y, x),  horizontalalignment='center', verticalalignment='center', color=textcolor)

enter image description here

: http://matplotlib.org/api/cm_api.html

+2

Source: https://habr.com/ru/post/1539142/


All Articles