改变xticks和yticks

时间:2018-03-13 22:23:34

标签: python-3.x python-2.7 matplotlib plot

在使用缩放的特征(年龄和工资)拟合kNN分类器后,我想用未缩放的特征值​​绘制结果图。

kNN-plot

我认为这样做的一种方法是改变剧情的xticks和yticks并留下类似的东西。希望有人有更好的主意。

此外,如果图表可以在左下角显示正确的(年龄/工资)值,当我将光标放在图表上时,这将是很好的。

不幸的是,我不知道该怎么做。因此,我正在寻求帮助。

数据集: https://www.dropbox.com/sh/2mfr2kajrm7y2qq/AADFmZzYWLEjqYSLPjaQcLwka?dl=0

到目前为止的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

X = dataset.iloc[:, [2, 3]].values.astype(float)
y = dataset.iloc[:,-1].values

# splitting into training and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.75, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)

# no fit, because it is test
X_test = sc_X.transform(X_test)

# fitting kNN classification to the training set
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)
classifier.fit(X_train, y_train)

# Predict the Test set result
y_pred = classifier.predict(X_test)


# Visualising the Test set results
f = plt.figure()
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Logistic Regression (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
f.show()

1 个答案:

答案 0 :(得分:0)

好吧,我注意到答案很简单...... 我觉得太复杂了。

然而,这是解决方案:

我们只需添加以下行:

wished_xticks = np.array([18, 22, 35])
temp_x = np.c_[ wished_xticks, [0]*len(wished_xticks) ]
transformed_x = sc_X.transform(temp_x)[:,0]
plt.xticks(transformed_x, wished_xticks)

wished_yticks = np.array([17000, 25000, 100000, 150000])
temp_y = np.c_[ [0]*len(wished_yticks), wished_yticks ]
transformed_y = sc_X.transform(temp_y)[:,1]
plt.yticks(transformed_y, wished_yticks)

所以,我们得到了我们希望的结果: Diagram