251127_BootCamp Day 29_데이터 분석 기초 프로젝트 (6)
2025. 11. 27. 20:47ㆍTIL
1. Matplotlib 공부 (matplotlib 튜토리얼 참고)
import matplotlib.pyplot as plt
import numpy as np
기본적인 plot 그리기
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

Bubble plot 그리기 (주석은 직접 공부해서 추가한 내용)
np.random.seed(19680801)
data = {'a': np.arange(50), #0 이상 50 미만 정수 배열 생성
'c': np.random.randint(0, 50, 50), #0 이상 50 미만 임의의 정수 50개
'd': np.random.randn(50)} # 표준정규분포 상의 임의의 실수 50개
data['b'] = data['a'] + 10 * np.random.randn(50) # b 추가
data['d'] = np.abs(data['d']) * 100 # d의 값 증가 (사이즈 크게 하기 위함)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
sc = ax.scatter('a', 'b', c='c', s='d', data=data, cmap='rainbow')
# 'a', 'b' : x축과 y축
# c : 색상 설정(color). 이 경우는 컬러맵 방식을 사용.
# 파이썬이 알아서 정수 범위에서 최소값과 최대값을 찾아 비율(%)로 바꾸고
# 지정된 컬러맵에서 해당 % 위치에 있는 색을 가져온다.
# 컬러맵을 쓰고 싶으면 반드시 데이터(점)의 개수와 길이가 같은 배열 형태로 들어와야 한다.
# s : 크기(size). 가변 사이즈를 위해 배열값을 주어, d값에 따라 점의 크기가 달라짐.
fig.colorbar(sc, ax=ax, label='Value of c')
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')

하나의 도화지(ax)에 여러 개 plot 만들기
x = np.linspace(0, 2, 100) # 0부터 2까지 100개 간격의 실수 배열 생성
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title("Simple Plot")
ax.legend()

누적합 그래프 : Plot 별로 색상과 선 스타일 다르게 하기
data1, data2, data3, data4 = np.random.randn(4, 100)
fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1)) #0부터 99까지 정수 배열 생성
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--')
# cumsum : 누적합
ax.plot(x, np.cumsum(data2), color='red', linewidth=2, linestyle=':')

Subplot을 이용해 plot 여러 개 그리면서, 각 scatter plot의 점 색깔 바꾸기
fig, ax = plt.subplots(1, 2, figsize=(10, 6))
ax[0].scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')
ax[1].scatter(data3, data4, s=50, facecolor='C1', edgecolor='m')

Scatter plot의 점 모양 바꾸기
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(data1, 'o', label='data1') # 동그라미 (o)
ax.plot(data2, 'd', label='data2') # 마름모 (diamond)
ax.plot(data3, 'v', label='data3') # 역삼각형 (v)
ax.plot(data4, 's', label='data4') # 정사각형 (square)
ax.legend()

히스토그램 그리기
mu, sigma = 115, 15 #평균, 표준편차
x = mu + sigma * np.random.randn(10000)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# Histogram이 반환하는 튜플 형태의 값을 변수 여러 개를 나열해 한 번에 받기
# n : 빈도수/높이, 각 막대의 높이값. 여기서는 randn을 썼으므로 확률밀도 값
# bins : 구간 경계. 전체 경계 수 + 1
# patches : 그래프에 그려진 각각 막대들의 리스트
n, bins, patches = ax.hist(x, 50, density=True, facecolor='C0', alpha=0.75)
ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengthes\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
# 그래프 위에 수학 기호를 적기 위해 사용
# r : raw string, 수학 기호를 사용하기 위해 백슬래시를 문자 자체로 써야 하므로
# raw string(글자 그대로 받아들이는 string)으로 지정한다
# $ : LaTeX 문법으로, $ 사이의 내용은 수학 공식처럼 렌더링한다. (Matplotlib 지원 기능)
# \ : LaTeX 문법으로, \mu, \sigma는 그리스 문자 표현, ,\는 쉼표를 찍고 강제로 한 칸 띄우는 것
ax.axis([55, 175, 0, 0.03])
ax.grid(True)

'TIL' 카테고리의 다른 글
| 251201_BootCamp Day 31_머신러닝 기초 (1) (2) | 2025.12.01 |
|---|---|
| 251128_BootCamp Day 30_데이터 분석 기초 프로젝트 (完) (1) | 2025.11.28 |
| 251126_BootCamp Day 28_데이터 분석 기초 프로젝트 (5) (2) | 2025.11.26 |
| 251125_BootCamp Day 27_데이터 분석 기초 프로젝트 (4) (0) | 2025.11.25 |
| 251124_BootCamp Dat 26_데이터 분석 기초 프로젝트 (3) (1) | 2025.11.24 |