Matplotlib 곡선형 그리드

Beginner

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

소개

이 랩에서는 GridHelperCurveLinear를 사용하여 Matplotlib 에서 사용자 정의 그리드와 눈금선을 만드는 방법을 배웁니다. 또한 직사각형 상자 내에서 극좌표 투영법 (polar projection) 을 만드는 방법도 배웁니다.

VM 팁

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

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

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

사용자 정의 변환을 위한 그리드

먼저, GridHelperCurveLinear를 사용하여 사용자 정의 그리드와 눈금선을 생성합니다. 사용자 정의 변환은 그리드와 눈금선에 적용됩니다. 다음 코드는 이 과정을 보여줍니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import Axes, HostAxes, angle_helper
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear

def curvelinear_test1(fig):
    ## Define custom transform
    def tr(x, y):
        return x, y - x
    def inv_tr(x, y):
        return x, y + x

    ## Create GridHelperCurveLinear object
    grid_helper = GridHelperCurveLinear((tr, inv_tr))

    ## Create a subplot with the custom grid and tick lines
    ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)

    ## Plot some points on the subplot
    xx, yy = tr(np.array([3, 6]), np.array([5, 10]))
    ax1.plot(xx, yy)

    ## Set the aspect ratio and limits of the subplot
    ax1.set_aspect(1)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ## Add floating axes and grid lines
    ax1.axis["t"] = ax1.new_floating_axis(0, 3)
    ax1.axis["t2"] = ax1.new_floating_axis(1, 7)
    ax1.grid(True, zorder=0)

fig = plt.figure(figsize=(7, 4))
curvelinear_test1(fig)
plt.show()

직사각형 상자 내의 극좌표 투영법

다음으로, GridHelperCurveLinear를 사용하여 직사각형 상자 내에서 극좌표 투영법을 생성합니다. Affine2D 변환을 사용하여 각도 좌표를 라디안으로 스케일링하고, PolarAxes.PolarTransform을 사용하여 극좌표 투영법을 생성합니다. 또한 angle_helper.ExtremeFinderCycle을 사용하여 극좌표 투영법의 극값을 찾고, angle_helper.LocatorDMSangle_helper.FormatterDMS를 사용하여 눈금 레이블의 형식을 지정합니다. 다음 코드는 이 과정을 보여줍니다.

def curvelinear_test2(fig):
    ## Define the custom transform
    tr = Affine2D().scale(np.pi/180, 1) + PolarAxes.PolarTransform()

    ## Define the extreme finder, grid locator, and tick formatter
    extreme_finder = angle_helper.ExtremeFinderCycle(
        nx=20, ny=20,
        lon_cycle=360, lat_cycle=None,
        lon_minmax=None, lat_minmax=(0, np.inf),
    )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    ## Create GridHelperCurveLinear object
    grid_helper = GridHelperCurveLinear(
        tr, extreme_finder=extreme_finder,
        grid_locator1=grid_locator1, tick_formatter1=tick_formatter1)
    ax1 = fig.add_subplot(
        1, 2, 2, axes_class=HostAxes, grid_helper=grid_helper)

    ## Make ticklabels of right and top axis visible
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    ## Let right axis show ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0

    ## Let bottom axis show ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    ## Set the aspect ratio and limits of the subplot
    ax1.set_aspect(1)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ## Add grid lines to the subplot
    ax1.grid(True, zorder=0)

    ## Create a parasite axes with the given transform
    ax2 = ax1.get_aux_axes(tr)

    ## Anything you draw in ax2 will match the ticks and grids of ax1.
    ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)

    ax2.pcolor(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
               np.arange(9).reshape((3, 3)))
    ax2.contour(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
                np.arange(16).reshape((4, 4)), colors="k")

fig = plt.figure(figsize=(7, 4))
curvelinear_test2(fig)
plt.show()

최종 코드

최종 코드는 1 단계와 2 단계의 코드를 결합합니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import Axes, HostAxes, angle_helper
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear

def curvelinear_test1(fig):
    ## Define custom transform
    def tr(x, y):
        return x, y - x
    def inv_tr(x, y):
        return x, y + x

    ## Create GridHelperCurveLinear object
    grid_helper = GridHelperCurveLinear((tr, inv_tr))

    ## Create a subplot with the custom grid and tick lines
    ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)

    ## Plot some points on the subplot
    xx, yy = tr(np.array([3, 6]), np.array([5, 10]))
    ax1.plot(xx, yy)

    ## Set the aspect ratio and limits of the subplot
    ax1.set_aspect(1)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ## Add floating axes and grid lines
    ax1.axis["t"] = ax1.new_floating_axis(0, 3)
    ax1.axis["t2"] = ax1.new_floating_axis(1, 7)
    ax1.grid(True, zorder=0)

def curvelinear_test2(fig):
    ## Define the custom transform
    tr = Affine2D().scale(np.pi/180, 1) + PolarAxes.PolarTransform()

    ## Define the extreme finder, grid locator, and tick formatter
    extreme_finder = angle_helper.ExtremeFinderCycle(
        nx=20, ny=20,
        lon_cycle=360, lat_cycle=None,
        lon_minmax=None, lat_minmax=(0, np.inf),
    )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    ## Create GridHelperCurveLinear object
    grid_helper = GridHelperCurveLinear(
        tr, extreme_finder=extreme_finder,
        grid_locator1=grid_locator1, tick_formatter1=tick_formatter1)
    ax1 = fig.add_subplot(
        1, 2, 2, axes_class=HostAxes, grid_helper=grid_helper)

    ## Make ticklabels of right and top axis visible
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    ## Let right axis show ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0

    ## Let bottom axis show ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    ## Set the aspect ratio and limits of the subplot
    ax1.set_aspect(1)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ## Add grid lines to the subplot
    ax1.grid(True, zorder=0)

    ## Create a parasite axes with the given transform
    ax2 = ax1.get_aux_axes(tr)

    ## Anything you draw in ax2 will match the ticks and grids of ax1.
    ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)

    ax2.pcolor(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
               np.arange(9).reshape((3, 3)))
    ax2.contour(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
                np.arange(16).reshape((4, 4)), colors="k")

fig = plt.figure(figsize=(7, 4))
curvelinear_test1(fig)
curvelinear_test2(fig)
plt.show()

요약

이 랩에서는 GridHelperCurveLinear를 사용하여 사용자 정의 그리드 및 눈금선을 만드는 방법을 배웠습니다. 또한 Affine2D, PolarAxes.PolarTransform, 그리고 GridHelperCurveLinear를 사용하여 직사각형 상자 내에서 극좌표 투영법을 생성하는 방법도 배웠습니다.