matplotlib contourf层级异常:KNN决策边界绘制类别数超限问题
Matplotlib contourf 忽略 levels 参数(类别数>5时少绘制一层)的解决方法
你遇到的问题根源在于:使用整数作为levels参数时,Matplotlib会自动从数据最小值到最大值生成等间距水平,但你的lm是离散整数类别标签,自动划分的区间无法完美对齐类别边界,当类别数超过5时,就会出现少绘制一层的情况。
解决方案
手动指定levels数组,让每个水平刚好落在类别标签的中间位置,确保每个类别对应独立的填充区域;同时调整colors参数长度与类别数匹配(levels数组长度为类别数+1,对应类别数个填充区域)。
修改后的代码:
import numpy as np import matplotlib.pyplot as plt color_lis = ['black','red','blue','green','gold','pink','cyan','peru','silver','purple'] def createPlot(num_of_classes, ax_idx , ax): x_linspace = np.linspace(-1,1 , num = 101) y_linspace = np.linspace(1,-1 , num = 101) xm, ym = np.meshgrid(x_linspace, y_linspace) lm = np.zeros(xm.shape) for i in range(xm.shape[0]): c = 0 l = 0 for j in range(xm.shape[1]): if c % num_of_classes == 0: l += 1 l %= num_of_classes lm[i,j] = l c += 1 ax[ax_idx].set_aspect('equal') # 手动生成levels数组,精准对齐类别边界 levels = np.arange(-0.5, num_of_classes + 0.5, 1) ax[ax_idx].contourf( xm, ym, lm , colors = color_lis[:num_of_classes], levels=levels, alpha = 0.35 , antialiased = True ) fig, ax = plt.subplots(nrows = 1 , ncols = 2) createPlot(4, 0 , ax) # 4个类别,对应4种颜色 createPlot(6, 1 , ax) # 6个类别,对应6种颜色,绘制正常
关键修改说明
levels = np.arange(-0.5, num_of_classes + 0.5, 1):生成的水平数组从-0.5开始,到num_of_classes-0.5结束,每个间隔为1,刚好落在每个整数类别的中间位置,确保每个类别(0到num_of_classes-1)对应一个独立的填充区间。colors = color_lis[:num_of_classes]:填充区域数量等于类别数,取前num_of_classes个颜色,避免多余颜色被Matplotlib忽略。
修改后,无论类别数是多少(≤10),contourf都会正确绘制每个类别的决策边界,不会出现少层问题。
内容的提问来源于stack exchange,提问作者ARK1375
相关产品推荐
相关产品推荐

