# meshgrid区域图

## code

```python
import numpy as np
from matplotlib.colors import ListedColormap

#classes_color:颜色列表
cmpcolor = ['#FFAAAA', '#AAFFAA', '#AAAAFF']


def create_meshgrid_pic(plt, predict, X, Y, classes_color=cmpcolor, step=0.05):
    # 确认训练集的边界
    x_min, x_max = X[:].min() - 1, X[:].max() + 1
    y_min, y_max = Y[:].min() - 1, Y[:].max() + 1
    # 生成网格数据，xx:所有网格点的x坐标，形状也是网格性nxm。yy同样
    xx, yy = np.meshgrid(np.arange(x_min, x_max, step),
                         np.arange(y_min, y_max, step))
    # xx,yy的扁平化成一串坐标点（密密麻麻的网格点平摊开来）
    d = np.c_[xx.ravel(), yy.ravel()]
    # 对网格点进行类型预测
    Z = predict(d)
    # 预测类型后，重新变回网格的样子，因为后面pcolormesh接收网格形式的绘图数据
    Z = Z.reshape(xx.shape)
    # 获取类型数量
    class_size = np.unique(Z).size
    if class_size > len(classes_color):
        print('颜色列表太少')
        return AttributeError
    classes_color = classes_color[:class_size]

    cmap_light = ListedColormap(classes_color)

    # 接收网格化的x,y,z
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
```

## 使用

```python
import matplotlib.pyplot as plt
from sklearn import neighbors
from **** import create_meshgrid_pic

X, Y = ()
clf = neighbors.KNeighborsClassifier(n_neighbors=15, weights='distance')
clf.fit(X, Y)
cmap_light = ['#FFAAAA', '#AAFFAA', '#AF0000']
create_meshgrid_pic(plt, clf, X[:, 0], X[:, 1], cmap_light, 0.02)
plt.show()
```

![img](/files/-LpsmZpcB1fUURVg6mAC)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/numpy-pandas-matplotlib/matplotlib/meshgrid.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
