티스토리 뷰

반응형


import pandas as pd

import numpy as np

from pandas import Series, DataFrame

from numpy import nan as NA

 


matplotlib API

 

cmd 모드로 사용 시,

      -  pylab 모드로 실행 : ipython --pylab

      -  pylab 모드로 전환 : %matplotlib qt


import matplotlib.pyplot as plt



#. 선 그래프(Line Plot) 그리기

 - figure : 그래프를 그릴 수 있는 도화지 (subplot만으로도 그래프 생성이 가능하지만, 특정 그래프, 특정 축 설정 변경을 위해 생성)

 - subplot : 도화지에 그래프가 그려지는 부분


# figure 준비

fig = plt.figure()


# subplot 생성

ax = fig.add_subplot(1,1,1)        # (a,b,c) : ab열의 c번째에 subplot 생성


# plot 그리기

data = DataFrame(np.random.rand(30), columns=['col'])

ax.plot(data['col'])


# plot 제목 설정

ax.set_title('test')


# 축 이름 설정

ax.set_xlabel('x')   # x축 이름

ax.set_ylabel('y')   # y축 이름


# 범위 설정

ax.set_xticks([0,10,20,30])   # x축 눈금 지정(정수)

ax.set_xticklabels(['one','two','three','four'], rotation=30, fontsize=7)    # x축 눈금 지정(문자열)

ax.set_ylim([0,1.5])            # y축 범위

# plt.xticks([,,,], labels=[,,,], rotation=) 




#. 여러 그래프 그리기

# 방법 1

fig, ax = plt.subplots(1,2)

ax[0].hist(np.random.rand(50), bins=20, alpha=0.5)    # alpha : 투명도

ax[1].scatter(np.random.rand(50), np.random.rand(50) * np.random.rand(50))

 

방법 2

fig = plt.figure()

ax1 = fig.add_subplot(2,2,1)

ax2 = fig.add_subplot(2,2,2)

ax3 = fig.add_subplot(2,2,3)

ax4 = fig.add_subplot(2,2,4)

ax1.plot(np.random.rand(100), 'k--')     # linestyle='--', color='k'

ax2.plot(np.random.rand(60), 'go--')     # linestyle='o--', color='g'

ax3.plot(np.random.rand(40), 'r-', drawstyle='steps-post')     # linestyle='-', color='r'

ax4.plot(np.random.rand(20), 'y.')        # linestyle='.', color='y'


 


#. 속성

# color


# linestyle

# 범례 위치



#. DataFrame 그래프

 - 각 컬럼별 선 그래프 출력

 - 각 컬럼이름이 범례로 지정

 

df1 = pd.read_csv('plot_test.csv')


# figure 없이 바로 그리기

df1.plot()

plt.ylim([100,300])


figure 생성 후 그리기

fig, ax = plt.subplots(1,1)

ax.plot(df1)      

ax.set_ylim([100.300])



 



#. Q1

import pandas as pd

import numpy as np

from pandas import Series, DataFrame

from numpy import nan as NA

import matplotlib.pyplot as plt

%matplotlib qt


# cctv 데이터를 불러오고

cctv = pd.read_csv('cctv.csv', encoding='cp949')

cctv['rate'] = round(cctv['검거'] / cctv['발생']*100,2)

cctv


data = cctv.pivot('년도', '', 'rate')

data


# 1) 각 년도별 검거율 증가추이를 각 구별로 비교할 수 있도록 plot 도표 그리기

plt.rc('font', family='Malgun Gothic', size=7)      

data.plot() 

plt.ylabel('검거율')   # y축 이름 설정

plt.ylim([0,150])    # y축 범위 설정

plt.xticks(data.index)   # x축 눈금 변경

plt.title('구별 검거율 추세')  # plot 제목 설정

# x축 : data.index

# x축 이름 : data.index.names

# 범례 이름 : data.columns.names


 

 

#. Q2

subway.csv 파일을 읽고

sub = pd.read_csv('subway.csv', encoding='cp949')

sub['시간'] = sub['시간'].map(lambda x : ('%04d' % x)).str[:2]    # .str : 색인이 벡터화 된 메서드


# 각 라인번호 별로 승하차의 시간별 증감추이를 승,하차 각각 그래프로 표현

data = sub.pivot('시간','노선번호',['승차','하차'])


fig, ax = plt.subplots(1,2)

ax[0].plot(data['승차'])

ax[1].plot(data['하차'])

ax[0].set_ylim([0,6000000])    # y축 범위 설정

ax[1].set_ylim([0,6000000])

ax[1].legend(data.columns.levels[1])   # 범례 설정

plt.title('구별 검거율 추세')    # plot 제목 설정

ax[0].set_xlabel('시간')      # x축 이름 설정

ax[1].set_xlabel('시간')

ax[0].set_ylabel('노선번호')     # y축 이름 설정

ax[1].set_ylabel('노선번호')  

# 다른 방법 같은 결과

fig = plt.figure()

ax1 = fig.add_subplot(1,2,1)

ax2 = fig.add_subplot(1,2,2)

ax1.plot(data['승차'])

ax2.plot(data['하차'])

ax1.set_ylim([0,6000000])      # y축 범위 설정

ax2.set_ylim([0,6000000])

ax2.legend(data.columns.levels[1])      # 범례 설정  # data['승차'].columns.values

plt.title('구별 검거율 추세')      # plot 제목 설정

ax1.set_xlabel('시간')       # x축 이름 설정

ax2.set_xlabel('시간')

ax1.set_ylabel('노선번호')      # y축 이름 설정

ax2.set_ylabel('노선번호') 





고: KIC 캠퍼스 머신러닝기반의 빅데이터분석 양성과정

반응형

'Python > Visualize' 카테고리의 다른 글

[Python 시각화] 막대 그래프 그리기 (matplotlib API)  (0) 2019.02.18
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday