python二维矩阵画三维图
时间: 2023-07-01 08:18:11 浏览: 70
要将二维矩阵画成三维图,可以使用Matplotlib库中的mplot3d模块。具体步骤如下:
1. 导入相关库:
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
```
2. 定义二维矩阵:
```python
matrix = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
```
3. 创建3D图像对象:
```python
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
```
4. 定义X、Y、Z坐标轴:
```python
x_data, y_data = np.meshgrid(np.arange(matrix.shape[0]), np.arange(matrix.shape[1]))
z_data = matrix
```
5. 画出3D图像:
```python
ax.plot_surface(x_data, y_data, z_data)
```
6. 显示图像:
```python
plt.show()
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
matrix = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x_data, y_data = np.meshgrid(np.arange(matrix.shape[0]), np.arange(matrix.shape[1]))
z_data = matrix
ax.plot_surface(x_data, y_data, z_data)
plt.show()
```
阅读全文