matplotlib_lineplot.html
1.11MB
matplotlib_lineplot.ipynb
0.51MB
Matplotlib Line Plot¶
기본 선 그래프 - plt.plot(), plt.show()¶
선 그래프는 시간의 따른 데이터의 변화를 시각화하는데 유용하게 사용된다.
- 지난 10년 간 경유 가격의 평균값
- 지난 두 달간 몸무게 변화
In [ ]:
from matplotlib import pyplot as plt
import numpy as np
x_values = np.array([0, 1, 2, 3, 4]) # x축 지점의 값들
y_values = np.array([0, 1, 4, 9, 16]) # y축 지점의 값들
plt.plot(x_values, y_values) # line 그래프를 그립니다
plt.show() # 그래프를 화면에 보여줍니다
여러 선 포함 그래프 - plt.plot()¶
하나의 그래프 뿐만 아니라 여러개의 그래프를 그릴 수 있다.
같은 scale과 axis를 사용하는 서로 다른 데이터를 보여줄 때 유용하다.
plt.plot() 함수를 반복호출하면 자동으로 여러 그래프를 같은 축에 그려준다.
- 그래프색 - 1st: blue, 2nd: orange, custom가능
In [ ]:
days = np.array([0, 1, 2, 3, 4, 5, 6]) # 한 주의 요일(0: 일, 1: 월 ~ 6: 토)
money_spent = np.array([10, 12, 12, 10, 14, 22, 24]) # 내가 사용한 돈(천원)
money_spent_2 = np.array([11, 14, 15, 15, 22, 21, 12]) # 친구가 사용한 돈(천원)
plt.plot(days, money_spent) # 사용한 돈 그래프로 그리기
plt.plot(days, money_spent_2) # 같은 그림에 친구가 사용한 돈도 그래프로 그리기
plt.show() # 화면에 그래프 그리기
In [ ]:
plt.plot(days, money_spent, color='green') # HTML color name
plt.plot(days, money_spent_2, color='#AAAAAA'); # HEX code
linestyle: 선의 형태를 커스터마이징
In [ ]:
plt.plot(x_values, y_values, linestyle='--') # 파선(Dashed)
plt.plot(x_values, y_values+1, linestyle=':') # 점선(Dotted)
plt.plot(x_values, y_values+2, linestyle='') # 실선(No line)
Out[ ]:
[<matplotlib.lines.Line2D at 0x241c50e4bb0>]
marker: 데이터 포인트 지정
In [ ]:
plt.plot(x_values, y_values, marker='o') # 원(A circle)
plt.plot(x_values, y_values+1, marker='s') # 정사각형(A square)
plt.plot(x_values, y_values+2, marker='*'); # 별(A star)
Axis and Labels - plt.axis(), plt.xlabel(), plt.ylabel(), plt.title()¶
- 그래프의 특정영역을 확대/강조할 때, 표현될 축범위를 plt.axis()로 지정한다.
- x와 y축, 그래프의 의미를 알기위해
- plt.xlabel() / plt.ylabel()로 라벨,
- plt.title()로 제목을 지정한다.
- 인자
- plt.axis(): [ x_min, x_max, y_min, y_max ]
- plt.xlabel(), plt.ylabel(), plt.title(): string
plt.axis()¶
In [ ]:
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 4, 9, 16])
plt.plot(x, y)
plt.axis([0, 3, 2, 5]) # x축은 0~3, y축은 2~5 까지 표현함
plt.show()
plt.xlabel(), plt.ylabel(), plt.title()¶
In [ ]:
hours = np.array([9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
happiness = np.array([9.8, 9.9, 9.2, 8.6, 8.3, 9.0, 8.7, 9.1, 7.0, 6.4, 6.9, 7.5])
plt.plot(hours, happiness)
plt.xlabel('Time of day')
plt.ylabel('Happiness Rating (out of 10)')
plt.title('My Self-Reported Happiness While Awake')
plt.show()
Subplots¶
- 두 데이터 비교 시, 같은 x-axes나 y-axes가 아닌 다른 axes을 사용하여 여러 그래프를 그린다.
- 여러 axes의 집합을 subplot
- subplot을 모두 포함하는 오브젝트를 figure 라고 한다.
- 하나의 figure에 여러 subplot들이 포함될 수 있다.
- 만약, 2행 3열의 총 6개 subplot을 포함하는 figure를 아래와 같이 그릴 수 있다.
plt.subplot()¶
- subplot 호출 함수: plt.subplot()
- plt.subplot() 인자: 행수, 열수, 만들고자 하는 subplot의 index
- e.g. plt.subplot(2, 3, 4) 은 2행 3열 figure에서 “Subplot4” 를 생성한다.
- plt.subplot() 뒤의 plt.plot()은 해당 subplot 에서 그래프를 그린다.
In [ ]:
# 데이터 셋
x = np.array([1, 2, 3, 4])
y = np.array([1, 2, 3, 4])
plt.subplot(1, 2, 1) # 1행 2열에서 1 번째 subplot
plt.plot(x, y, color='green')
plt.title('First Subplot')
plt.subplot(1, 2, 2) # 1행 2열에서 2 번째 subplot
plt.plot(x, y, color='steelblue')
plt.title('Second Subplot')
plt.show() # 그래프를 화면에 그린다
plt.subplot()의 label 간 겹침 문제: plt.subplots_adjust()로 margin을 조정¶
- 아래와 같이, plt.subplot()의 label 간 겹칠 경우, plt.subplots_adjust()로 margin을 조정해 해결
- plt.subplots_adjust() 인자 (keyword argument)
- left - 왼쪽 margin. 디폴트는 0.125
- right - 오른쪽 margin. 디폴트는 0.9
- bottom - 아래쪽 margin. 디폴트는 0.1
- top - 위쪽 margin. 디폴트는 0.9
- wspace - subplots의 수평 간격. 디폴트는 0.2
- hspace - subplots의 수직 간격. 디폴트는 0.2
- subplots의 간격조정 예시
In [ ]:
plt.subplots_adjust(bottom=0.2) # 아래쪽 margin을 0.1 에서 0.2로 늘린다
plt.subplots_adjust(top=0.95, hspace=0.25) # 위쪽 margin을 0.95, 수직 간격을 0.25로 늘린다
plt.show()
<Figure size 640x480 with 0 Axes>
- label 겹침문제 예시
In [ ]:
plt.subplot(1, 2, 1) # 첫 번째 subplot
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
plt.xlabel("x-Label for Plot 1")
plt.ylabel("y-Label for Plot 1")
plt.subplot(1, 2, 2) # 두 번째 subplot
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
plt.xlabel("x-Label for Plot 2")
plt.ylabel("y-Label for Plot 2")
plt.show()
- label 겹침문제 해결
In [ ]:
plt.subplot(1, 2, 1) # 첫 번째 subplot
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
plt.xlabel("x-Label for Plot 1")
plt.ylabel("y-Label for Plot 1")
plt.subplot(1, 2, 2) # 두 번째 subplot
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
plt.xlabel("x-Label for Plot 2")
plt.ylabel("y-Label for Plot 2")
plt.subplots_adjust(wspace=0.35) # 수평 간격을 0.2에서 0.35로 늘린다
plt.show()
Legends - plt.legend()¶
- legend는 하나의 subplot에 여러 그래프를 그릴 경우, 이해를 돕기 위해 다는 모달
- plt.legend()에 라벨을 달아줄 값의 배열을 전달하여 legend를 달아준다.
- plt.legend() 인자인 loc값 (keyword argument: loc)
Number Code | String |
---|---|
0 | best |
1 | upper right |
2 | upper left |
3 | lower left |
4 | lower right |
5 | right |
6 | center left |
7 | center right |
8 | lower center |
9 | upper center |
10 | center |
Note: loc값 미지정시, ‘best’로 할당된다.
- loc값 설정 예시: loc값 6을 지정해, center left(가운데 왼쪽)에 legend 위치
In [ ]:
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16])
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64])
plt.legend(['parabola', 'cubic'], loc=6)
plt.show()
- plt.legend()내에 label을 지정하는 대신, plt.plot()에 label옵션을 지정할 수 있다.
In [ ]:
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16],
label="parabola")
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64],
label="cubic")
plt.legend() # 꼭 호출해야 legend가 달린다
plt.show()
Modify Ticks - axes.¶
- tick을 수정할 figure의 subplot 지정
In [ ]:
ax = plt.subplot(1, 1, 1)
- ax는 axes 오브젝트로, 특정 subplot(여기서는 1행 1열 1 번째 subplot)의 axes 수정가능
- x-ticks 수정(숫자일 경우): ax.set_xticks()의 인자로 tick배열을 넘겨준다.
- x-ticks 수정(label일 경우): ax.set_xticklabels()의 인자로 tick 배열을 넘겨준다.
- x-ticks를 1, 2,4로 수정
In [ ]:
ax = plt.subplot()
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16])
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64])
plt.legend(['parabola', 'cubic'])
ax.set_xticks([1, 2, 4]);
- y-ticks를 0.1, 0.6, 0.8로 수정
In [ ]:
ax = plt.subplot()
plt.plot([1, 3, 3.5], [0.1, 0.6, 0.8], 'o') # 'o' 파라미터를 넘겨 scatter 그래프를 그린다.
ax.set_yticks([0.1, 0.6, 0.8])
ax.set_yticklabels(['10%', '60%', '80%'])
Out[ ]:
[Text(0, 0.1, '10%'), Text(0, 0.6, '60%'), Text(0, 0.8, '80%')]
Figures¶
- plt.close('all'): 기존에 존재하는 모든 그래프를 지움. 기존에 plt.plot()로 그린 그래프를 새 plot에 나타나지 않게 하기 위해 새 plot을 그리기 전 시행한다.
- plt.figure(): 새 figure를 생성하고, figsize 옵션으로 (width, height) 튜플을 전달해 figure의 가로, 세로 길이(인치) 지정할 수 있다.
In [ ]:
plt.figure(figsize=(4, 10))
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64]);
- plt.savefig(): png, svg, pdf형식으로 figure저장. 인수는 지정할 파일 이름이다.
In [ ]:
plt.figure(figsize=(4, 10))
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64])
plt.savefig('tall_and_narrow.png') # 위 figure를 tall_and_narrow.png 로 저장한다
plot폰트 크기 변경¶
In [ ]:
plt.rc('font', size=20) # 기본 폰트 크기
plt.rc('axes', labelsize=20) # x,y축 label 폰트 크기
plt.rc('xtick', labelsize=50) # x축 눈금 폰트 크기
plt.rc('ytick', labelsize=20) # y축 눈금 폰트 크기
plt.rc('legend', fontsize=20) # 범례 폰트 크기
plt.rc('figure', titlesize=50) # figure title 폰트 크기
'파이썬 > visualization' 카테고리의 다른 글
[파이썬/viz] Matplotlib Stylesheet (0) | 2022.11.12 |
---|