Matplotlib fill_between 및 Alpha 활용

Beginner

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

소개

데이터 시각화에서 그래프의 특정 영역이나 범위를 강조해야 할 때가 있습니다. Matplotlib 의 fill_between 함수는 최소 및 최대 경계 사이의 음영 영역을 생성하는 데 유용한 도구입니다. 또한 그래프의 시각적 외관을 향상시키는 데 사용할 수 있습니다. alpha 인수를 사용하여 음영 영역의 투명도를 조정할 수 있습니다. 이 랩에서는 Matplotlib 에서 fill_betweenalpha를 사용하여 시각적으로 더 매력적이고 유익한 그래프를 만드는 몇 가지 예제를 안내합니다.

VM 팁

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

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

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

fill_between으로 선 그래프 향상시키기

첫 번째 예제에서는 fill_between을 사용하여 선 그래프를 향상시키는 방법을 보여줍니다. Google 의 금융 데이터를 사용하여 두 개의 서브플롯을 생성합니다. 하나는 단순한 선 그래프이고 다른 하나는 채워진 선 그래프입니다.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook

## load up some sample financial data
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)

## create two subplots with the shared x and y axes
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)

pricemin = r.close.min()

ax1.plot(r.date, r.close, lw=2)
ax2.fill_between(r.date, pricemin, r.close, alpha=0.7)

for ax in ax1, ax2:
    ax.grid(True)
    ax.label_outer()

ax1.set_ylabel('price')
fig.suptitle('Google (GOOG) daily closing price')
fig.autofmt_xdate()

alpha를 사용하여 색상 부드럽게 하기

alpha 인수는 시각적으로 더 매력적인 플롯을 위해 색상을 부드럽게 하는 데에도 사용할 수 있습니다. 다음 예제에서는 단계가 그려지는 정규 분포의 서로 다른 평균과 표준 편차를 가진 두 개의 무작위 보행자 (random walker) 집단을 계산합니다. 채워진 영역을 사용하여 집단의 평균 위치의 +/- 1 표준 편차를 플롯합니다.

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

Nsteps, Nwalkers = 100, 250
t = np.arange(Nsteps)

## an (Nsteps x Nwalkers) array of random walk steps
S1 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers)
S2 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers)

## an (Nsteps x Nwalkers) array of random walker positions
X1 = S1.cumsum(axis=0)
X2 = S2.cumsum(axis=0)

## Nsteps length arrays empirical means and standard deviations of both
## populations over time
mu1 = X1.mean(axis=1)
sigma1 = X1.std(axis=1)
mu2 = X2.mean(axis=1)
sigma2 = X2.std(axis=1)

## plot it!
fig, ax = plt.subplots(1)
ax.plot(t, mu1, lw=2, label='mean population 1')
ax.plot(t, mu2, lw=2, label='mean population 2')
ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='C0', alpha=0.4)
ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='C1', alpha=0.4)
ax.set_title(r'random walkers empirical $\mu$ and $\pm \sigma$ interval')
ax.legend(loc='upper left')
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

where를 사용하여 특정 영역 강조하기

where 키워드 인수는 그래프의 특정 영역을 강조 표시하는 데 매우 유용합니다. where는 x, ymin 및 ymax 인수와 동일한 길이의 부울 마스크를 사용하며, 부울 마스크가 True 인 영역만 채웁니다. 아래 예제에서는 단일 무작위 보행자를 시뮬레이션하고 모집단 위치의 분석적 평균과 표준 편차를 계산합니다. 모집단 평균은 점선으로 표시되고, 평균에서 플러스/마이너스 1 시그마 편차는 채워진 영역으로 표시됩니다. X > upper_bound where 마스크를 사용하여 보행자가 1 시그마 경계 밖에 있는 영역을 찾고 해당 영역을 빨간색으로 음영 처리합니다.

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

Nsteps = 500
t = np.arange(Nsteps)

mu = 0.002
sigma = 0.01

## the steps and position
S = mu + sigma*np.random.randn(Nsteps)
X = S.cumsum()

## the 1 sigma upper and lower analytic population bounds
lower_bound = mu*t - sigma*np.sqrt(t)
upper_bound = mu*t + sigma*np.sqrt(t)

fig, ax = plt.subplots(1)
ax.plot(t, X, lw=2, label='walker position')
ax.plot(t, mu*t, lw=1, label='population mean', color='C0', ls='--')
ax.fill_between(t, lower_bound, upper_bound, facecolor='C0', alpha=0.4,
                label='1 sigma range')
ax.legend(loc='upper left')

## here we use the where argument to only fill the region where the
## walker is above the population 1 sigma boundary
ax.fill_between(t, upper_bound, X, where=X > upper_bound, fc='red', alpha=0.4)
ax.fill_between(t, lower_bound, X, where=X < lower_bound, fc='red', alpha=0.4)
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

axhspanaxvspan을 사용하여 축 범위 강조 표시하기

채워진 영역의 또 다른 유용한 사용법은 축 (Axes) 의 수평 또는 수직 범위를 강조 표시하는 것입니다. 이를 위해 Matplotlib 에는 헬퍼 함수 axhspanaxvspan이 있습니다. 자세한 내용은 axhspan_demo 갤러리를 참조하십시오.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
ax.axvspan(6, 7, facecolor='r', alpha=0.5)

plt.show()

요약

이 랩에서는 Matplotlib 에서 fill_between 함수와 alpha 인수를 사용하여 시각적으로 더 매력적이고 유익한 그래프를 만드는 방법을 배웠습니다. fill_betweenalpha를 사용하여 그래프의 특정 영역 또는 범위를 강조 표시하는 몇 가지 예제를 시연했습니다. 또한 축 (Axes) 의 범위를 강조 표시하기 위한 axhspanaxvspan 함수를 간략하게 소개했습니다.