AI 기본 과정

Python을 이용한 데이터 분석 - Matplotlib (1)

넝구리 2022. 5. 2. 23:49

ICT이노베이션스퀘어 AI기본과정(CNU) 교육을 듣고 정리한 내용입니다.

AI기본과정(CNU) 교육 자료를 참고하였습니다.


기온 공공데이터 분석

 

서울 기온 데이터 분석

 

seoul.csv
1.12MB

 

 

1. csv 파일에서 데이터 읽어오기

 

seoul.csv 파일 읽어오기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv', 'r', encoding = 'cp949')

seoul_temperature = csv.reader(f, delimiter = ',')
print(seoul_temperature)

f.close()

 

 

2. 데이터 출력하기

 

seoul.csv 데이터 한 행(row)씩 읽어오기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv', encoding = 'cp949')

seoul_temperature = csv.reader(f)

for row in seoul_temperature:
    print(row)

f.close()

 

누락된 데이터 확인

# 1950년 9월 1일부터 1953년 11월 30일까지의 기온 데이터가 누락되었음을 알 수 있음

 

 

3. 헤더 저장하기

 

next() 함수를 활용해 헤더(열 변수명) 저장하기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)

header = next(seoul_temperature)
print(header)

f.close()

 

헤더를 제외한 데이터 한 행씩 출력하기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)

header = next(seoul_temperature)

for row in seoul_temperature:
    print(row)

f.close()

 

 

4. 기온 공공데이터에 질문하기

 

  • 기상 관측 이래 최저기온이 나타난 때는 언제일까?
  • 기상 관측 이래 최고기온이 나타난 때는 언제일까?
  • 일교차가 가장 심한 날은 언제일까?
  • 서울이 가장 더웠던 날은 언제일까?
  • 2000년 이후 최고기온과 최저기온은 몇 도일까?

 

 

 

서울이 가장 더웠던 날은 언제일까?

 

1. 질문 다듬기

 

서울이 가장 더웠던 날은 언제일까?

-> 기상 관측 이래 서울의 기온이 가장 높은 날은 언제였고, 몇 도였을까?

 

 

2. 문제 해결 방법 구상하기

 

  • 문제 : 기상 관측 이래 서울의 기온이 가장 높은 날은 언제였고, 몇 도였을까?
  • 문제 해결을 위해 필요한 데이터 : 날짜, 최고기온
  • 문제 해결을 위한 알고리즘 : 데이터 읽어오기 -> 순차적으로 최고 기온 확인하기 -> 최고 기온이 가장 높았던 날짜의 데이터 저장하기 -> 저장된 데이터 출력하기

 

 

3. 파이썬 코드 구현

 

데이터를 한 행씩 출력

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)

header = next(seoul_temperature)

for row in seoul_temperature:
    print(row)

f.close()

 

최고 기온을 실수로 변환하여 한 행씩 출력

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)

header = next(seoul_temperature)

for row in seoul_temperature:
    row[-1] = float(row[-1])     # 최고 기온을 실수로 변환
    print(row)

f.close()

 

기상 관측 이래 서울의 기온이 가장 높은 날은 언제였고, 몇 도였을까?

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)

header = next(seoul_temperature)

max_temp = -999     # 최고 기온을 저장할 변수 초기화
max_date = ""     # 최고 기온이었던 날짜를 저장할 변수 초기화

for row in seoul_temperature:
    if row[-1] == "":     # 최고 기온 데이터가 누락되었다면 최고 기온을 -999로 저장
        row[-1] = -999
   
    row[-1] = float(row[-1])
    
    if max_temp < row[-1]:     # 이전의 최고 기온보다 더 높으면 업데이트
        max_date = row[0]
        max_temp = row[-1]
    
f.close()

print("기상 관측 이래 서울의 최고 기온이 가장 높았던 날은", max_date, "로", max_temp, "도 였습니다.")

 

 

 

 

데이터 시각화 기초

 

기본 그래프

 

