소개
이 랩에서는 Python 의 Matplotlib 라이브러리를 사용하여 레이더 차트를 만드는 방법을 배우게 됩니다. 레이더 차트는 스파이더 차트 또는 스타 차트라고도 하며, 동일한 지점에서 시작하는 축에 표시되는 세 개 이상의 정량적 변수의 2 차원 차트 형태로 다변량 데이터를 표시하는 그래픽 방법입니다. 여러 요소를 기반으로 다양한 제품 또는 솔루션을 비교하는 데 자주 사용됩니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 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'):
## code for the function goes here
레이더 변환 및 레이더 축 클래스 정의
radar_factory 함수 내에서 RadarTransform 및 RadarAxes 클래스를 정의합니다. 이 클래스는 레이더 차트를 생성하는 데 사용됩니다.
class RadarTransform(PolarAxes.PolarTransform):
## code for the RadarTransform class goes here
class RadarAxes(PolarAxes):
## code for the RadarAxes class goes here
fill 및 plot 메서드 정의
RadarAxes 클래스 내에서 fill 및 plot 메서드를 정의합니다. 이 메서드는 각각 차트 내부 영역을 채우고 데이터 포인트를 플롯하는 데 사용됩니다.
class RadarAxes(PolarAxes):
## code for the RadarAxes class goes here
def fill(self, *args, closed=True, **kwargs):
## override the fill method
return super().fill(closed=closed, *args, **kwargs)
def plot(self, *args, **kwargs):
## override the plot method
lines = super().plot(*args, **kwargs)
for line in lines:
self._close_line(line)
def _close_line(self, line):
## helper method to close the 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):
## code for the RadarAxes class goes here
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 = [
['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
('Basecase', [
[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]]),
('With CO', [
[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]]),
('With O3', [
[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]]),
('CO & O3', [
[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 라이브러리를 사용하여 레이더 차트를 만드는 방법을 배웠습니다. 레이더 차트는 동일한 지점에서 시작하는 축에 표시되는 세 개 이상의 정량적 변수의 2 차원 차트 형태로 다변량 데이터를 표시하는 그래픽 방법입니다. 여러 요소를 기반으로 다양한 제품 또는 솔루션을 비교하는 데 자주 사용됩니다.