简介
在本实验中,你将学习如何使用 Python 的 Matplotlib 库创建雷达图。雷达图,也称为蜘蛛图或星图,是一种以二维图表形式显示多变量数据的图形方法,该图表由三个或更多定量变量组成,这些变量从同一点开始在坐标轴上表示。它通常用于根据多个因素比较不同的产品或解决方案。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入库
首先,我们需要导入必要的库。本教程需要 Matplotlib 和 numpy。
import matplotlib.pyplot as plt
import numpy as np
定义雷达图函数
接下来,我们将定义一个创建雷达图的函数。这个函数将接受两个参数:num_vars 和 frame。num_vars 是雷达图的变量数量,frame 指定围绕坐标轴的框架形状。
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections import register_projection
from matplotlib.projections.polar import PolarAxes
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D
def radar_factory(num_vars, frame='circle'):
## 函数的代码写在这里
定义雷达变换和雷达轴类
在 radar_factory 函数中,我们将定义 RadarTransform 和 RadarAxes 类。这些类将用于创建雷达图。
class RadarTransform(PolarAxes.PolarTransform):
## RadarTransform 类的代码写在这里
class RadarAxes(PolarAxes):
## RadarAxes 类的代码写在这里
定义 fill 和 plot 方法
在 RadarAxes 类中,我们将定义 fill 和 plot 方法。这些方法将分别用于填充图表内部的区域和绘制数据点。
class RadarAxes(PolarAxes):
## RadarAxes 类的代码写在这里
def fill(self, *args, closed=True, **kwargs):
## 重写 fill 方法
return super().fill(closed=closed, *args, **kwargs)
def plot(self, *args, **kwargs):
## 重写 plot 方法
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.append(x, x[0])
y = np.append(y, y[0])
line.set_data(x, y)
定义 set_varlabels、_gen_axes_patch 和 _gen_axes_spines 方法
在 RadarAxes 类中,我们还将定义 set_varlabels、_gen_axes_patch 和 _gen_axes_spines 方法。这些方法将分别用于设置变量标签、生成坐标轴补丁以及生成坐标轴脊线。
class RadarAxes(PolarAxes):
## RadarAxes 类的代码写在这里
def set_varlabels(self, labels):
self.set_thetagrids(np.degrees(theta), labels)
def _gen_axes_patch(self):
if frame == 'circle':
return Circle((0.5, 0.5), 0.5)
elif frame == 'polygon':
return RegularPolygon((0.5, 0.5), num_vars,
radius=.5, edgecolor="k")
else:
raise ValueError("Unknown value for 'frame': %s" % frame)
def _gen_axes_spines(self):
if frame == 'circle':
return super()._gen_axes_spines()
elif frame == 'polygon':
spine = Spine(axes=self,
spine_type='circle',
path=Path.unit_regular_polygon(num_vars))
spine.set_transform(Affine2D().scale(.5).translate(.5,.5)
+ self.transAxes)
return {'polar': spine}
else:
raise ValueError("Unknown value for 'frame': %s" % frame)
定义示例数据
现在,我们将定义用于创建雷达图的示例数据。此数据取自一项关于污染源特征估计的研究。
def example_data():
data = [
['硫酸盐', '硝酸盐', '元素碳', '有机碳 1', '有机碳 2', '有机碳 3', '有机磷', '一氧化碳', '臭氧'],
('基础情况', [
[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
[0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
[0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
[0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
[0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),
('含一氧化碳', [
[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],
[0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],
[0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],
[0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],
[0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),
('含臭氧', [
[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],
[0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],
[0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],
[0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],
[0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),
('一氧化碳和臭氧', [
[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],
[0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],
[0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],
[0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],
[0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])
]
return data
设置变量数量并计算轴角度
现在我们将设置变量的数量,并使用 numpy 计算等间距的轴角度。
N = 9
theta = radar_factory(N, frame='polygon')
创建雷达图
最后,我们可以使用示例数据和 RadarAxes 类来创建雷达图。
data = example_data()
spoke_labels = data.pop(0)
fig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,
subplot_kw=dict(projection='radar'))
fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
colors = ['b', 'r', 'g','m', 'y']
for ax, (title, case_data) in zip(axs.flat, data):
ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
horizontalalignment='center', verticalalignment='center')
for d, color in zip(case_data, colors):
ax.plot(theta, d, color=color)
ax.fill(theta, d, facecolor=color, alpha=0.25, label='_nolegend_')
ax.set_varlabels(spoke_labels)
labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
legend = axs[0, 0].legend(labels, loc=(0.9,.95),
labelspacing=0.1, fontsize='small')
fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
horizontalalignment='center', color='black', weight='bold',
size='large')
plt.show()
总结
在本实验中,你学习了如何使用 Python 的 Matplotlib 库创建雷达图。雷达图是一种以二维图表形式展示多变量数据的图形方法,这些数据由三个或更多从同一点出发的轴上表示的定量变量组成。它常用于基于多个因素比较不同的产品或解决方案。