스마트 인재개발원/Python 기초

2021-04-13 파이썬 라이브러리(스마트인재개발원)

Matplotlib!!
import matplotlib.pyplot as plt
Line Plot 그리기
y = [2,12,6]
plt.plot(y)
#plot(좌표 y요소)
# x좌표는 0부터 1씩 증가시키며 할당 

#plt.show(): 그동안 그렸던 plot들을 출력
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '--')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-.')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = '1')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'v')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'p')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'D')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 's')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'h')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = '_')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '--', marker = '1', lw = 5)
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '--', marker = '1', lw = 5, color = 'r')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'o', lw = 5, color = 'r', markerfacecolor = 'g')
plt.show()

x = [1,2,3]
y = [2,4,6]
plt.plot(x,y, ls = '-', marker = 'o', lw = 5, color = 'pink', markerfacecolor = 'r')
plt.show()

import numpy as np
x = np.arange(7)
y = [1,4,5,8,9,5,3]

plt.plot(x,y, ls = '--', marker = 'o', color = 'g')
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>

import numpy as np
x = np.arange(7)
y = [1,4,5,8,9,5,3]

plt.plot(x,y, ls = ':', marker = 'D', color = 'r', markerfacecolor = 'b')
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>

lotto = np.random.randint(1,46,6)
lotto
array([24, 17,  1, 21, 37, 20])
import numpy as np
x = np.arange(7)
y = [1,4,5,8,9,5,3]

plt.plot(x,y, ls = ':', marker = 'D', color = 'r', markerfacecolor = 'b', markersize = 9)
plt.xlim(-2,10)
plt.ylim(-2,10)
plt.show()

import numpy as np
x = np.arange(7)
y = [1,4,5,8,9,5,3]

plt.plot(x,y, ls = ':', marker = 'D', color = 'r', markerfacecolor = 'b', markersize = 9)
plt.xlim(2,6)
plt.ylim(-2,20)
plt.show()

import numpy as np
x = np.arange(7)
y = [1,4,5,8,9,5,3]

plt.plot(x,y, ls = ':', marker = 'D', color = 'r', markerfacecolor = 'b', markersize = 9)
plt.xlim(-2,10)
plt.ylim(-2,10)

plt.grid(axis= 'x') #플롯에 격자를 추가가
plt.show()

여러개 plot 그리기
x = [1,2,3,4]
y = [2,4,6,8]
z = [3,6,9,12]

plt.plot(x)
plt.plot(y)
plt.plot(z)

plt.show()

x = [1,2,3,4]
y = [2,4,6,8]
z = [3,6,9,12]

plt.plot(x, label = 'x')
plt.plot(y, label = 'y')
plt.plot(z, label = 'z')

#범례표시
plt.legend()


#x축 라벨 설정 
plt.xlabel('X')

#y축 라벨설명 
plt.ylabel('Y')

#plot에 제목설정
plt.title('title')
plt.show()

x = np.arange(3)
values = {100, 400, 900}
years = ['2017', '2018', '2019']
plt.bar(x, values)
plt.xticks(x, years)
plt.show()

산점도
N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.title('title')
colors = np.random.randint(0,3,size=(N))
# s = 점의크기, alpha = 투명도
plt.scatter(x,y, s=50, c=colors ,alpha = 0.5)
<matplotlib.collections.PathCollection at 0x27a4bcca2e0>

차트에서 한글 보이게 하기
from matplotlib import font_manager, rc
font_name  = font_manager.FontProperties(fname='C:/Windows/Fonts/malgun.ttf').get_name()
font_name
'Malgun Gothic'
rc('font',family = font_name)

x = [1,2,3,4]
y = [2,4,6,8]
z = [3,6,9,12]

plt.plot(x, label = 'x')
plt.plot(y, label = 'y')
plt.plot(z, label = 'z')

#범례표시
plt.legend()


#x축 라벨 설정 
plt.xlabel('X값')

#y축 라벨설명 
plt.ylabel('Y값')

#plot에 제목설정
plt.title('타이틀')
plt.show()

전국 사망교통사고 2017 시각화
import pandas as pd
data = pd.read_csv('data/Traffic_Accident_2017.csv',encoding = 'euc-kr')
car_crash_data = pd.DataFrame(data)

car_crash.head(3)
발생년	발생년월일시	발생분	주야	요일	사망자수	사상자수	중상자수	경상자수	부상신고자수	...	도로형태_대분류	도로형태	당사자종별_1당_대분류	당사자종별_1당	당사자종별_2당_대분류	당사자종별_2당	발생위치X_UTMK	발생위치Y_UTMK	경도	위도
0	2017	2017010101	15	야간	일	1	2	1	0	0	...	단일로	기타단일로	승용차	승용차	승용차	승용차	933501	1700129	126.768634	35.294464
1	2017	2017010102	28	야간	일	1	1	0	0	0	...	교차로	교차로부근	승용차	승용차	보행자	보행자	967570	1944453	127.133107	37.498741
2	2017	2017010102	43	야간	일	1	2	0	1	0	...	단일로	기타단일로	승용차	승용차	승용차	승용차	916497	1842880	126.566631	36.580069
3 rows × 27 columns

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4065 entries, 0 to 4064
Data columns (total 27 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   발생년           4065 non-null   int64  
 1   발생년월일시        4065 non-null   int64  
 2   발생분           4065 non-null   int64  
 3   주야            4065 non-null   object 
 4   요일            4065 non-null   object 
 5   사망자수          4065 non-null   int64  
 6   사상자수          4065 non-null   int64  
 7   중상자수          4065 non-null   int64  
 8   경상자수          4065 non-null   int64  
 9   부상신고자수        4065 non-null   int64  
 10  발생지시도         4065 non-null   object 
 11  발생지시군구        4065 non-null   object 
 12  사고유형_대분류      4065 non-null   object 
 13  사고유형_중분류      4065 non-null   object 
 14  사고유형          4065 non-null   object 
 15  법규위반_대분류      4065 non-null   object 
 16  법규위반          4065 non-null   object 
 17  도로형태_대분류      4065 non-null   object 
 18  도로형태          4065 non-null   object 
 19  당사자종별_1당_대분류  4065 non-null   object 
 20  당사자종별_1당      4065 non-null   object 
 21  당사자종별_2당_대분류  4065 non-null   object 
 22  당사자종별_2당      4065 non-null   object 
 23  발생위치X_UTMK    4065 non-null   int64  
 24  발생위치Y_UTMK    4065 non-null   int64  
 25  경도            4065 non-null   float64
 26  위도            4065 non-null   float64
dtypes: float64(2), int64(10), object(15)
memory usage: 857.6+ KB
요일별 사망교통사고 시각화
data['요일'].unique()
array(['일', '월', '화', '수', '목', '금', '토'], dtype=object)
week_data = data['요일'].value_counts()
week_data = week_data[['월','화','수','목','금','토','일']]
week_data
월    603
화    608
수    565
목    586
금    603
토    596
일    504
Name: 요일, dtype: int64
plt.plot(week_data)
plt.show()

x = week_data.index
plt.bar(x,week_data)
plt.ylim(500,650)
plt.xlabel('요일')
plt.ylabel('사건 건수').set_rotation(0)
plt.title('요일별 사망건수')
plt.show()