1. matplotlib 라이브러리

 

  • 파이썬으로 데이터를 시각화할 때 가장 많이 사용하는 라이브러리
  • 2D 형태의 그래프, 이미지 등을 그릴 때 사용
  • 실제 과학 컴퓨팅 연구 분야나 인공지능 연구 분야에서도 많이 활용

 

matplotlib 라이브러리의 pyplot 모듈 불러오기

import matplotlib.pyplot

 

matplotlib 라이브러리의 pyplot 모듈을 'plt'라는 별명으로 부르기

import matplotlib.pyplot as plt

 

 

2. 기본 그래프

 

plt.plot(데이터셋)

import matplotlib.pyplot as plt

plt.plot([10,30,50,70])
plt.show()

 

plt.plot(x축 데이터셋, y축 데이터셋)

import matplotlib.pyplot as plt

plt.plot([10,30,50,70],[5,15,30,20])
plt.show()

 

 

3. 그래프에 옵션 추가

 

그래프에 제목 추가

import matplotlib.pyplot as plt

plt.title("my graph")
plt.plot([10,30,50,70])
plt.show()

 

그래프에 범례 추가

import matplotlib.pyplot as plt

plt.title("my graph")
plt.plot([10,30,50,70], label = "asc")
plt.plot([70,50,30,10], label = "desc")
plt.legend()
plt.show()

 

그래프 색상 변경

import matplotlib.pyplot as plt

plt.title("my graph")
plt.plot([10,30,50,70], color = "green", label = "green")
plt.plot([70,50,30,10], color = "red", label = "red")
plt.legend()
plt.show()

 

그래프 선 모양 변경

import matplotlib.pyplot as plt

plt.title("my graph")
plt.plot([10,30,50,70], "g.", label = "circle")     # 초록색 원형 마커 그래프
plt.plot([70,50,30,10], "y^", label = "triangle")     # 노란색 삼각형 마커 그래프
plt.legend()
plt.show()

 

 

 

생일의 기온 변화 그래프

 

1. 데이터 읽어오기

 

데이터 읽어와서 최고 기온 데이터 출력하기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

for row in seoul_temperature:
    print(row[-1])

 

데이터 리스트에 저장하기

import csv

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":
        max_temp.append(float(row[-1]))

print(max_temp)

 

 

2. 데이터 시각화

 

최고 기온 데이터 꺾은선 그래프로 그리기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":
        max_temp.append(float(row[-1]))

plt.plot(max_temp, "r")
plt.show()

 

 

3. 날짜 데이터 추출

 

split() 함수 : 문자열 분리

date = "2000-01-01"
print(date.split("-"))

 

연, 월, 일 추출하기

date = "2000-01-01"

print(date.split("-")[0])
print(date.split("-")[1])
print(date.split("-")[2])

 

8월의 최고 기온 데이터 시각화

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":     # 최고 기온 값이 공백이 아니라면
        if row[0].split("-")[1] == "08":     # 8월에 해당하는 값이라면
            max_temp.append(float(row[-1]))     # max_temp 리스트에 최고 기온 값 추가

plt.plot(max_temp, "hotpink")
plt.show()

 

내 생일의 최고 기온 데이터 시각화

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":
        if row[0].split("-")[1] == "09" and row[0].split("-")[2] == "27":
            max_temp.append(float(row[-1]))

plt.plot(max_temp, "hotpink")
plt.show()

9월 27일의 최고 기온 데이터 그래프

 

내 생일의 최고 기온 및 최저 기온 데이터 시각화

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []
min_temp = []

for row in seoul_temperature:
    if row[-1] != "" and row[-2] != "":     # 최고 기온과 최저 기온이 모두 공백이 아니라면
        if row[0].split("-")[1] == "09" and row[0].split("-")[2] == "27":
            max_temp.append(float(row[-1]))
            min_temp.append(float(row[-2])) 

plt.title("the temperature of my birthday")
plt.plot(max_temp, "hotpink", label = "maximum")
plt.plot(min_temp, "skyblue", label = "minimum")
plt.legend()
plt.show()

 

한글 폰트 사용하기(Windows 기준)

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []
min_temp = []

