使用matplotlib绘制分类值的等高线图

时间:2017-04-04 10:58:47

标签: matplotlib contour

我必须绘制SVM分类器的图形。这是我用来绘制的代码:

plt.contour(xx, yy, Z)

此处xxyy是功能,Z是标签。这些标签是字符串。当我运行代码时,我收到错误

ValueError: could not convert string to float: dog  

如何绘制此图表?

1 个答案:

答案 0 :(得分:2)

因为"狗"不是数值,不能直接绘制它。您需要的是分类值和数值之间的映射,例如使用dicitionary,

an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}

使用此词典,您可以使用contourf或imshow绘制0到4之间的数字数组。两者之间的差异可以在下面观察到。 Imshow更好地保留了catergories,因为它绘制像素而不是在它们之间进行插值。而且由于类别很少被插入(猫和狐狸之间的平均值是什么?),它可能更接近于此处所需的内容。

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (6,2.8)

animals = [['no animal', 'no animal', 'no animal', 'chicken', 'chicken'],
     ['no animal', 'no animal', 'cow', 'no animal', 'chicken'],
     ['no animal', 'cow', 'cat', 'cat', 'no animal'],
     ['no animal', 'cow', 'fox', 'cat', 'no animal'],
     ['cow', 'cow', 'fox', 'chicken', 'no animal'],
     ['no animal','cow', 'chicken', 'chicken', 'no animal'],
     ['no animal', 'no animal', 'chicken', 'cat', 'chicken'],
     ['no animal', 'no animal', 'no animal', 'cat', 'no animal']]

y = np.linspace(-4,4, 8)
x = np.linspace(-3,3, 5)
X,Y = np.meshgrid(x,y)

an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}
aninv =  { val: key for key, val in an.items()  }
f = lambda x: an[x]
fv = np.vectorize(f)
Z = fv(animals)


fig, (ax, ax2) = plt.subplots(ncols=2)
ax.set_title("contourf"); ax2.set_title("imshow")

im = ax.contourf(X,Y,Z, levels=[-0.5,0.5,1.5,2.5,3.5,4.5] )
cbar = fig.colorbar(im, ax=ax)
cbar.set_ticks([0,1,2,3,4])
cbar.set_ticklabels([aninv[t] for t in [0,1,2,3,4]])


im2 = ax2.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max() ], origin="lower" )
cbar2 = fig.colorbar(im2, ax=ax2 )
cbar2.set_ticks([0,1,2,3,4])
cbar2.set_ticklabels([aninv[t] for t in [0,1,2,3,4]])


plt.tight_layout()
plt.show()

enter image description here