본문 바로가기

전처리 및 시각화

데이터 시각화(matplotlib)

# matplotlib.pyplot

파이썬에서 시각화를 위한 라이브러리 중 하나이다.

- 2D 그래픽을 생성하는데 주로 사용된다.

- 선 그래프 / 막대 그래프 / 히스토그램 / 산점도 / 파이 차트 등 다양한 시각화 방식을 지원한다.

- 그래프를 색상 / 스타일 / 레이블 / 축 범위 등을 조절하여 원하는 형태로 시각화할 수 있다.

 

#그래프 유형

Line Plot
연속형 데이터
데이터의 변화 및 추이를 시각화
Bar Plot
범주형 데이터
카테고리 별 값의 크기를 시각적으로 비교
Histogram
연속형 데이터
데이터 분포, 빈도, 패턴 등을 이해
Pie Chart
범주형 데이터의 비율
범주별 상대적 비율을 부채꼴 모양으로 시각화
Box Plot
연속형 데이터의 분포
중앙값, 사분위수, 최소값, 최대값, 이상치 확인
Scatter Plot
두 변수 간 관계
변수 간의 관계, 군집, 이상치 등 확인

 

# 기존에 만들었던 그래프 크기 조정하는 코드

import pandas as pd
df = pd.DataFrame({
    'A' : [1,2,3,4,5],
    'B' : [5,4,3,2,1]
})
df.plot(x='A', y='B', color='red', linestyle='--', marker='o', label='Data Series')
plt.show()
import pandas as pd
df = pd.DataFrame({
    'A' : [1,2,3,4,5],
    'B' : [5,4,3,2,1]
})
ax = df.plot(x='A', y='B', color='red', linestyle='--', marker='o')
ax.legend('Data Series')
plt.show()

선 그래프 그리는 방법과 범례를 추가하는 두 가지 방법

import pandas as pd
df = pd.DataFrame({
    'A' : [1,2,3,4,5],
    'B' : [5,4,3,2,1]
})
ax = df.plot(x='A', y='B', color='red', linestyle='--', marker='o')
ax.legend('Data Series')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Title')
ax.text(3, 3, 'Some Text', fontsize=12)
ax.text(2, 2, 'Some Text', fontsize=10)
plt.show()

기타 추가사항

 

# 그래프 크기 조정 방법

# 원하는 그래프 사이즈 입력 후 데이터에 맞는 그래프 시각화
plt.figure(figsize=(8,6))
x = [1,2,3,4,5]
y = [2,4,6,8,10]
plt.plot(x, y)
plt.show()

기본적으로 그래프의 사이즈를 바꾸기 위한 방법

import pandas as pd
df = pd.DataFrame({
    'A' : [1,2,3,4,5],
    'B' : [5,4,3,2,1]
})
plt.figure(figsize=(18,6)) # 이 코드를 넣어도 사이즈가 변하지 않음
ax = df.plot(x='A', y='B', color='red', linestyle='--', marker='o')
ax.legend('Data Series')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Title')
ax.text(3, 3, 'Some Text', fontsize=12)
ax.text(2, 2, 'Some Text', fontsize=10)
plt.show()
fig, ax = plt.subplots(figsize=(8, 6))
ax = df.plot(x = 'A', y = 'B', color='red', linestyle='--', marker='o', ax=ax)
ax.legend()
...

# plt.figure(figsize=(16, 6)) 이런 코드를 단순히 위에 추가하면 이미지 크기가 안바뀐다.

plt.figure에 대한 사이즈와 만들어낸 plot에 대한 사이즈가 같은 figure가 아니기 때문이다.

고로 subplots()를 활용해서 엑시스를 새로 가져오고 그 엑시스를 플랏이라는 메소드 안에 넣어서 활용해주면 된다.

그래서 subplots()메소드 안에 figsize를 설정해주는 새로운 fig와 ax를 정의해준 다음에 plot 메소드 안에 ax=ax 를 추가해준다.

# subplots 에서 Figure 객체를 fig 로 / AxesSubplot 객체를 ax로 정한 것이다.

 

