### 如何使用 Python 的 Matplotlib 库绘制雷达图
以下是通过 `Matplotlib` 绘制雷达图的具体方法以及完整的代码示例:
#### 创建图形并设置极坐标
为了绘制雷达图,首先需要创建一个具有极坐标的子图。这可以通过在 `subplot()` 函数中将参数 `polar=True` 设置实现[^3]。
#### 添加多边形区域和连线
雷达图通常由多个顶点组成一个多边形,并且这些顶点之间需要用线条连接起来。可以利用 `fill()` 或者 `plot()` 方法完成这一操作[^2]。
#### 定义标签与数值轴
定义一组标签用于描述每个维度的意义;同时还需要指定对应于各个维度上的具体取值范围。这样可以让读者更清楚地理解所展示的信息内容[^1]。
下面是具体的代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
def radar_factory(num_vars, frame='circle'):
"""Create a radar chart with `num_vars` axes."""
theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False)
class RadarAxes(ax.Axes):
name = 'radar'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_theta_zero_location('N')
def fill(self, *args, closed=True, **kwargs):
return super().fill(closed=closed, *args, **kwargs)
def plot(self, *args, **kwargs):
lines = super().plot(*args, **kwargs)
for line in lines:
self._close_line(line)
def _close_line(self, line):
x, y = line.get_data()
if x[0] != x[-1]:
x = np.concatenate((x, [x[0]]))
y = np.concatenate((y, [y[0]]))
line.set_data(x, y)
register_projection(RadarAxes)
return theta
data = [
['Strength', 'Speed', 'Intelligence', 'Stamina'],
('Base Stats', [[7], [8], [6], [9]])
]
N = len(data[0])
theta = radar_factory(N, frame='polygon')
spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(projection='radar'))
ax.set_ylim(-1, 10)
ax.set_rgrids([2, 4, 6, 8])
ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
horizontalalignment='center', verticalalignment='center')
for d in case_data:
ax.plot(theta, d, '-')
ax.fill(theta, d, alpha=0.25)
ax.set_varlabels(spoke_labels)
plt.show()
```
上述脚本展示了如何构建基本的雷达图结构,并填充颜色以突出显示不同类别之间的差异。