matplotlib 色图:不要调整大小
我正在使用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)]
但是matplotlib似乎会自动调整颜色变化的范围:左下角的格子应该是浅灰色,因为它对应的值是0.2,而不是0.0。同样,右下角的格子应该是深灰色,因为它是0.8,而不是1。
我觉得我漏掉了设置颜色映射动态范围的步骤。我查阅了一些matplotlib的文档,但没有找到我想要的内容。
1 个回答
2
如果你想明确设置颜色映射的范围,可以使用 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)
想了解更多,可以查看这里: http://matplotlib.org/api/cm_api.html