본문 바로가기

데이터 사이언스/데이터 분석

Matplotlib 기초

Line Plot

- 라인 그래프를 그리는 함수

- subplots()에 매개변수가 없다면, 단일 그래프가 반환됨

- 색깔도 설정 가능 (color 매개변수 사용)

fig, ax = plt.subplots()
x = np.arrange(15)
y = x ** 2	  # x의 제곱
ax.plot(
	x, y,
    linestyle=":",
    marker="*"
)

- linestyle은 -, -. , : , -- 등으로 설정할 수 있음


축 경계 조정하기

- linespace로 조정

- set_ylim, set_xlim은 축의 경계를 설정

x = np.linespace(0, 10, 1000)
fig, ax = plot.subplots()
ax.plot(x, np.sin(x))
ax.set_xlim(-2, 12)    # lim은 limit의 축약어로, x축의 축의 경계 설정
ax.set_ylim(-1.5, 1.5)

범례

- set_ylabel, set_xlabel로 라벨 추가

- legend가 범례를 지정해주는 함수

- legend의 속성 중, loc는 위치 옵션으로, 자주 사용되는 속성은 다음과 같음

'best'
'upper right', 'upper left'
'lower left', 'lower right'
'right'
'center left', 'center right'
'lower center'
'upper center'
'center'
-
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(loc='upper right',
		  shadow=True,
          fancybox=True,	# 범례의 모서리를 둥글게 만듦
          borderpad=2)		# 범례의 크기 지정

Bar Plot

- 막대 그래프를 그리는 함수

x = np.arrange(10)
fig, ax = plt.subplots(figsize=(12, 4))   # 가로, 세로
ax.bar(x, x*2)

 

- 누적 그래프를 그리고 싶다면 다음과 같이 설정

- set_xticks는 왼쪽의 범례를 지정해주며, set_xticklabels은 x축의 라벨을 지정해줌

- set_xlim이나 set_ylim은 원하는 범위를 리스트로 넣어주는 반면, set_xticks나 set_yticks는 규칙성이 없는 값들을 넣어줄 수 있음

x = np.random.rand(3)
y = np.random.rand(3)
z = np.random.rand(3)

data = [x, y, z]

fig, ax = plt.subplots()

x_ax = np.arrange(3)
for i in x_ax:
	ax.bar(x_ax, data[i])
    bottom = np.sum(data[:i], axis=0)
    
    
ax.set_xticks(x_ax)
ax.set_xticklabels(['A', 'B', 'C'])

Histogram

- 도수분포표를 그려주는 함수

fig, ax = plt.subplots()
data = np.random.randn(1000)
ax.hist(data, bins=50)