1. 데이터 경향 표시
- 산점도를 이용하여 데이터 경향을 표시.
1) 사용 데이터
- 서울시 CCTV 데이터와 인구 데이터를 합친 data_result를 이용
2) 산점도 그리기
- 인구수가 늘어날 수록 cctv가 많아지는 듯해 보이긴 함
plt.figure(figsize=(10,10))
plt.scatter(data_result["인구수"], data_result["소계"], s=50)
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid()
plt.show()
3) numpy를 이용한 1차 직선 만들기
import numpy as np
① np.polyfit(x, y, n)
- 직선을 구성하기 위한 계수를 계산
- 직선의 구성요소인 y절편과 기울기를 알려줌 (y=ax+b)
- 데이터 x, y를 입력해주고 다항식의 차수(n)를 지정
fp1 = np.polyfit(data_result["인구수"], data_result["소계"], 1)
---------------------------------------
array([1.11155868e-03, 1.06515745e+03])
② np.poly1d( )
- polyfit으로 찾은 계수로 파이썬에서 사용할 수 있는 함수로만들어주는기능
f1 = np.poly1d(fp1)
----------------------------------------
poly1d([1.11155868e-03, 1.06515745e+03])
cf. 인구가 40만인 구에서 서울시 전체 경향에 맞는 적당한 CCTV 수?
f1(400000)
------------------
1509.7809252413338
③ np.linspace(a, b, n)
- a부터 b까지 n개의 등간격 데이터 생성
fx = np.linspace(100000, 700000, 100)
plt.figure(figsize=(14,10))
plt.scatter(data_result["인구수"], data_result["소계"], s=50)
plt.plot(fx, f1(fx), ls="dashed", lw=3, color="g")
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid(True)
plt.show()
2. 강조할 데이터 시각화
- 경향을 벗어나는 데이터를 찾아서 강조.
1) 경향(trend)과의 오차 생성
- 경향은 f1함수에 해당 인구를 입력
- 오차 = 실제 CCTV 보유 수 - 경향
data_result["오차"] = data_result["소계"] - f1(data_result["인구수"])
2) 오차 정렬
- 경향 대비 CCTV를 많이 가진 구
df_sort_f = data_result.sort_values(by="오차", ascending=False)
- 경향 대비 CCTV를 적게 가진 구
df_sort_t = data_result.sort_values(by="오차", ascending=True)
3) 데이터 시각화
- colormap 을 사용자 정의(user define)로 세팅
- for 구문을 이용하여 상위 5개, 하위 5개 데이터의 이름 표기
from matplotlib.colors import ListedColormap
color_step = ["#e74c3c","#2ecc71","#95a9a6","#2ecc71","#3498db","#3489db"]
my_cmap = ListedColormap(color_step)
plt.figure(figsize=(14,10))
plt.scatter(data_result["인구수"], data_result["소계"], s=50, c=data_result["오차"], cmap=my_cmap)
plt.plot(fx, f1(fx), ls="dashed", lw=3, color="g")
for n in range(5):
# 상위 5개
plt.text(
df_sort_f["인구수"][n]*1.02, #x좌표
df_sort_f["소계"][n]*0.98, #y좌표
df_sort_f.index[n], #title
fontsize=15,
)
# 하위 5개
plt.text(
df_sort_t["인구수"][n]*1.02,
df_sort_t["소계"][n]*0.98,
df_sort_t.index[n],
fontsize = 15
)
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.colorbar()
plt.grid(True)
plt.show()
3. 참고할만한 사이트
Matplotlib Tutorial - 파이썬으로 데이터 시각화하기
## 도서 소개 - 이 책은 파이썬의 대표적인 데이터 시각화 라이브러리인 Matplotlib의 사용법을 소개합니다. - 30여 개 이상의 다양한 주제에 대해 1 ...
wikidocs.net
Plot types — Matplotlib 3.5.2 documentation
Overview of many common plotting commands in Matplotlib. Note that we have stripped all labels, but they are present by default. See the gallery for many more examples and the tutorials page for longer examples. Unstructured coordinates Sometimes we collec
matplotlib.org