简体   繁体   English

如何在matplotlib中强制轴相等

[英]How to force axis equal in matplotlib

I'm implementing a Naive Bayes classifier. 我正在实现朴素贝叶斯分类器。

I have the following figure showing me my classification boundaries: 下图显示了我的分类边界:

在此处输入图片说明

I want to make the axes equally scaled for the figure, because I think it would help me better understand what is going on. 我想使轴按比例缩放,因为它可以帮助我更好地了解发生了什么。 However, I haven't found any way to do this. 但是,我还没有找到任何方法可以做到这一点。 The plot is generated by a function not written by me: 该图由我未编写的函数生成:

%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()

I've tried injecting plt.axis("equal") into this function (1 line from the bottom of the code) but it doesn't make my axes equal. 我尝试将plt.axis("equal")注入此函数(从代码底部开始的1行),但这不会使我的轴相等。 How can I achieve this? 我该如何实现?

EDIT: I also tried injecting plt.gca().set_aspect('equal', adjustable='box') . 编辑:我也尝试注入plt.gca().set_aspect('equal', adjustable='box') It didn't change anything. 它没有改变任何东西。

the equal keyword scales x and y to be on the same scale. 相等的关键字将x和y缩放为相同的比例。 However if you meant that you want square axis you can try plt.axis('box') 但是,如果您要使用方轴,则可以尝试plt.axis('box')

You can set the limits manually: 您可以手动设置限制:

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

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

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

Then make sure you have a 1:1 aspect ratio 然后确保纵横比为1:1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM