소개
Matplotlib 는 Python 에서 시각화를 생성하기 위한 강력한 라이브러리입니다. 때로는 그래프를 생성할 때 서브플롯 (subplot) 매개변수를 수동으로 조정해야 할 수 있습니다. 이 랩에서는 레이블의 크기에 따라 프로그래밍 방식으로 서브플롯 매개변수를 조정하는 방법을 보여줍니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.
필요한 라이브러리 가져오기
그래프를 생성하고 서브플롯 매개변수를 조작하려면 matplotlib.pyplot 및 matplotlib.transforms가 필요합니다.
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
그래프 생성
몇 개의 긴 y-레이블이 있는 간단한 선 그래프를 만들어 보겠습니다.
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_yticks([2, 5, 7], labels=['really, really, really', 'long', 'labels'])
draw 콜백 함수 정의
그래프가 그려질 때마다 호출될 함수를 정의합니다. 이 함수는 y-레이블의 경계 상자 (bounding box) 를 계산하고, 서브플롯이 레이블을 위한 충분한 공간을 남겨두는지 확인하며, 필요한 경우 서브플롯 매개변수를 조정합니다.
def on_draw(event):
bboxes = []
for label in ax.get_yticklabels():
## Bounding box in pixels
bbox_px = label.get_window_extent()
## Transform to relative figure coordinates. This is the inverse of
## transFigure.
bbox_fig = bbox_px.transformed(fig.transFigure.inverted())
bboxes.append(bbox_fig)
## the bbox that bounds all the bboxes, again in relative figure coords
bbox = mtransforms.Bbox.union(bboxes)
if fig.subplotpars.left < bbox.width:
## Move the subplot left edge more to the right
fig.subplots_adjust(left=1.1*bbox.width) ## pad a little
fig.canvas.draw()
draw 이벤트 (event) 를 콜백 함수에 연결
draw_event를 on_draw 함수에 연결해야 합니다.
fig.canvas.mpl_connect('draw_event', on_draw)
그래프 표시
마지막으로, 그래프를 표시합니다.
plt.show()
요약
이 랩에서는 레이블 크기에 따라 프로그래밍 방식으로 서브플롯 (subplot) 매개변수를 조정하는 방법을 배웠습니다. matplotlib.transforms 모듈을 사용하여 레이블의 경계 상자 (bounding box) 를 계산하고, draw_event를 사용하여 on_draw 함수를 호출했습니다.