Matplotlib Figure 및 Axes Enter/Leave 이벤트

Beginner

This tutorial is from open-source community. Access the source code

소개

Matplotlib 는 Python 을 위한 데이터 시각화 라이브러리입니다. Python 에서 정적, 애니메이션, 그리고 인터랙티브 시각화를 생성하기 위한 다양한 도구를 제공합니다. Matplotlib 의 인터랙티브 기능 중 하나는 마우스가 figure 또는 axes 에 진입하고 나갈 때 감지하는 능력입니다. 이 랩에서는 Matplotlib 의 Figure 및 Axes enter/leave 이벤트를 사용하여 figure 와 axes 의 프레임 색상을 변경하는 방법을 배웁니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.

학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

Matplotlib 임포트

Matplotlib 을 사용하기 전에, 먼저 임포트해야 합니다. 또한, 플롯을 생성하기 위한 간단한 인터페이스를 제공하는 pyplot 모듈도 임포트합니다.

import matplotlib.pyplot as plt

Figure 및 Axes 생성

subplots 함수를 사용하여 두 개의 서브플롯 (axes) 이 있는 figure 를 생성합니다. 또한 figure 의 제목을 설정합니다.

fig, axs = plt.subplots(2, 1)
fig.suptitle('Mouse Hover Over Figure or Axes to Trigger Events')

이벤트 핸들러 정의

이제 네 개의 이벤트 핸들러 함수, on_enter_axes, on_leave_axes, on_enter_figure, 그리고 on_leave_figure를 정의합니다. 이 함수들은 마우스가 axes 또는 figure 에 들어가거나 나갈 때 호출됩니다.

def on_enter_axes(event):
    print('enter_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('yellow')
    event.canvas.draw()

def on_leave_axes(event):
    print('leave_axes', event.inaxes)
    event.inaxes.patch.set_facecolor('white')
    event.canvas.draw()

def on_enter_figure(event):
    print('enter_figure', event.canvas.figure)
    event.canvas.figure.patch.set_facecolor('red')
    event.canvas.draw()

def on_leave_figure(event):
    print('leave_figure', event.canvas.figure)
    event.canvas.figure.patch.set_facecolor('grey')
    event.canvas.draw()

이벤트 핸들러를 Figure Canvas 에 연결

이제 mpl_connect 메서드를 사용하여 이벤트 핸들러를 figure canvas 에 연결합니다. 이렇게 하면 마우스가 figure 또는 axes 에 들어가거나 나갈 때 이벤트 핸들러가 트리거됩니다.

fig.canvas.mpl_connect('figure_enter_event', on_enter_figure)
fig.canvas.mpl_connect('figure_leave_event', on_leave_figure)
fig.canvas.mpl_connect('axes_enter_event', on_enter_axes)
fig.canvas.mpl_connect('axes_leave_event', on_leave_axes)

Figure 표시

이제 show 함수를 사용하여 figure 를 표시합니다.

plt.show()

요약

이 랩에서는 Matplotlib 의 Figure 및 Axes enter/leave 이벤트를 사용하여 figure 와 axes 의 프레임 색상을 변경하는 방법을 배웠습니다. 두 개의 서브플롯 (subplot) 이 있는 figure 를 생성하고, figure 와 axes 의 진입 및 이탈에 대한 이벤트 핸들러 함수를 정의했으며, 이벤트 핸들러를 figure canvas 에 연결하고 figure 를 표시했습니다.