# 선 그래프(Line Plot)

import pandas as pd
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 2)) # 가로 5인치, 세로 2인치

# 데이터 생성
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]


# 그래프 그리기
plt.plot(x, y, color='green', linestyle='--', marker='o')

# 추가 설정
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Title of the Plot')
plt.legend(['Data Series'])
plt.text(3, 8, 'Some Text', fontsize=12)  # 특정 좌표에 텍스트 추가

# 그래프 출력
plt.show()

# 데이터프레임 생성
data = {'date': ['2023-01-01', '2023-01-02', '2023-01-03'],
        'value': [10, 15, 8]}

plt.figure(figsize=(10, 2))   # 가로 10인치,세로 2인치

df = pd.DataFrame(data)

# '날짜'를 날짜 형식으로 변환
df['date'] = pd.to_datetime(df['date'])

# 선 그래프 작성
plt.plot(df['date'], df['value'])
plt.xlabel('date')
plt.ylabel('value')
plt.title('ex')
plt.show()

 

# 막대 그래프(Bar Plot)

# 데이터프레임 생성
data = {'city': ['Seoul', 'Busan', 'Daegu', 'Incheon'],
        'population': [990, 350, 250, 290]}

plt.figure(figsize=(5, 2))

df = pd.DataFrame(data)

# 막대 그래프 작성
plt.bar(df['city'], df['population'])
plt.xlabel('city')
plt.ylabel('population')
plt.title('ex')
plt.show()

 

# 히스토그램(Histogram)

import matplotlib.pyplot as plt
import numpy as np

# 데이터 생성 (랜덤 데이터)
data = np.random.randn(1000)

plt.figure(figsize=(5, 2))

# 히스토그램 그리기
plt.hist(data, bins=50) # bins는 가로축 구간의 개수를 지정(클수록 얇아짐)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()

 

# 원 그래프(Pie Chart)

# 데이터 생성
sizes = [30, 20, 25, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']

# 원 그래프 그리기
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()

 

# 박스 플롯(Box Plot)

import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset("iris")

species = iris['species'].unique()
sepal_lengths_list = [iris[iris['species'] == s]['sepal_length'] for s in species]
plt.boxplot(sepal_lengths_list, labels=species)
plt.show()

리스트 내포 안의 문법에서 iris[a][b] 에 대한 설명

- a는 조건식 또는 을 선택하는 인덱스가 될 수 있습니다. 만약 a가 조건식이라면, iris DataFrame에서 그 조건을 만족하는 행들만 필터링합니다. 예를 들어, a가 iris['species'] == 'setosa'라면, iris DataFrame에서 종이 'setosa'인 행들만 선택

- b는 특정 (column)을 지정합니다. b가 문자열로 주어진다면, 그 열의 이름을 의미하게 됩니다. 예를 들어, b가 'sepal_length'라면, 필터링된 행들 중 'sepal_length' 열의 값들을 선택

 

리스트 내포를 활용해서 각 종마다 'sepal_length'의 수치를 모아놓은 3개의 리스트를 한 리스트에 넣어넣고,

이 리스트를 시각화한 것

# matplotlib으로 seaborn 데이터 바로 가져와서 시각화 하기

sns.boxplot(x='species', y='sepal_length', data=iris)
plt.show()

import matplotlib.pyplot as plt
import numpy as np

# 데이터 생성
np.random.seed(10)
data = [np.random.normal(0, std, 100) for std in range(1, 6)]

# 박스 플롯 그리기
plt.boxplot(data)
plt.xlabel('Data')
plt.ylabel('Value')
plt.title('Box Plot')
plt.show()

 

# 산점도(Scatter Plot)

iris.corr()
iris.corr(numeric_only=True)

iris 데이터프레임의 상관 계수를 계산하는 코드 / numeric_only = False 가 기본값

numeric_only = True 일 경우 iris 데이터프레임에서 숫자형 열만 선택하여 상관 계수를 계산한다.

-1 ~ 1 의 범위이며 0은 상관없음을 나타낸다.

# 데이터 생성
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# 산점도 그리기
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.show()