데이터분석/Python matplotlib

<matplotlib> 실시간 데이터 반영 그래프

창조적생각 2021. 8. 29. 13:09

 

<목차>

 

1. 기본 구조

 

2. csv 파일 읽어들여 만들기

 

 

1. 기본 구조

 

사용한 라이브러리

 

random -> 무작위의 수를 생성하기 위해 사용합니다.

intertools.count -> 1,2,3... 순차적인 수를 생성하기 위해 사용합니다.

pandas

matplotlib.pyplot

matplotlib.animation -> animation 효과, 실시간 데이터 반영을 위해 사용합니다.

 

사용한 메서드

index = count()

next(index) -> 순차적인 수를 생성해냅니다.

random.randint(0,5) -> 0~5 사이의 랜덤한 정수를 생성합니다.

plt.cla() -> 앞선 그래프를 삭제합니다.

ani = FuncAnimation(plt.gcf(), animate, interval = 1000)

-> plt.gcf() --> 현재 그래프 모양을 가져옵니다.

-> animate -> 애니메이션 효과를 적용합니다.

->interval = 1000 -> 1000 밀리초 마다 적용합니다.

 

[코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
 
plt.style.use('fivethirtyeight')
 
x_val = []
y_val = []
 
index = count()
 
def animate(i):
    x_val.append(next(index))
    y_val.append(random.randint(0,5))
    plt.cla()
    plt.plot(x_val, y_val)
 
ani = FuncAnimation(plt.gcf(), animate, interval = 1000)
 
 
 
plt.tight_layout()
plt.show()
cs

 

[실행결과]

 

2. csv_file을 읽어들여 만들기

 

(1) 실시간으로 데이터를 생성하는 csv

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import csv
import random
import time
 
x_value = 0
total_1 = 1000
total_2 = 1000
 
fieldnames = ["x_value","total_1","total_2"]
 
with open('C:/Users/opers/python/data4.csv','w'as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
    csv_writer.writeheader()
while True:
    with open('C:/Users/opers/python/data4.csv','a'as csv_file:
        csv_writer = csv.DictWriter(csv_file,fieldnames=fieldnames)
 
        info = {
            "x_value":x_value,
            "total_1":total_1,
            "total_2":total_2
        }
 
        csv_writer.writerow(info)
        print(x_value,total_1,total_2)
 
        x_value += 1
        total_1 = total_1+random.randint(-4,8)
        total_2 = total_2+random.randint(-5,8)
 
    time.sleep(1)
cs

 

(2) 실시간 그래프 그리기 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from pandas.core.indexes import interval
 
 
 
def animate(i):
    data =pd.read_csv('data4.csv')
    x = data['x_value']
    y1 = data['total_1']
    y2 = data['total_2']
 
    plt.cla()
    plt.plot(x,y1, label='블로그')
    plt.plot(x,y2,label='유튜브')
    
    plt.legend(loc = 'upper left')
    plt.tight_layout()
 
ani = FuncAnimation(plt.gcf(),animate, interval = 1000)
 
plt.tight_layout()
plt.show()
cs

 

[실행결과]

 

728x90