소개
이 랩은 matplotlib 패치를 마우스 오버했을 때 나타나는 툴팁을 만드는 방법에 대한 단계별 튜토리얼입니다. matplotlib 에서 툴팁을 생성하고, 패치 위에 마우스를 올리면 툴팁의 표시 여부를 토글합니다. 이 접근 방식은 툴팁 배치 및 모양을 완벽하게 제어할 수 있지만, 초기 코드 작성이 더 필요합니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
패치 생성
먼저 툴팁이 할당될 패치를 생성합니다.
rect1 = plt.Rectangle((10, -20), 10, 5, fc='blue')
rect2 = plt.Rectangle((-20, 15), 10, 5, fc='green')
shapes = [rect1, rect2]
labels = ['This is a blue rectangle.', 'This is a green rectangle']
패치 및 툴팁 주석 추가
그런 다음 패치와 툴팁 주석을 플롯에 추가합니다. 툴팁 주석은 annotate 메서드를 사용하여 생성됩니다. xy 매개변수를 패치의 좌표로 설정하고, xytext를 (0, 0)으로 설정하여 툴팁을 패치 바로 위에 배치합니다. 또한 textcoords 매개변수를 'offset points'로 설정하여 툴팁을 패치에 정렬합니다. color 매개변수를 'w'로 설정하여 텍스트를 흰색으로 만들고, ha를 'center'로 설정하여 텍스트를 가로로 가운데 정렬하며, fontsize를 8로 설정하여 글꼴 크기를 설정하고, bbox를 사용하여 툴팁 상자의 스타일을 설정합니다.
for i, (item, label) in enumerate(zip(shapes, labels)):
patch = ax.add_patch(item)
annotate = ax.annotate(labels[i], xy=item.get_xy(), xytext=(0, 0),
textcoords='offset points', color='w', ha='center',
fontsize=8, bbox=dict(boxstyle='round, pad=.5',
fc=(.1, .1, .1, .92),
ec=(1., 1., 1.), lw=1,
zorder=1))
ax.add_patch(patch)
patch.set_gid(f'mypatch_{i:03d}')
annotate.set_gid(f'mytooltip_{i:03d}')
그림을 SVG 로 저장
BytesIO 클래스와 savefig 메서드를 사용하여 가짜 파일 객체에 그림을 저장합니다.
ax.set_xlim(-30, 30)
ax.set_ylim(-30, 30)
ax.set_aspect('equal')
f = BytesIO()
plt.savefig(f, format="svg")
상호 작용 추가
패치 위에 마우스를 올릴 때 켜고 끌 수 있는 툴팁을 생성하여 플롯에 상호 작용을 추가합니다. SVG 파일에서 XML 트리를 생성하고, 툴팁을 숨기고, onmouseover 및 onmouseout 콜백을 패치에 할당하여 이를 수행합니다. 또한 패치 위에 마우스를 올릴 때 호출될 ShowTooltip 및 HideTooltip 함수를 정의합니다.
tree, xmlid = ET.XMLID(f.getvalue())
tree.set('onload', 'init(event)')
for i in shapes:
## Get the index of the shape
index = shapes.index(i)
## Hide the tooltips
tooltip = xmlid[f'mytooltip_{index:03d}']
tooltip.set('visibility', 'hidden')
## Assign onmouseover and onmouseout callbacks to patches.
mypatch = xmlid[f'mypatch_{index:03d}']
mypatch.set('onmouseover', "ShowTooltip(this)")
mypatch.set('onmouseout', "HideTooltip(this)")
## This is the script defining the ShowTooltip and HideTooltip functions.
script = """
<script type="text/ecmascript">
<![CDATA[
function init(event) {
if ( window.svgDocument == null ) {
svgDocument = event.target.ownerDocument;
}
}
function ShowTooltip(obj) {
var cur = obj.id.split("_")[1];
var tip = svgDocument.getElementById('mytooltip_' + cur);
tip.setAttribute('visibility', "visible")
}
function HideTooltip(obj) {
var cur = obj.id.split("_")[1];
var tip = svgDocument.getElementById('mytooltip_' + cur);
tip.setAttribute('visibility', "hidden")
}
]]>
</script>
"""
## Insert the script at the top of the file and save it.
tree.insert(0, ET.XML(script))
ET.ElementTree(tree).write('svg_tooltip.svg')
요약
이 랩에서는 matplotlib 패치 위에 마우스를 올릴 때 표시되는 툴팁을 만드는 방법을 배웠습니다. matplotlib 에서 툴팁을 생성하고 패치 위에 마우스를 올릴 때 해당 가시성을 단순히 토글했습니다. 또한 패치 위에 마우스를 올릴 때 켜고 끌 수 있는 툴팁을 생성하여 플롯에 상호 작용을 추가했습니다.