파이썬으로 그래프 그리기

hasun·2022년 1월 6일

시계열 데이터

Heatmap

범주형 데이터

수치형 데이터

모듈 import , 데이터 정의

import matplotlib.pyplot as plt
%matplotlib inline

subject = ['English', 'Math', 'Korean', 'Science', 'Computer']
points = [40, 90, 50, 60, 100]
fig = plt.figure(figsize=(5,2)) # 그래프사이즈 조절
ax1 = fig.add_subplot(1,1,1)

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,4)

스크린샷 2022-01-05 10.25.37.png

API 문서 : https://matplotlib.org/stable/api/index.html

https://matplotlib.org/stable/api/figure_api.html?highlight=add_subplot#matplotlib.figure.Figure.add_subplot

https://matplotlib.org/stable/api/figure_api.html?highlight=figure#module-matplotlib.figure

# 그래프 데이터 
subject = ['English', 'Math', 'Korean', 'Science', 'Computer']
points = [40, 90, 50, 60, 100]

# 축 그리기
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

# 그래프 그리기
ax1.bar(subject, points)

# 라벨, 타이틀 달기
plt.xlabel('Subject')
plt.ylabel('Points')
plt.title("Yuna's Test Result")

스크린샷 2022-01-05 10.28.34.png

선 그래프 그리기

from datetime import datetime
import pandas as pd
import os

# 그래프 데이터 
csv_path = os.getenv("HOME") + "/data_visualization/data/AMZN.csv"
data = pd.read_csv(csv_path ,index_col=0, parse_dates=True)
price = data['Close'] #Pandas Series 선그래프 그리기 기능
print(price)
# 축 그리기 및 좌표축 설정
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#Pandas plot사용 하면서 matplotlib정의한 subplot공간 ax사용
price.plot(ax=ax, style='black')

plt.ylim([1600,2200]) # 좌표축 설정
plt.xlim(['2019-05-01','2020-03-01'])

# 주석달기 (그래프 안에 추가적으로 글자나 화살표 주석 그릴때 annotate()메소드 사용)
important_data = [(datetime(2019, 6, 3), "Low Price"),(datetime(2020, 2, 19), "Peak Price")]
for d, label in important_data:
    ax.annotate(label, xy=(d, price.asof(d)+10), # 주석을 달 좌표(x,y)
                xytext=(d,price.asof(d)+100), # 주석 텍스트가 위차할 좌표(x,y)
                arrowprops=dict(facecolor='red')) # 화살표 추가 및 색 설정

# 그리드, 타이틀 달기
plt.grid() # 격자눈금 추가
ax.set_title('StockPrice')

# 보여주기
plt.show()

스크린샷 2022-01-05 10.46.08.png

plot 사용법 상세

figure() 객체를 생성하고 add_subplot()으로 서브플롯 생성하며 plot을 그린다고 했는데

2가지 과정을 생략하고 plt.plot()명령으로 그래프를 그리면 matplotlib은 **가장 최근의 figure객체의 서브플롯을 그린다. 만약 서브 플롯이 없으면 서브플롯을 하나 생성한다.**

import numpy as np
x = np.linspace(0, 10, 100) #0에서 10까지 균등한 간격으로  100개의 숫자를 만들라는 뜻입니다.
plt.plot(x, np.sin(x),'o')
plt.plot(x, np.cos(x),'--', color='black') 
plt.show()

#------------------------------------------
x = np.linspace(0, 10, 100) 

plt.subplot(2,1,1)
plt.plot(x, np.sin(x),'orange','o')

plt.subplot(2,1,2)
plt.plot(x, np.cos(x), 'orange') 
plt.show()

스크린샷 2022-01-05 10.49.15.png

스크린샷 2022-01-05 10.50.30.png

x = np.linspace(0, 10, 100) 

plt.plot(x, x + 0, linestyle='solid') 
plt.plot(x, x + 1, linestyle='dashed') 
plt.plot(x, x + 2, linestyle='dashdot') 
plt.plot(x, x + 3, linestyle='dotted')
plt.plot(x, x + 0, '-g') # solid green 
plt.plot(x, x + 1, '--c') # dashed cyan 
plt.plot(x, x + 2, '-.k') # dashdot black 
plt.plot(x, x + 3, ':r'); # dotted red
plt.plot(x, x + 4, linestyle='-') # solid 
plt.plot(x, x + 5, linestyle='--') # dashed 
plt.plot(x, x + 6, linestyle='-.') # dashdot 
plt.plot(x, x + 7, linestyle=':'); # dotted

스크린샷 2022-01-05 10.52.08.png

Pandas plot() 그래프 그리기

  • label: 그래프의 범례 이름.
  • ax: 그래프를 그릴 matplotlib의 서브플롯 객체.
  • style: matplotlib에 전달할 'ko--'같은 스타일의 문자열
  • alpha: 투명도 (0 ~1)
  • kind: 그래프의 종류: line, bar, barh, kde
  • logy: Y축에 대한 로그 스케일
  • use_index: 객체의 색인을 눈금 이름으로 사용할지의 여부
  • rot: 눈금 이름을 로테이션(0 ~ 360)
  • xticks, yticks: x축, y축으로 사용할 값
  • xlim, ylim: x축, y축 한계
  • grid: 축의 그리드 표시할지 여부

Pandas의 data가 DataFrame일 때 plot메서드 인자

  • subplots: 각 DataFrame의 칼럼을 독립된 서브플롯에 그린다.
  • sharex: subplots=True 면 같은 X 축을 공유하고 눈금과 한계를 연결한다.
  • sharey: subplots=True 면 같은 Y 축을 공유한다.
  • figsize: 그래프의 크기, 튜플로 지정
  • title: 그래프의 제목을 문자열로 지정
  • sort_columns: 칼럼을 알파벳 순서로 그린다.
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(5), index=list('abcde'))
data.plot(kind='bar', ax=axes[0], color='blue', alpha=1)
data.plot(kind='barh', ax=axes[1], color='red', alpha=0.3)

#--------------------------------------------

df = pd.DataFrame(np.random.rand(6,4), columns=pd.Index(['A','B','C','D']))
df.plot(kind='line')

스크린샷 2022-01-05 10.57.49.png

스크린샷 2022-01-05 10.58.01.png

  1. fig = plt.figure() : figure 객체선언 ‘도화지 펼친다’
  2. axl = flg.add_subplot(1,1,1) : 축을 그린다
  3. axl.bar(x,y) 축 안에 어떤 그래프를 그릴지 메서드를 선택한 다음 인자로 데이터를 넣어준다
  4. 그래프 타이틀 축의 레이블 등을 plt 여러 메서드 grid, xlabel, ylabel, 이용해 추가
  5. plt.saveflg 메서드 이용해 저장 해준다.

스크린샷 2022-01-05 10.59.22.png

profile
내가 얻는 보상은 내가 제공하는 가치와 비례한다.

0개의 댓글