如何在matplotlib中强制轴相等

时间:2018-10-26 11:55:58

标签: python matplotlib jupyter-notebook

我正在实现朴素贝叶斯分类器。

下图显示了我的分类边界:

enter image description here

我想使轴与图形相等地缩放,因为我认为这将有助于我更好地了解发生了什么。但是,我还没有找到任何方法可以做到这一点。该图由我未编写的函数生成:

%matplotlib inline
plotBoundary(BayesClassifier(), dataset='iris',split=0.7)

# ## Plotting the decision boundary
#
# This is some code that you can use for plotting the decision boundary
# boundary in the last part of the lab.
def plotBoundary(classifier, dataset='iris', split=0.7):

    X,y,pcadim = fetchDataset(dataset)
    xTr,yTr,xTe,yTe,trIdx,teIdx = trteSplitEven(X,y,split,1)
    classes = np.unique(y)

    pca = decomposition.PCA(n_components=2)
    pca.fit(xTr)

    xTr = pca.transform(xTr)
    xTe = pca.transform(xTe)

    pX = np.vstack((xTr, xTe))
    py = np.hstack((yTr, yTe))

    # Train
    trained_classifier = classifier.trainClassifier(xTr, yTr)

    xRange = np.arange(np.min(pX[:,0]),np.max(pX[:,0]),np.abs(np.max(pX[:,0])-np.min(pX[:,0]))/100.0)
    yRange = np.arange(np.min(pX[:,1]),np.max(pX[:,1]),np.abs(np.max(pX[:,1])-np.min(pX[:,1]))/100.0)

    grid = np.zeros((yRange.size, xRange.size))

    for (xi, xx) in enumerate(xRange):
        for (yi, yy) in enumerate(yRange):
            # Predict
            grid[yi,xi] = trained_classifier.classify(np.array([[xx, yy]]))


    ys = [i+xx+(i*xx)**2 for i in range(len(classes))]
    colormap = cm.rainbow(np.linspace(0, 1, len(ys)))

    fig = plt.figure()
    # plt.hold(True)
    conv = ColorConverter()
    for (color, c) in zip(colormap, classes):
        try:
            CS = plt.contour(xRange,yRange,(grid==c).astype(float),15,linewidths=0.25,colors=conv.to_rgba_array(color))
        except ValueError:
            pass
        trClIdx = np.where(y[trIdx] == c)[0]
        teClIdx = np.where(y[teIdx] == c)[0]
        plt.scatter(xTr[trClIdx,0],xTr[trClIdx,1],marker='o',c=color,s=40,alpha=0.5, label="Class "+str(c)+" Train")
        plt.scatter(xTe[teClIdx,0],xTe[teClIdx,1],marker='*',c=color,s=50,alpha=0.8, label="Class "+str(c)+" Test")
    plt.legend(bbox_to_anchor=(1., 1), loc=2, borderaxespad=0.)
    fig.subplots_adjust(right=0.7)
    plt.axis("equal") # <------- TRIED TO INJECT axis("equal") here
    plt.show()

我尝试将plt.axis("equal")注入到此函数中(代码底部的1行),但这并不能使我的坐标轴相等。我该如何实现?

编辑:我也尝试注入plt.gca().set_aspect('equal', adjustable='box')。它什么都没改变。

2 个答案:

答案 0 :(得分:0)

相等的关键字将x和y缩放为相同的比例。但是,如果您要使用方轴,可以尝试plt.axis('box')

答案 1 :(得分:0)

您可以手动设置限制:

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()

fmin = min(xmin, ymin)
fmax = max(xmax, ymax)

plt.xlim(fmin, fmax)
plt.ylim(fmin, fmax)

然后确保纵横比为1:1