본문 바로가기

Python_Intermediate/Matplotilb

Python Matplotlib - Txt File Load 그래프

반응형

1. TXT 파일을 쉼표로 구분하여 Sample Data File 작성

1, 2

2, 3

3, 4

4, 5

5, 6

6, 7

7, 8

8, 9

9, 10

10, 11

sample.txt


2. Sample Code(import CSV)

- Import Module

import matplotlib.pyplot as plt
import csv

- Code

import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('sample.txt', 'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))

plt.figure()
plt.plot(x, y, label='int load file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Txt To CSV File Load')
plt.grid()
plt.legend()
plt.savefig('txt.png')
plt.close()

- Code 풀이

x = []
y = []

x 축 y 축 데이터를 저장할 빈 리스트 부여


with open('sample.txt', 'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))

sample.txt를 CSV로 읽어들여 구분 기호(delimiter)를 , 로 준다.

이를 x와 y에 정수로 구분하여 추가한다.

plt.figure()
plt.plot(x, y, label='int load file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Txt To CSV File Load')
plt.grid()
plt.legend()
plt.savefig('txt.png')
plt.close()

Pyplot 구문


- 출력물


3. Sample Code(import Numpy)

- import module

import matplotlib.pyplot as plt
import numpy as np

- Code

import matplotlib.pyplot as plt
import numpy as np

x, y= np.loadtxt('sample.txt', delimiter=',', unpack=True)
plt.figure()
plt.plot(x, y, label='int load file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Txt To CSV File Load')
plt.grid()
plt.legend()
plt.savefig('txt2.png')
plt.close()

- Code 풀이

x, y= np.loadtxt('sample.txt', delimiter=',', unpack=True)

sample.txt를 로드하여 , 를 기준으로 언팩킹 작업 구문


plt.figure()
plt.plot(x, y, label='int load file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Txt To CSV File Load')
plt.grid()
plt.legend()
plt.savefig('txt2.png')
plt.close()

Pyplot 구문


- 출력물





반응형