Matplotlib 스타일 시트

Beginner

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

소개

Matplotlib 는 Python 에서 강력한 데이터 시각화 라이브러리입니다. 산점도, 히스토그램, 막대 그래프 등 다양한 플롯을 생성할 수 있습니다. 스타일 시트 참조 스크립트는 공통 예제 플롯 세트에서 사용 가능한 다양한 스타일 시트를 보여줍니다. 이 랩에서는 Matplotlib 스타일 시트를 사용하여 플롯의 모양을 사용자 정의하는 방법을 배우게 됩니다.

VM 팁

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

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

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

라이브러리 가져오기

시작하기 전에 필요한 라이브러리를 가져와야 합니다. 이 랩에서는 Matplotlib 와 NumPy 를 사용합니다.

import matplotlib.pyplot as plt
import numpy as np

플롯 함수 정의

다음으로, 예제 플롯을 생성하는 데 사용될 플롯 함수를 정의해야 합니다. 이 단계에서는 다음 플롯 함수를 정의합니다.

  • plot_scatter(): 산점도 생성
  • plot_colored_lines(): 스타일 색상 순환에 따라 색상이 있는 선을 플롯
  • plot_bar_graphs(): 막대 그래프 생성
  • plot_colored_circles(): 원형 패치 플롯
  • plot_image_and_patch(): 원형 패치가 있는 이미지 플롯
  • plot_histograms(): 히스토그램 생성
def plot_scatter(ax, prng, nb_samples=100):
    """Scatter plot."""
    for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1., 's')]:
        x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))
        ax.plot(x, y, ls='none', marker=marker)
    ax.set_xlabel('X-label')
    ax.set_title('Axes title')
    return ax


def plot_colored_lines(ax):
    """Plot lines with colors following the style color cycle."""
    t = np.linspace(-10, 10, 100)

    def sigmoid(t, t0):
        return 1 / (1 + np.exp(-(t - t0)))

    nb_colors = len(plt.rcParams['axes.prop_cycle'])
    shifts = np.linspace(-5, 5, nb_colors)
    amplitudes = np.linspace(1, 1.5, nb_colors)
    for t0, a in zip(shifts, amplitudes):
        ax.plot(t, a * sigmoid(t, t0), '-')
    ax.set_xlim(-10, 10)
    return ax


def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5):
    """Plot two bar graphs side by side, with letters as x-tick labels."""
    x = np.arange(nb_samples)
    ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples))
    width = 0.25
    ax.bar(x, ya, width)
    ax.bar(x + width, yb, width, color='C2')
    ax.set_xticks(x + width, labels=['a', 'b', 'c', 'd', 'e'])
    return ax


def plot_colored_circles(ax, prng, nb_samples=15):
    """
    Plot circle patches.

    NB: draws a fixed amount of samples, rather than using the length of
    the color cycle, because different styles may have different numbers
    of colors.
    """
    for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'](),
                           range(nb_samples)):
        ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
                                radius=1.0, color=sty_dict['color']))
    ax.grid(visible=True)

    ## Add title for enabling grid
    plt.title('ax.grid(True)', family='monospace', fontsize='small')

    ax.set_xlim([-4, 8])
    ax.set_ylim([-5, 6])
    ax.set_aspect('equal', adjustable='box')  ## to plot circles as circles
    return ax


def plot_image_and_patch(ax, prng, size=(20, 20)):
    """Plot an image with random values and superimpose a circular patch."""
    values = prng.random_sample(size=size)
    ax.imshow(values, interpolation='none')
    c = plt.Circle((5, 5), radius=5, label='patch')
    ax.add_patch(c)
    ## Remove ticks
    ax.set_xticks([])
    ax.set_yticks([])


def plot_histograms(ax, prng, nb_samples=10000):
    """Plot 4 histograms and a text annotation."""
    params = ((10, 10), (4, 12), (50, 12), (6, 55))
    for a, b in params:
        values = prng.beta(a, b, size=nb_samples)
        ax.hist(values, histtype="stepfilled", bins=30,
                alpha=0.8, density=True)

    ## Add a small annotation.
    ax.annotate('Annotation', xy=(0.25, 4.25),
                xytext=(0.9, 0.9), textcoords=ax.transAxes,
                va="top", ha="right",
                bbox=dict(boxstyle="round", alpha=0.2),
                arrowprops=dict(
                          arrowstyle="->",
                          connectionstyle="angle,angleA=-95,angleB=35,rad=10"),
                )
    return ax

플롯 함수 정의

이제, 주어진 스타일로 데모 그림을 설정하고 플롯하는 plot_figure() 함수를 정의해야 합니다. 이 함수는 2 단계에서 정의된 각 플롯 함수를 호출합니다.

def plot_figure(style_label=""):
    """Setup and plot the demonstration figure with a given style."""
    ## Use a dedicated RandomState instance to draw the same "random" values
    ## across the different figures.
    prng = np.random.RandomState(96917002)

    fig, axs = plt.subplots(ncols=6, nrows=1, num=style_label,
                            figsize=(14.8, 2.8), layout='constrained')

    ## make a suptitle, in the same style for all subfigures,
    ## except those with dark backgrounds, which get a lighter color:
    background_color = mcolors.rgb_to_hsv(
        mcolors.to_rgb(plt.rcParams['figure.facecolor']))[2]
    if background_color < 0.5:
        title_color = [0.8, 0.8, 1]
    else:
        title_color = np.array([19, 6, 84]) / 256
    fig.suptitle(style_label, x=0.01, ha='left', color=title_color,
                 fontsize=14, fontfamily='DejaVu Sans', fontweight='normal')

    plot_scatter(axs[0], prng)
    plot_image_and_patch(axs[1], prng)
    plot_bar_graphs(axs[2], prng)
    plot_colored_lines(axs[3])
    plot_histograms(axs[4], prng)
    plot_colored_circles(axs[5], prng)

    ## add divider
    rec = Rectangle((1 + 0.025, -2), 0.05, 16,
                    clip_on=False, color='gray')

    axs[4].add_artist(rec)

각 스타일 시트에 대한 데모 그림 플롯

마지막으로, 사용 가능한 각 스타일 시트에 대한 데모 그림을 플롯해야 합니다. style_list를 반복하고 각 스타일 시트에 대해 plot_figure() 함수를 호출하여 이 작업을 수행할 수 있습니다.

if __name__ == "__main__":

    ## Set up a list of all available styles, in alphabetical order but
    ## the `default` and `classic` ones, which will be forced resp. in
    ## first and second position.
    ## styles with leading underscores are for internal use such as testing
    ## and plot types gallery. These are excluded here.
    style_list = ['default', 'classic'] + sorted(
        style for style in plt.style.available
        if style != 'classic' and not style.startswith('_'))

    ## Plot a demonstration figure for every available style sheet.
    for style_label in style_list:
        with plt.rc_context({"figure.max_open_warning": len(style_list)}):
            with plt.style.context(style_label):
                plot_figure(style_label=style_label)

    plt.show()

요약

이 랩에서는 Matplotlib 스타일 시트를 사용하여 플롯의 모양을 사용자 정의하는 방법을 배웠습니다. 플롯 함수를 정의하고 이를 사용하여 주어진 스타일 시트로 데모 그림을 만드는 방법을 배웠습니다. 이 랩에 설명된 단계를 따르면, Matplotlib 스타일 시트를 자체 플롯에 적용하여 전문적인 모양의 데이터 시각화를 만들 수 있습니다.