Matplotlib 리본 박스 차트

Beginner

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

소개

Matplotlib 는 Python 을 위한 인기 있는 데이터 시각화 라이브러리입니다. 이 튜토리얼은 데이터를 시각화하는 독특한 방법인 리본 박스 차트 (ribbon box chart) 를 만드는 과정을 안내합니다. 리본 박스 차트는 각 막대가 "리본 모양"이고 그라데이션 색상 체계를 갖는 누적 막대 차트입니다.

VM 팁

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

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

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

라이브러리 임포트 및 데이터 로딩

이 단계에서는 필요한 라이브러리를 임포트하고 데이터를 로드합니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from matplotlib import colors as mcolors
from matplotlib.image import AxesImage
from matplotlib.transforms import Bbox, BboxTransformTo, TransformedBbox

RibbonBox 클래스 생성

이 단계에서는 리본 박스에 대한 그라데이션 색상을 생성하는 데 사용될 RibbonBox 클래스를 생성합니다.

class RibbonBox:
    ## Load the ribbon box image
    original_image = plt.imread(cbook.get_sample_data("Minduka_Present_Blue_Pack.png"))
    cut_location = 70
    b_and_h = original_image[:, :, 2:3]
    color = original_image[:, :, 2:3] - original_image[:, :, 0:1]
    alpha = original_image[:, :, 3:4]
    nx = original_image.shape[1]

    def __init__(self, color):
        rgb = mcolors.to_rgb(color)
        self.im = np.dstack([self.b_and_h - self.color * (1 - np.array(rgb)), self.alpha])

    def get_stretched_image(self, stretch_factor):
        stretch_factor = max(stretch_factor, 1)
        ny, nx, nch = self.im.shape
        ny2 = int(ny*stretch_factor)
        return np.vstack([self.im[:self.cut_location],
                          np.broadcast_to(self.im[self.cut_location], (ny2 - ny, nx, nch)),
                          self.im[self.cut_location:]])

RibbonBoxImage 클래스 생성

이 단계에서는 실제 리본 박스를 생성하는 데 사용될 RibbonBoxImage 클래스를 생성합니다.

class RibbonBoxImage(AxesImage):
    zorder = 1

    def __init__(self, ax, bbox, color, *, extent=(0, 1, 0, 1), **kwargs):
        super().__init__(ax, extent=extent, **kwargs)
        self._bbox = bbox
        self._ribbonbox = RibbonBox(color)
        self.set_transform(BboxTransformTo(bbox))

    def draw(self, renderer, *args, **kwargs):
        stretch_factor = self._bbox.height / self._bbox.width

        ny = int(stretch_factor*self._ribbonbox.nx)
        if self.get_array() is None or self.get_array().shape[0] != ny:
            arr = self._ribbonbox.get_stretched_image(stretch_factor)
            self.set_array(arr)

        super().draw(renderer, *args, **kwargs)

차트 생성

이 단계에서는 RibbonBoxImage 클래스를 사용하여 실제 리본 박스를 생성하여 차트를 만듭니다.

def main():
    fig, ax = plt.subplots()

    years = np.arange(2004, 2009)
    heights = [7900, 8100, 7900, 6900, 2800]
    box_colors = [(0.8, 0.2, 0.2),
                  (0.2, 0.8, 0.2),
                  (0.2, 0.2, 0.8),
                  (0.7, 0.5, 0.8),
                  (0.3, 0.8, 0.7)]

    for year, h, bc in zip(years, heights, box_colors):
        bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
        bbox = TransformedBbox(bbox0, ax.transData)
        ax.add_artist(RibbonBoxImage(ax, bbox, bc, interpolation="bicubic"))
        ax.annotate(str(h), (year, h), va="bottom", ha="center")

    ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
    ax.set_ylim(0, 10000)

    ## Create a background gradient
    background_gradient = np.zeros((2, 2, 4))
    background_gradient[:, :, :3] = [1, 1, 0]
    background_gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]]
    ax.imshow(background_gradient, interpolation="bicubic", zorder=0.1,
              extent=(0, 1, 0, 1), transform=ax.transAxes, aspect="auto")

    plt.show()

main()

차트 이해

이 단계에서는 우리가 생성한 차트에 대해 논의합니다. 이 차트는 막대 차트를 형성하기 위해 서로 위에 쌓인 리본 박스로 구성됩니다. 각 리본 박스의 높이는 데이터 세트의 값에 해당합니다. 리본 박스는 시각적으로 매력적인 그라데이션 색상 체계를 가지고 있습니다.

요약

이 튜토리얼에서는 Matplotlib 을 사용하여 리본 박스 차트를 만드는 방법을 배웠습니다. 그라데이션 색상과 실제 리본 박스를 각각 생성하기 위해 RibbonBoxRibbonBoxImage 클래스를 만들었습니다. 그런 다음 이러한 클래스를 사용하여 막대 차트를 형성하기 위해 서로 위에 쌓인 리본 박스로 구성된 차트를 만들었습니다.