matplotlib画三维热力图
时间: 2023-06-16 20:03:31 浏览: 102
要画三维热力图,可以使用`mplot3d`子库。具体步骤如下:
1. 导入`mplot3d`和`pyplot`子库:
```python
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
```
2. 创建三维图形对象`fig`和`ax`:
```python
fig = plt.figure()
ax = plt.axes(projection='3d')
```
3. 绘制三维热力图:
```python
ax.plot_surface(X, Y, Z, cmap='viridis')
```
其中,`X`、`Y`、`Z`是三个数组,表示三维空间中的点坐标和对应的颜色值。
完整代码示例:
```python
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
# 定义三维空间中的点坐标和对应的颜色值
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# 创建三维图形对象
fig = plt.figure()
ax = plt.axes(projection='3d')
# 绘制三维热力图
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
```
运行结果如下图所示:
![3d_heatmap.png](https://cdn.nlark.com/yuque/0/2021/png/538589/1626143156659-8d63d8f8-acd9-4f2e-8a4a-a19beae8c7d8.png#height=400&id=3fc83d6c-0a9e-4f42-a2a2-7e8ba5f7d2f3&margin=%5Bobject%20Object%5D&name=3d_heatmap.png&originHeight=400&originWidth=400&originalType=binary&ratio=1&size=39874&status=done&style=none&width=400)
阅读全文