for row in seoul_temperature:
    if row[-1] != "" and row[-2] != "":
        if row[0].split("-")[1] == "09" and row[0].split("-")[2] == "27":
            max_temp.append(float(row[-1]))
            min_temp.append(float(row[-2])) 

plt.rc("font", family = "Malgun Gothic")     # '맑은고딕' 폰트 사용
plt.title("내 생일의 기온 변화 그래프")
plt.plot(max_temp, "hotpink", label = "최고 기온")
plt.plot(min_temp, "skyblue", label = "최저 기온")
plt.legend()
plt.show()

 

 

 

기온 데이터의 다양한 시각화

 

1. 히스토그램

 

hist() 함수

import matplotlib.pyplot as plt

plt.hist([1,1,2,2,2,3,4,5,5,6,7,8,9,10,10,10,10])
plt.show()

 

주사위 시뮬레이션

import random
import matplotlib.pyplot as plt

dice = []

for i in range(10):     # 주사위를 10번 던짐
    dice.append(random.randint(1,6))     # 1~6 사이의 랜덤 숫자를 dice 리스트에 추가

plt.hist(dice, bins = 6)     # 6개 구간의 히스토그램으로 표현
plt.show()

 

 

2. 기온 데이터를 히스토그램으로 표현하기

 

최고 기온 데이터 히스토그램으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":
        max_temp.append(float(row[-1]))

plt.hist(max_temp, bins = 100, color = "r")
plt.show()

 

8월의 최고 기온 데이터 히스토그램으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

August_max = []

for row in seoul_temperature:
    if row[-1] != "":
        if row[0].split("-")[1] == "08":
            August_max.append(float(row[-1]))

plt.hist(August_max, bins = 100, color = "red")
plt.show()

 

1월과 8월의 최고 기온 데이터를 히스토그램으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

January_max = []
August_max = []

for row in seoul_temperature:
    if row[-1] != "":
        if row[0].split("-")[1] == "01":
            January_max.append(float(row[-1]))
        elif row[0].split("-")[1] == "08":
            August_max.append(float(row[-1]))

plt.hist(January_max, bins = 100, color = "blue", label = "Jan")            
plt.hist(August_max, bins = 100, color = "red", label = "Aug")
plt.legend()
plt.show()

 

 

3. 기온 데이터를 상자 그림으로 표현하기

 

최고 기온 데이터 상자 그림으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

max_temp = []

for row in seoul_temperature:
    if row[-1] != "":
        max_temp.append(float(row[-1]))

plt.boxplot(max_temp)
plt.show()

 

1월과 8월의 최고 기온 데이터 상자 그림으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

January_max = []
August_max = []

for row in seoul_temperature:
    if row[-1] != "":
        if row[0].split("-")[1] == "01":
            January_max.append(float(row[-1]))
        elif row[0].split("-")[1] == "08":
            August_max.append(float(row[-1]))

plt.boxplot([January_max,August_max])
plt.show()

 

1월부터 12월까지의 최고 기온 데이터를 상자 그림으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

month = [[],[],[],[],[],[],[],[],[],[],[],[]]     # month 리스트 안에 12개의 리스트 생성

for row in seoul_temperature:
    if row[-1] != "":
        month[int(row[0].split("-")[1])-1].append(float(row[-1]))
        
plt.boxplot(month)
plt.show()

 

8월 1일부터 8월 31일까지의 최고 기온 데이터를 상자 그림으로 표현하기

import csv
import matplotlib.pyplot as plt

f = open('C:/Users/82109/OneDrive/바탕 화면/seoul.csv')

seoul_temperature = csv.reader(f)
next(seoul_temperature)

month = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],
         [],[],[],[],[],[],[],[],[],[],[],[],[],[]]     # month 리스트 안에 31개의 리스트 생성

for row in seoul_temperature:
    if row[-1] != "":
        if row[0].split("-")[1] == "08":
            month[int(row[0].split("-")[2])-1].append(float(row[-1]))
        
plt.boxplot(month)
plt.show()