Data Analysis

Python/Matplotlip(시각화)

[Python] Matplotlib (4) 라인 스타일, 영역 채우기

Holy_Water 2022. 11. 28. 15:57

linestyle 지정하기

plt.plot([1, 2, 3], [4, 4, 4], linestyle='solid', color='C0', label="'solid'")
plt.plot([1, 2, 3], [3, 3, 3], linestyle='dashed', color='C0', label="'dashed'")
plt.plot([1, 2, 3], [2, 2, 2], linestyle='dotted', color='C0', label="'dotted'")
plt.plot([1, 2, 3], [1, 1, 1], linestyle='dashdot', color='C0', label="'dashdot'")
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.axis([0.8, 3.2, 0.5, 5.0])
plt.legend(loc='upper right', ncol=4)
plt.tight_layout()
plt.show()

- plot() 함수의 linestyle 파라미터 값을 직접 지정할 수 있습니다.
- 포맷 문자열과 같이 ‘solid’, ‘dashed’, ‘dotted’, dashdot’ 네가지의 선 종류를 지정할 수 있습니다.
- 결과는 아래와 같습니다.

 

 

선/마커 동시에 나타내기

# plt.plot([1, 2, 3, 4], [2, 3, 5, 10], 'bo-')    # 파란색 + 마커 + 실선
plt.plot([1, 2, 3, 4], [2, 3, 5, 10], 'bo--')     # 파란색 + 마커 + 점선
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.show()

- ‘bo-‘는 파란색의 원형 마커와 실선 (Solid line)을 의미합니다.
- 또한 ‘bo- -‘는 파란색의 원형 마커와 점선 (Dashed line)을 의미합니다.
- 아래 그림과 같이 실선 또는 점선과 마커가 함께 표시됩니다.

 

 

 

색상 지정하기

plt.plot([1, 2, 3, 4], [2.0, 3.0, 5.0, 10.0], 'r')
plt.plot([1, 2, 3, 4], [2.0, 2.8, 4.3, 6.5], 'g')
plt.plot([1, 2, 3, 4], [2.0, 2.5, 3.3, 4.5], 'b')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

plt.show()

- plot() 함수의 포맷 문자열 (Format string)을 사용해서 실선의 색상을 지정했습니다.

 

 

 

그래프 영역 채우기

- 그래프의 특정 영역을 색상으로 채워서 강조할 수 있습니다.

 

matplotlib.pyplot 모듈에서 그래프의 영역을 채우는 아래의 세가지 함수에 대해 소개합니다.
- fill_between() - 두 수평 방향의 곡선 사이를 채웁니다.
- fill_betweenx() - 두 수직 방향의 곡선 사이를 채웁니다.
- fill() - 다각형 영역을 채웁니다.

 

 

기본 사용 - fill_between()

x = [1, 2, 3, 4]
y = [2, 3, 5, 10]

plt.plot(x, y)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.fill_between(x[1:3], y[1:3], alpha=0.5)

plt.show()

- fill_between() 함수에 x[1:3], y[1:3]를 순서대로 입력하면,
- 네 점 (x[1], y[1]), (x[2], y[2]), (x[1], 0), (x[2], 0)을 잇는 영역이 채워집니다.

 

 

 

기본 사용 - fill_betweenx()

x = [1, 2, 3, 4]
y = [2, 3, 5, 10]

plt.plot(x, y)
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.fill_betweenx(y[2:4], x[2:4], alpha=0.5)

plt.show()

- fill_betweenx() 함수에 y[2:4], x[2:4]를 순서대로 입력하면,
- 네 점 (x[2], y[2]), (x[3], y[3]), (0, y[2]), (0, y[3])을 잇는 영역이 채워집니다.