-
[Data Visualization] 데이터 시각화 - matplotlib(1)Data Science/Data Visualization 2021. 1. 18. 23:41
파이썬에서 시각화를 하는 방법은 여러가지가 있지만
먼저 matplotlib부터 정리를 해보려고 합니다.
기본 그래프 그리기
데이터 시각화를 위한 라이브러리인 matplotlib 불러오고
import matplotlib.pyplot as plt
시각화를 위해서 데이터 프레임을 생성해 줍니다.
x = [1, 3, 5, 7] y = [2, 4, 6, 8] df = pd.DataFrame({'x' : x, 'y' : y})
matplotlib의 plot() 함수에 x와 y 값을 넣어주면 다음과 같은 그래프가 그려집니다.
plt.plot([1, 3, 5], [2, 4, 6]);
축 레이블 설정
xlabel(), ylabel()을 이용하면 축의 레이블을 설정할 수 있습니다.
plt.xlabel('X') plt.ylabel('Y')
축 범위 지정
axis() 함수를 이용하면 축의 범위를 지정할 수 있습니다.
plt.axis([xmin, xmax, ymin, ymax])
위 그래프에 적용해보면
plt.plot([1, 3, 5], [2, 4, 6]) plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.show()
마커 지정하기
marker 옵션으로 마커를 지정해줍니다.
plt.plot(x, y, marker = '')
위 그래프에 marker = 'o'을 이용해 원형 마커를 지정해보면
plt.plot([1, 3, 5], [2, 4, 6], marker = 'o') plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.show()
그래프 색상 변경하기
color 옵션을 지정해서 그래프의 색상을 지정할 수 있습니다.
plt.plot(x, y, color = '')
위 그래프를 초록색으로 변경해보면
plt.plot([1, 3, 5], [2, 4, 6], marker = 'o', color = 'g') # g = green plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.show()
그리드 설정하기
grid() 함수를 통해서 그래프의 그리드를 설정해 줍니다.
plt.grid(True)
x축과 y축 둘 다 그려지는 것이 default 이지만, x축과 y축 중 하나만 선택할 수도 있습니다.
뿐만 아니라 color, alpha, linestyle로 그리드 설정을 변경해 줄 수 있습니다.
plt.plot([1, 3, 5], [2, 4, 6], marker = 'o', color = 'g') plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.grid(True, axis = 'y', color = '#374045', alpha = 0.3, linestyle = '--') plt.show()
눈금 설정하기
xticks(), yticks()으로 각각 x축과 y축의 눈금을 표시할 수 있습니다.
plt.xticks() plt.yticks()
리스트나 np.arange()로 눈금을 지정해주면 됩니다.
plt.plot([1, 3, 5], [2, 4, 6], marker = 'o', color = 'g') plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.grid(True, axis = 'y', color = '#374045', alpha = 0.3, linestyle = '--') plt.xticks([1, 3, 5, 7, 9]) plt.yticks(np.arange(0, 11)) plt.show()
그래프 타이틀 설정하기
title()는 그래프의 타이틀을 설정합니다.
plt.title()
fontsize, fontweight로 폰트의 설정을 변경할 수 있고,
loc를 사용하면 타이틀의 위치를 변경이 가능합니다.
plt.plot([1, 3, 5], [2, 4, 6], marker = 'o', color = 'g') plt.xlabel('X') plt.ylabel('Y') plt.axis([0, 10, 0, 10]) plt.grid(True, axis = 'y', color = '#374045', alpha = 0.3, linestyle = '--') plt.xticks([1, 3, 5, 7, 9]) plt.yticks(np.arange(0, 11)) plt.title('TITLE', fontsize = 20, fontweight = 'bold') plt.show()
'Data Science > Data Visualization' 카테고리의 다른 글
[Data Visualization] folium으로 지도에 데이터 시각화하기 (0) 2021.07.25 [Data Visualization] 데이터 시각화 - plotly : Interactive scatter plot (0) 2021.07.13 [Data Visualization] 데이터 시각화 - matplotlib(4) : pie (0) 2021.01.27 [Data Visualization] 데이터 시각화 - matplotlib(3) : hist (0) 2021.01.25 [Data Visualization] 데이터 시각화 - matplotlib(2) : scatter, bar, barh (0) 2021.01.24