Matplotlib 를 사용한 레이블 막대 차트

Beginner

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

소개

이 튜토리얼에서는 Matplotlib 의 bar_label 헬퍼 함수를 사용하여 레이블이 지정된 막대 차트를 만드는 방법을 배웁니다. 수평 및 수직 막대 차트에 레이블을 지정하고, 다양한 레이블 형식을 사용하며, 레이블 모양을 사용자 정의하는 등 다양한 시나리오를 다룰 것입니다.

VM 팁

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

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

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

라이브러리 임포트

먼저 numpymatplotlib을 포함한 필요한 라이브러리를 임포트해야 합니다. 또한 일부 임의의 데이터를 생성하기 위해 numpyrandom 모듈을 사용합니다.

import matplotlib.pyplot as plt
import numpy as np

## Fixing random state for reproducibility
np.random.seed(19680801)

수직 막대 차트 레이블 지정

bar_label 함수를 사용하여 수직 막대 차트를 만들고 레이블을 지정하는 것으로 시작합니다. 사용할 데이터는 https://allisonhorst.github.io/palmerpenguins/에서 가져온 성별에 따른 펭귄의 수입니다.

species = ('Adelie', 'Chinstrap', 'Gentoo')
sex_counts = {
    'Male': np.array([73, 34, 61]),
    'Female': np.array([73, 34, 58]),
}
width = 0.6  ## the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots()
bottom = np.zeros(3)

for sex, sex_count in sex_counts.items():
    p = ax.bar(species, sex_count, width, label=sex, bottom=bottom)
    bottom += sex_count

    ax.bar_label(p, label_type='center')

ax.set_title('Number of penguins by sex')
ax.legend()

plt.show()

수평 막대 차트 레이블 지정

다음으로, bar_label 함수를 사용하여 수평 막대 차트를 만들고 레이블을 지정합니다. 이전 단계의 데이터를 사용하지만, 이번에는 각 사람에 대한 임의의 성능 데이터를 생성합니다.

people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  ## labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

## Label with specially formatted floats
ax.bar_label(hbars, fmt='%.2f')
ax.set_xlim(right=15)  ## adjust xlim to fit labels

plt.show()

고급 막대 레이블 지정

이 단계에서는 막대 레이블로 수행할 수 있는 몇 가지 더 고급 기능을 보여줍니다. 이전 단계와 동일한 수평 막대 차트를 사용합니다.

fig, ax = plt.subplots()

hbars = ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  ## labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

## Label with given captions, custom padding and annotate options
ax.bar_label(hbars, labels=[f'±{e:.2f}' for e in error],
             padding=8, color='b', fontsize=14)
ax.set_xlim(right=16)

plt.show()

{} 스타일 형식 문자열을 사용한 막대 레이블 지정

이 단계에서는 {} 스타일 형식 문자열을 사용하여 막대 레이블을 형식화하는 방법을 보여줍니다. 맛별 젤라토 판매에 대한 데이터를 사용합니다.

fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio']
fruit_counts = [4000, 2000, 7000]

fig, ax = plt.subplots()
bar_container = ax.bar(fruit_names, fruit_counts)
ax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000))
ax.bar_label(bar_container, fmt='{:,.0f}')

호출 가능한 객체를 사용한 막대 레이블 지정

마지막으로, 호출 가능한 객체 (callable) 를 사용하여 막대 레이블을 형식화하는 방법을 보여줍니다. 다양한 동물의 달리기 속도에 대한 데이터를 사용합니다.

animal_names = ['Lion', 'Gazelle', 'Cheetah']
mph_speed = [50, 60, 75]

fig, ax = plt.subplots()
bar_container = ax.bar(animal_names, mph_speed)
ax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))
ax.bar_label(bar_container, fmt=lambda x: f'{x * 1.61:.1f} km/h')

요약

이 튜토리얼에서는 Matplotlib 의 bar_label 헬퍼 함수를 사용하여 레이블이 지정된 막대 차트를 만드는 방법을 배웠습니다. 수평 및 수직 막대 차트 레이블 지정, 다양한 레이블 형식 사용, 레이블 모양 사용자 지정과 같은 다양한 시나리오를 다루었습니다.