본문 바로가기

Crawling/데이터 시각화

Matplotlib_라인 플롯(Line Plot)

import matplotlib as mpl
from matplotlib import font_manager, rc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
print(mpl.__version__)
# seaborn 스타일 사용
plt.style.use('seaborn-notebook')

# matplotlib 그래프 한글폰트 깨질 때 대처(Mac & Window)
import platform
if platform.system() == 'Windows':
# 윈도우인 경우
    font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
    rc('font', family=font_name)
else:    
# Mac 인 경우
    rc('font', family='AppleGothic')
    
# 그래프에서 마이너스 기호가 표시되도록 하는 설정
mpl.rcParams['axes.unicode_minus'] = False

 

- 플롯(plot)은 그림(figure)와 축(axes)으로 구성
1. plt.Figure: 축과 그래픽, 텍스트, 레이블을 표시하는 모든 객체를 포함하는 컨테이너
2. plt.Axes: 눈금과 레이블이 있는 테두리 박스로 시각화를 형성하는 플롯 요소 포함

 

fig = plt.figure()
ax = plt.axes()

or

fig = plt.figure()

# plt.plot() 함수는 리스트의 값들이 y 값들이라고 가정하고, x값 [0, 1, 2, 3]을 자동으로 만들어냅니다.
plt.plot([2, 4, 6, 8]);

or

x = np.arange(0, 10, 0.01)

fig = plt.figure()
plt.plot(x, np.sin(x));

or

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x));

 

or

plt.plot(np.random.randn(50).cumsum())

 

or

plt.plot(np.random.randn(50).cumsum(), linestyle='solid')
plt.plot(np.random.randn(50).cumsum(), linestyle='dashed')
plt.plot(np.random.randn(50).cumsum(), linestyle='dashdot')
plt.plot(np.random.randn(50).cumsum(), linestyle='dotted')

or

 

plt.plot(np.random.randn(50).cumsum(), linestyle='-')
plt.plot(np.random.randn(50).cumsum(), linestyle='--')
plt.plot(np.random.randn(50).cumsum(), linestyle='-.')
plt.plot(np.random.randn(50).cumsum(), linestyle=':')

##스타일

-  : solid
-- : dashed
-. : dashdot
:  : dotted

 

 

or

plt.plot(np.random.randn(50).cumsum(), color='g')            # 색상 코드
plt.plot(np.random.randn(50).cumsum(), color='#1243FF')      # RGB
plt.plot(np.random.randn(50).cumsum(), color=(0.2,0.4,0.6))  # RGB
plt.plot(np.random.randn(50).cumsum(), color='darkblue')     # 색상 명

##색상코드

b : blue
g : green
r : red
c : cyan
m : magenta
y : yellow
k : black
w : white

 

# 라인 스타일, 라인 색상 한번에 지정하기
plt.plot(np.random.randn(50).cumsum(), 'b-') 
plt.plot(np.random.randn(50).cumsum(), 'g--')
plt.plot(np.random.randn(50).cumsum(), 'c-.')
plt.plot(np.random.randn(50).cumsum(), 'm:')

 

# 플롯 축(Plot axis)

plt.plot(np.random.randn(50))
plt.xlim(-1,50)  # x축 범위
plt.ylim(-5,5);  # y축 범위
# x축, y축 범위 한번에 지정하기
plt.plot(np.random.randn(50))
plt.axis([-1, 50, -5, 5])
# x축, y축 범위 딱 맞게 
plt.plot(np.random.randn(50))
plt.axis('tight')
# x축, y축 범위 넉넉하게
plt.plot(np.random.randn(50))
plt.axis('equal')
plt.plot(np.random.randn(50))
plt.title('title')
plt.xlabel('x')
plt.ylabel('random.randn')
# 플롯마다 label 달고 legend(범례) 표시하기
plt.plot(np.random.randn(50), label='A')
plt.plot(np.random.randn(50), label='B')
plt.plot(np.random.randn(50), label='C')
plt.legend(loc='lower right')  # loc : 'upper', 'center', 'lower', 'right', 'left', 'best'

# 타이틀, x축, y축 레이블 달기
plt.title('title')
plt.xlabel('x')
plt.ylabel('random.randn')
plt.plot(np.random.randn(50), label='A')
plt.plot(np.random.randn(50), label='B')
plt.plot(np.random.randn(50), label='C')

# legend(범례) 꾸미기
plt.legend(loc='lower right',    
          fancybox=True, framealpha=0.9, shadow=True, borderpad=1)

##폰트

# 폰트 종류 확인
set([f.name for f in  mpl.font_manager.fontManager.ttflist])
font1 = {'family':'DejaVu Sans', 'size':24, 'color':'black'}
font2 = {'family':'Liberation Mono', 'size':18, 'weight':'bold', 'color':'darkred'}
font3 = {'family':'STIXGeneral', 'size':16, 'weight':'light', 'color':'blue'}
plt.plot([1,2,3,4,5], [1,2,3,4,5])

plt.title('title', fontdict=font1)
plt.xlabel('xlabel', fontdict=font2)
plt.ylabel('ylabel', fontdict=font3)