练习利用matplotlib库画三维曲面图、雷达图等
时间: 2024-09-30 08:16:43 浏览: 41
`matplotlib`是一个强大的数据可视化库,用于Python,它支持创建各种类型的图表,包括三维图形。下面我会简单讲解如何使用`matplotlib`及其姐妹库`mpl_toolkits.mplot3d`来绘制三维曲面图和雷达图。
**三维曲面图**:
要绘制三维曲面图,你需要先导入`matplotlib.pyplot`和`mpl_toolkits.mplot3d`模块,然后创建一个`Axes3D`对象。这里以绘制一个简单的二维函数z=f(x,y)为例:
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 定义x和y网格
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# 定义函数z = x^2 + y^2
Z = X**2 + Y**2
# 创建3D图像
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis') # 使用颜色映射
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
```
**雷达图**:
雷达图是一种用于比较多维度数据的特殊形式的折线图。首先需要`matplotlib.ticker`和`matplotlib.collections`。以下是如何制作雷达图的例子:
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
def radar_factory(n):
d = np.array([0] * n)
angles = [2*np.pi*i/n for i in range(n)]
codes = [(Path.MOVETO, (0,0))] + [(Path.LINETO, point) for point in zip(np.cos(angles), np.sin(angles))]
path = Path(codes)
return path, angles
def plot_radar(ax, angles, values, labels=None, **kwargs):
if labels is None:
labels = ['Dim {}'.format(i+1) for i in range(len(values[0]))]
path, angles = radar_factory(len(values))
patch = PathPatch(path, facecolor='w', edgecolor='k', lw=2)
ax.add_patch(patch)
ax.set_thetagrids(angles * 180/np.pi, labels, radius=1.1)
ax.axis('equal') # Equal aspect ratio ensures that circles are drawn as circles.
ax.set_rlabel_position(90) # Move radial labels away from plotted line
# Plot data
lines = ax.plot(angles * np.ones_like(values), values, **kwargs)
ax.fill(angles * np.ones_like(values), values, alpha=0.25)
# 示例
values = [[4, 6, 7, 8, 5], [2, 3, 5, 7, 6]]
plot_radar(ax, angles=np.arange(5), values=values, label=['A', 'B'], linestyle='--', linewidth=2)
plt.title("Radar Chart")
plt.show()
```
阅读全文