Bar of Pie 차트 만들기

Beginner

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

소개

이 튜토리얼에서는 Python 의 Matplotlib 라이브러리를 사용하여 "Bar of Pie" 차트를 만드는 방법을 배웁니다. Bar of Pie 차트는 파이 차트와 누적 막대 차트의 조합으로, 파이의 첫 번째 슬라이스가 막대 차트로 분해되어 해당 특성을 더 자세히 보여줍니다. 이 차트는 전체 데이터 세트의 분포를 표시하는 동시에 특정 범주를 강조 표시하려는 경우 유용합니다.

VM 팁

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

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

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

필요한 라이브러리 가져오기

차트를 만들기 전에 필요한 라이브러리를 가져와야 합니다. 이 경우 matplotlib.pyplotnumpy를 사용합니다.

import matplotlib.pyplot as plt
import numpy as np

차트 데이터 정의

다음으로, 차트를 만드는 데 사용할 데이터를 정의해야 합니다. 이 경우 다음 데이터를 사용합니다.

## pie chart parameters
overall_ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]

## bar chart parameters
age_ratios = [.33, .54, .07, .06]
age_labels = ['Under 35', '35-49', '50-65', 'Over 65']

파이 차트 생성

이제 파이 차트를 만들 수 있습니다. 먼저 figure 및 axis 객체를 정의합니다.

## make figure and assign axis objects
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 5))
fig.subplots_adjust(wspace=0)

그런 다음 파이 차트의 매개변수를 설정하고 플롯합니다.

## rotate so that first wedge is split by the x-axis
angle = -180 * overall_ratios[0]
wedges, *_ = ax1.pie(overall_ratios, autopct='%1.1f%%', startangle=angle,
                     labels=labels, explode=explode)

막대 차트 생성

다음으로, 누적 막대 차트를 만듭니다. 먼저 차트의 매개변수를 정의합니다.

## bar chart parameters
bottom = 1
width = .2

## Adding from the top matches the legend.
for j, (height, label) in enumerate(reversed([*zip(age_ratios, age_labels)])):
    bottom -= height
    bc = ax2.bar(0, height, width, bottom=bottom, color='C0', label=label,
                 alpha=0.1 + 0.25 * j)
    ax2.bar_label(bc, labels=[f"{height:.0%}"], label_type='center')

파이 차트와 막대 차트 연결

마지막으로, ConnectionPatch를 사용하여 파이 차트와 막대 차트를 연결합니다.

## use ConnectionPatch to draw lines between the two plots
theta1, theta2 = wedges[0].theta1, wedges[0].theta2
center, r = wedges[0].center, wedges[0].r
bar_height = sum(age_ratios)

## draw top connecting line
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = r * np.sin(np.pi / 180 * theta2) + center[1]
con = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)

## draw bottom connecting line
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = r * np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)

차트 표시

마지막으로, 차트를 표시합니다.

plt.show()

요약

이 튜토리얼에서는 Python 의 Matplotlib 라이브러리를 사용하여 "Bar of Pie" 차트를 만드는 방법을 배웠습니다. Bar of Pie 차트는 전체 데이터 세트의 분포를 표시하는 동시에 특정 범주를 강조 표시하려는 경우 유용합니다. 또한 파이 차트와 막대 차트를 연결하기 위해 ConnectionPatch를 사용하는 방법도 배웠습니다.