728x90
Matplotlib은 데이터 시각화와 2D 그래프 플롯에 사용되는 파이썬 라이브러리이다.
Example. Basic
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4]) #plot() 안의 값은 y 값이다.
plt.show() #show() 함수는 그래프를 화면에 나타낸다.
Example. Use number
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) # 이때 x값, y값이 된다.
# (1,1), (2,4), (3,9), (4,16) 이렇게 찍힌다.
plt.show()
Example
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') # 'ro'는 색상 'red'와 형태 'o'를 뜻한다.
plt.axis([0, 6, 0, 20]) #axis([xmin, xmax, ymin, ymax]) 축의 범위를 지정할 수 있다.
plt.show()
# r-- : red dash, bs : blue square, g^ : green triangle
Example. Dictionary 사용
import matplotlib.pyplot as plt
data_dict = {'data_x': [1, 2, 3, 4, 5], 'data_y': [2, 3, 5, 10, 8]}
plt.plot('data_x', 'data_y', data=data_dict)
plt.show()
Example. Axis labelling
import matplotlib.pyplot as plt
font1 = {'family': 'serif',
'color': 'b',
'weight': 'bold',
'size': 14
} # dictionary 이용하여 font 정보 저장
font2 = {'family': 'fantasy',
'color': 'deeppink',
'weight': 'normal',
'size': 'xx-large'
}
plt.plot([1, 2, 3, 4], [2, 3, 5, 10])
plt.xlabel('X-Axis', labelpad=15, fontdict=font1)
plt.ylabel('Y-Axis', labelpad=20, fontdict=font2)
# ylabel : y축 이름 설정, labelpad : 여백, fontdict : font 지정
plt.show()
Example. Label
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [2, 3, 5, 10], label='Price ($)') #label='Price ($)'가 범례
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.legend(loc=(1.0, 1.0)) #legend() 함수의 loc 파라미터를 이용해서 범례가 표시될 위치를 설정 가능
plt.show()
Example. Axis range
- xlim() - X축이 표시되는 범위를 지정/반환
- ylim() - Y축이 표시되는 범위를 지정/반환
- axis() - X, Y축이 표시되는 범위를 지정/반환
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [2, 3, 5, 10])
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.xlim([0, 15]) # X축의 범위: [xmin, xmax]
plt.ylim([0, 27]) # Y축의 범위: [ymin, ymax]
plt.show()