Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matplotlib 绘图相关 #49

Open
w4096 opened this issue Jan 11, 2019 · 2 comments
Open

Matplotlib 绘图相关 #49

w4096 opened this issue Jan 11, 2019 · 2 comments

Comments

@w4096
Copy link
Owner

w4096 commented Jan 11, 2019

@w4096
Copy link
Owner Author

w4096 commented Jan 11, 2019

散点图

各种 marker

import matplotlib as mpl
import matplotlib.pyplot as plt

for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
    plt.plot(np.random.rand(5), np.random.rand(5), marker,
             label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);

image

@w4096
Copy link
Owner Author

w4096 commented Jan 11, 2019

对三维数据可视化

有时将三维数据展示在二维平面上很有用,比如绘制热力图、等高线等。

使用 contourf / contourf 来绘制等高线、热力图

# 函数 f 根据 x, y 计算出 z

def f(x, y):
    return x**2 + y**2

x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 20)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

plt.contour(X, Y, Z, 30, cmap=plt.cm.rainbow)
plt.colorbar()

image

contourf 后面的 f 是填充的意思

plt.contourf(X, Y, Z, 30, cmap=plt.cm.rainbow)
plt.colorbar()

image

绘制分类器决策面

from sklearn.datasets import make_blobs

X, y = make_blobs(n_samples=100, centers=2, cluster_std=2, random_state=42)

plt.scatter(X[:,0], X[:,1], c=y, s=20, cmap=plt.cm.Dark2)

image

from sklearn.linear_model import LogisticRegression

clf = LogisticRegression()
clf.fit(X, y)

def plot_predictions(clf, axes):
    x1 = np.linspace(axes[0], axes[1], 100)
    x2 = np.linspace(axes[2], axes[3], 100)
    X1, X2 = np.meshgrid(x1, x2)
    X = np.vstack((X1.ravel(), X2.ravel())).T
    Y = clf.predict(X).reshape(X1.shape)
    plt.contourf(X1, X2, Y, cmap=plt.cm.tab10, alpha=0.2)

plt.scatter(X[:,0], X[:,1], c=y, s=10, cmap=plt.cm.tab10)
plot_predictions(clf, [-10, 10, -10, 15])

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant