notebook icon indicating copy to clipboard operation
notebook copied to clipboard

Matplotlib 绘图相关

Open w4096 opened this issue 6 years ago • 2 comments

  • 散点图
  • 对三维数据可视化

w4096 avatar Jan 11 '19 14:01 w4096

散点图

各种 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 avatar Jan 11 '19 14:01 w4096

对三维数据可视化

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

使用 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

w4096 avatar Jan 11 '19 14:01 w4096