마커를 사용한 Matplotlib 시각화 사용자 정의

Beginner

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

소개

Matplotlib 는 차트, 그래프 및 플롯을 포함한 시각화를 생성하는 데 사용되는 인기 있는 Python 라이브러리입니다. Matplotlib 의 주요 구성 요소 중 하나는 플롯에서 데이터 포인트를 나타내는 데 사용되는 마커 (marker) 입니다. 마커는 다양한 모양, 크기 및 스타일로 제공되며 특정 데이터 세트에 맞게 사용자 정의할 수 있습니다. 이 랩에서는 Matplotlib 마커를 사용하여 데이터를 효과적으로 전달하는 사용자 정의 시각화를 만드는 방법을 배우게 됩니다.

VM 팁

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

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

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

채워지지 않은 마커 (Unfilled Markers)

채워지지 않은 마커는 단색입니다. 다음 코드는 채워지지 않은 마커를 만드는 방법을 보여줍니다.

unfilled_markers = [m for m, func in Line2D.markers.items()
                    if func != 'nothing' and m not in Line2D.filled_markers]

for ax, markers in zip(axs, split_list(unfilled_markers)):
    for y, marker in enumerate(markers):
        ax.text(-0.5, y, repr(marker), **text_style)
        ax.plot([y] * 3, marker=marker, **marker_style)
    format_axes(ax)

채워진 마커 (Filled Markers)

채워진 마커는 채워지지 않은 마커의 반대입니다. 다음 코드는 채워진 마커를 만드는 방법을 보여줍니다.

fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
    for y, marker in enumerate(markers):
        ax.text(-0.5, y, repr(marker), **text_style)
        ax.plot([y] * 3, marker=marker, **marker_style)
    format_axes(ax)

마커 채우기 스타일 (Marker Fill Styles)

채워진 마커의 테두리 색상과 채우기 색상은 개별적으로 지정할 수 있습니다. 또한, fillstyle은 채워지지 않음 (unfilled), 완전히 채워짐 (fully filled), 또는 다양한 방향으로 반만 채워짐 (half-filled) 으로 구성할 수 있습니다. 반만 채워진 스타일은 보조 채우기 색상으로 markerfacecoloralt를 사용합니다. 다음 코드는 마커 채우기 스타일을 만드는 방법을 보여줍니다.

fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)

filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
                           color='darkgrey',
                           markerfacecolor='tab:blue',
                           markerfacecoloralt='lightsteelblue',
                           markeredgecolor='brown')

for y, fill_style in enumerate(Line2D.fillStyles):
    ax.text(-0.5, y, repr(fill_style), **text_style)
    ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)

TeX 심볼 (TeX Symbols) 로 생성된 마커

:ref:MathText <mathtext>를 사용하여, 예를 들어 "$\u266B$"와 같은 사용자 정의 마커 심볼을 사용할 수 있습니다. STIX 폰트 심볼에 대한 개요는 STIX 폰트 테이블 <http://www.stixfonts.org/allGlyphs.html>_을 참조하십시오. 또한 :doc:/gallery/text_labels_and_annotations/stix_fonts_demo도 참조하십시오.

fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)

marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]

for y, marker in enumerate(markers):
    ## Escape dollars so that the text is written "as is", not as mathtext.
    ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
    ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)

경로 (Paths) 에서 생성된 마커

어떤 ~.path.Path도 마커로 사용할 수 있습니다. 다음 예제는 두 개의 간단한 경로인 starcircle과, 별 모양이 잘린 원의 더 정교한 경로를 보여줍니다.

import numpy as np

import matplotlib.path as mpath

star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
## concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
    vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
    codes=np.concatenate([circle.codes, star.codes]))

fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)

markers = {'star': star, 'circle': circle, 'cut_star': cut_star}

for y, (name, marker) in enumerate(markers.items()):
    ax.text(-0.5, y, name, **text_style)
    ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)

변환 (Transform) 을 사용한 고급 마커 수정

마커는 MarkerStyle 생성자에 변환 (transform) 을 전달하여 수정할 수 있습니다. 다음 예제는 제공된 회전이 여러 마커 모양에 어떻게 적용되는지 보여줍니다.

common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]

fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)

ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)

ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)

ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    eq = r'$\frac{1}{x}$'
    ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)

for x, theta in enumerate(angles):
    ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)

fig.tight_layout()

마커 캡 스타일 (Cap Style) 및 조인 스타일 (Join Style) 설정

마커는 기본 캡 스타일과 조인 스타일을 가지고 있지만, MarkerStyle을 생성할 때 이를 사용자 정의할 수 있습니다.

from matplotlib.markers import CapStyle, JoinStyle

marker_inner = dict(markersize=35,
                    markerfacecolor='tab:blue',
                    markerfacecoloralt='lightsteelblue',
                    markeredgecolor='brown',
                    markeredgewidth=8,
                    )

marker_outer = dict(markersize=35,
                    markerfacecolor='tab:blue',
                    markerfacecoloralt='lightsteelblue',
                    markeredgecolor='white',
                    markeredgewidth=1,
                    )

fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)

for y, cap_style in enumerate(CapStyle):
    ax.text(-0.5, y, cap_style.name, **text_style)
    for x, theta in enumerate(angles):
        t = Affine2D().rotate_deg(theta)
        m = MarkerStyle('1', transform=t, capstyle=cap_style)
        ax.plot(x, y, marker=m, **marker_inner)
        ax.plot(x, y, marker=m, **marker_outer)
        ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)

조인 스타일 (Join Style) 수정

마커의 조인 스타일도 유사한 방식으로 수정할 수 있습니다.

fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)

for y, join_style in enumerate(JoinStyle):
    ax.text(-0.5, y, join_style.name, **text_style)
    for x, theta in enumerate(angles):
        t = Affine2D().rotate_deg(theta)
        m = MarkerStyle('*', transform=t, joinstyle=join_style)
        ax.plot(x, y, marker=m, **marker_inner)
        ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)

plt.show()

요약

이 랩에서는 Matplotlib 마커를 사용하여 사용자 정의 시각화를 만드는 방법을 배웠습니다. 구체적으로, 채워지지 않은 마커와 채워진 마커, 마커 채우기 스타일, TeX 기호로 생성된 마커, 경로로 생성된 마커, 변환 (transform) 을 사용한 고급 마커 수정, 그리고 마커 캡 스타일 (cap style) 및 조인 스타일 (join style) 을 설정하는 방법을 배웠습니다. 이러한 기술을 사용하여 데이터를 명확하고 정확하게 전달하는 효과적인 시각화를 만들 수 있습니다.