Matplotlib 오차 막대 플롯 생성

Beginner

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

소개

오차 막대 (Error bars) 는 그래프와 차트에서 측정 또는 데이터 포인트의 잠재적인 오차 또는 불확실성을 표시하는 데 사용됩니다. Python Matplotlib 은 다양한 유형의 오차 막대 플롯을 제공하는 인기 있는 데이터 시각화 라이브러리입니다. 이 랩에서는 Matplotlib 을 사용하여 상한 및 하한이 있는 오차 막대 플롯을 만드는 방법을 배웁니다.

VM 팁

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

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

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

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

NumPy 및 Matplotlib 을 포함하여 필요한 라이브러리를 가져오는 것으로 시작합니다.

import matplotlib.pyplot as plt
import numpy as np

데이터 정의

다음으로, 플롯할 몇 가지 예제 데이터를 정의합니다. 여기서는 x 값, y 값 및 해당 오차 값의 배열을 생성합니다.

x = np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0])
y = np.exp(-x)
xerr = 0.1
yerr = 0.2

간단한 오차 막대 그래프 생성

errorbar 함수를 사용하여 표준 오차 막대가 있는 간단한 오차 막대 그래프를 생성합니다. 여기서는 x 및 y 값과 해당 오차 값을 설정합니다. 또한 선 스타일을 점선으로 설정합니다.

fig, ax = plt.subplots(figsize=(7, 4))

## standard error bars
ax.errorbar(x, y, xerr=xerr, yerr=yerr, linestyle='dotted')

상한 추가

오차 막대에 상한을 추가하려면 errorbar 함수의 uplims 매개변수를 사용합니다. 또한 이전 플롯과 구별하기 위해 y 값에 0.5 의 상수 값을 추가합니다.

## including upper limits
ax.errorbar(x, y + 0.5, xerr=xerr, yerr=yerr, uplims=True, linestyle='dotted')

하한 추가

오차 막대에 하한을 추가하려면 errorbar 함수의 lolims 매개변수를 사용합니다. 또한 이전 플롯들과 구별하기 위해 y 값에 1.0 의 상수 값을 추가합니다.

## including lower limits
ax.errorbar(x, y + 1.0, xerr=xerr, yerr=yerr, lolims=True, linestyle='dotted')

상한 및 하한 추가

오차 막대에 상한과 하한을 모두 추가하려면 errorbar 함수의 uplimslolims 매개변수를 모두 사용합니다. 또한 이전 플롯들과 구별하기 위해 플롯에 마커를 추가합니다.

## including upper and lower limits
ax.errorbar(x, y + 1.5, xerr=xerr, yerr=yerr, lolims=True, uplims=True,
            marker='o', markersize=8, linestyle='dotted')

X 및 Y 축 모두에 제한 추가

마지막으로, x 축과 y 축 모두에 제한을 추가합니다. x 축 오차 막대에 제한을 추가하기 위해 xlolimsxuplims 매개변수를 사용합니다.

## Plot a series with lower and upper limits in both x & y
## constant x-error with varying y-error
xerr = 0.2
yerr = np.full_like(x, 0.2)
yerr[[3, 6]] = 0.3

## mock up some limits by modifying previous data
xlolims = lolims
xuplims = uplims
lolims = np.zeros_like(x)
uplims = np.zeros_like(x)
lolims[[6]] = True  ## only limited at this index
uplims[[3]] = True  ## only limited at this index

## do the plotting
ax.errorbar(x, y + 2.1, xerr=xerr, yerr=yerr,
            xlolims=xlolims, xuplims=xuplims,
            uplims=uplims, lolims=lolims,
            marker='o', markersize=8, linestyle='none')

플롯 표시

마지막으로, show 함수를 사용하여 플롯을 표시합니다.

## tidy up the figure
ax.set_xlim((0, 5.5))
ax.set_title('Errorbar upper and lower limits')
plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 상한 및 하한이 있는 오차 막대 플롯을 만드는 방법을 배웠습니다. errorbar 함수를 사용하여 상한 및 하한이 있는 다양한 플롯을 만들었습니다. 또한 x 축과 y 축 모두에 제한을 추가하는 방법도 배웠습니다.