Hat 그래프 생성하기

Beginner

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

소개

이 랩에서는 Matplotlib 라이브러리를 사용하여 Python 에서 Hat 그래프를 만드는 방법을 배웁니다. Hat 그래프는 스택 막대 차트의 변형으로, 각 막대가 모자 모양을 갖습니다. 게임 수와 플레이어별 점수 데이터 세트를 사용하여 그래프를 생성합니다.

VM 팁

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

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

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

라이브러리 가져오기

이 단계에서는 Hat 그래프를 생성하는 데 필요한 라이브러리를 가져오겠습니다.

import matplotlib.pyplot as plt
import numpy as np

Hat 그래프 함수 정의

이 단계에서는 Hat 그래프를 생성하는 함수를 정의합니다. 이 함수는 다음과 같은 매개변수를 사용합니다.

  • ax: 플롯할 Axes (축).
  • xlabels: x 축에 표시될 범주 이름.
  • values: 데이터 값. 행은 그룹이고, 열은 범주입니다.
  • group_labels: 범례에 표시될 그룹 레이블.
def hat_graph(ax, xlabels, values, group_labels):
    """
    Hat 그래프를 생성합니다.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        플롯할 Axes (축).
    xlabels : list of str
        x 축에 표시될 범주 이름 목록.
    values : (M, N) array-like
        데이터 값.
        행은 그룹 (len(group_labels) == M) 입니다.
        열은 범주 (len(xlabels) == N) 입니다.
    group_labels : list of str
        범례에 표시될 그룹 레이블 목록.
    """

    def label_bars(heights, rects):
        """각 막대 위에 텍스트 레이블을 첨부합니다."""
        for height, rect in zip(heights, rects):
            ax.annotate(f'{height}',
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 4),  ## 4 points vertical offset.
                        textcoords='offset points',
                        ha='center', va='bottom')

    values = np.asarray(values)
    x = np.arange(values.shape[1])
    ax.set_xticks(x, labels=xlabels)
    spacing = 0.3  ## hat 그룹 간 간격
    width = (1 - spacing) / values.shape[0]
    heights0 = values[0]
    for i, (heights, group_label) in enumerate(zip(values, group_labels)):
        style = {'fill': False} if i == 0 else {'edgecolor': 'black'}
        rects = ax.bar(x - spacing/2 + i * width, heights - heights0,
                       width, bottom=heights0, label=group_label, **style)
        label_bars(heights, rects)

데이터 준비

이 단계에서는 레이블과 numpy 배열을 초기화합니다. 배열에 N 개의 값에 대한 N 개의 레이블이 있는지 확인합니다.

## initialise labels and a numpy array make sure you have
## N labels of N number of values in the array
xlabels = ['I', 'II', 'III', 'IV', 'V']
playerA = np.array([5, 15, 22, 20, 25])
playerB = np.array([25, 32, 34, 30, 27])

Hat 그래프 생성

이 단계에서는 이전 단계에서 준비한 데이터와 hat_graph 함수를 사용하여 Hat 그래프를 생성합니다.

fig, ax = plt.subplots()
hat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])

## Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Games')
ax.set_ylabel('Score')
ax.set_ylim(0, 60)
ax.set_title('Scores by number of game and players')
ax.legend()

fig.tight_layout()
plt.show()

전체 코드

다음은 Python 에서 Hat 그래프를 생성하기 위한 전체 코드입니다.

import matplotlib.pyplot as plt
import numpy as np


def hat_graph(ax, xlabels, values, group_labels):
    """
    Create a hat graph.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        The Axes to plot into.
    xlabels : list of str
        The category names to be displayed on the x-axis.
    values : (M, N) array-like
        The data values.
        Rows are the groups (len(group_labels) == M).
        Columns are the categories (len(xlabels) == N).
    group_labels : list of str
        The group labels displayed in the legend.
    """

    def label_bars(heights, rects):
        """Attach a text label on top of each bar."""
        for height, rect in zip(heights, rects):
            ax.annotate(f'{height}',
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 4),  ## 4 points vertical offset.
                        textcoords='offset points',
                        ha='center', va='bottom')

    values = np.asarray(values)
    x = np.arange(values.shape[1])
    ax.set_xticks(x, labels=xlabels)
    spacing = 0.3  ## spacing between hat groups
    width = (1 - spacing) / values.shape[0]
    heights0 = values[0]
    for i, (heights, group_label) in enumerate(zip(values, group_labels)):
        style = {'fill': False} if i == 0 else {'edgecolor': 'black'}
        rects = ax.bar(x - spacing/2 + i * width, heights - heights0,
                       width, bottom=heights0, label=group_label, **style)
        label_bars(heights, rects)


## initialise labels and a numpy array make sure you have
## N labels of N number of values in the array
xlabels = ['I', 'II', 'III', 'IV', 'V']
playerA = np.array([5, 15, 22, 20, 25])
playerB = np.array([25, 32, 34, 30, 27])

fig, ax = plt.subplots()
hat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])

## Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Games')
ax.set_ylabel('Score')
ax.set_ylim(0, 60)
ax.set_title('Scores by number of game and players')
ax.legend()

fig.tight_layout()
plt.show()

요약

이 랩에서는 Matplotlib 라이브러리를 사용하여 Python 에서 Hat 그래프를 생성하는 방법을 배웠습니다. Hat 그래프를 생성하는 함수를 정의하고, 데이터를 준비한 다음, hat_graph 함수를 사용하여 그래프를 생성했습니다. Hat 그래프는 스택 막대 차트 (stacked bar chart) 의 변형으로, 각 막대가 모자 모양을 갖습니다. 우리는 게임 수와 플레이어별 점수 데이터 세트를 사용하여 그래프를 생성했습니다.