matplotlib---画等高线
contour - 绘制等高线
mp.contour(x, y, z, 等高线条数,colors=颜色, linewidth=线宽)#等高线绘制
contourf - 填充等高线
mp.contourf(x, y, z, 等高线条数,cmap=颜色映射)# 等高线填充
clabel - 标记等高线,向CS(由contour函数返回的matplotlib.contour.ContourSet对象)中的轮廓线添加标签
clabel(CS, *args, **kwargs)
- CS - 由contour函数产生的句柄对象
- fontsize - string(smaller, x-large) or float ,optional
- colors - Color of each label
- None, 标记的颜色为轮廓的颜色
- one string color (e.g color = 'r' ), 所有的标签均为红色
- a tuple of matplotlib color args (string, float, rgb, etc), 不同的标签按照指定的颜色标记
- inline - bool, optional . 默认True(在标签位值移除轮廓线,也即标签覆盖轮廓线,而非穿越)
- inline_spacing - float, optional,默认5,放置内联时,标签两侧留有的像素空间
- fmt - string or dict, optional, 默认'%1.3f ',保留小数位。1.3中的1表示输出位宽,3表示小数位长度,此时实际数据会覆盖掉该数据对应的轮廓线;当9.3时,轮廓线会被覆盖掉9个位置,同时小数点后保留3位,也就是说,轮廓线移除的长度大于数据长度
- manual - bool or iterable, optional , 手动添加标签。忽略该字典
- rightside_up - bool, optional,默认 True(标签旋转均以正负90度计)
- use_clabeltext - bool, optional,默认False,若为True,则用 `ClabelText` class (instead of `Text`) 创建标签,当使用“CababelTress”绘制文本时,会重新计算文本的旋转角度,因此,如果轴的角度发生变化时,可以使用“CababelTress”来旋转角度。
举例:One-class SVM
import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn import svm xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500)) # Generate train data X = 0.3 * np.random.randn(100, 2) X_train = np.r_[X + 2.4, X - 2.3] X_test = np.r_[X + 2, X - 2] # Generate some abnormal novel observations X_outliers = np.random.uniform(low=0.1, high=4, size=(20, 2)) # fit the model clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1) clf.fit(X_train) y_pred_train = clf.predict(X_train) y_pred_test = clf.predict(X_test) y_pred_outliers = clf.predict(X_outliers) n_error_train = y_pred_train[y_pred_train == -1].size n_error_test = y_pred_test[y_pred_test == -1].size n_error_outlier = y_pred_outliers[y_pred_outliers == 1].size # plot the line , the points, and the nearest vectors to the plane Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Novelty Detection") # 填充等高线图 plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu) # 绘制等高线 a = plt.contour(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred') s = 40 b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='green', s=s, edgecolors='k') b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s, edgecolors='k') c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s, edgecolors='k') plt.axis('tight') plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend([a.collections[0], b1, b2, c], ["learned frontier", 'training observations', "new regular observations", "new abnormal observations"], loc="upper left", prop=matplotlib.font_manager.FontProperties(size=11)) plt.xlabel("error train: %d/200; errors novel regular: %d/40; errors novel abnormal:%d/40" % (n_error_train, n_error_test, n_error_outlier)) plt.show()
参考文献:
【1】基于matplotlib的数据可视化 - 等高线 contour 与 contourf