Matplotlib 사용해보기(산점도 scatter)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

scatter 산점도

  • 가로축, 세로축 모두 수치형 받음
  • 범주 넣을 순 있지만 활용도 떨어짐
  • 데이터 간의 얼마나 흩뿌려져있는가를 확인 할 때 사용
  • 데이터 간의 분포를 확인할 때 사용

회귀선, 추세선 같은 것과 조합해서 많이 사용

# 샘플 데이터: 20명의 키(cm)와 몸무게(kg)
np.random.seed(42)
heights = np.random.normal(170, 10, 1000)  # 평균 170cm, 표준편차 10
weights = heights * 0.8 - 60 + np.random.normal(0, 5, 1000)  # 키에 비례 + 노이즈
plt.figure(figsize=(5,3))

# scatter에서는 alpha값이 중요하다
# 낮은 알파값으로 데이터의 중복을 진하게 표현가능하다 > 데이터가 밀집된 곳 표현이 가능
plt.scatter(heights, weights,
            s=80,  # 마커(점) 사이즈
            marker=r'$\heartsuit$',
            color='red',
            alpha=0.1
            )

plt.title('키와 몸무게의 관계')
plt.xlabel('키(cm)')
plt.ylabel('몸무게(kg)')
plt.show()

추세선 추가하기

plt.figure(figsize=(5,3))
plt.scatter(heights, weights,
            s=80,  # 마커(점) 사이즈
            marker=r'$\heartsuit$',
            color='red',
            alpha=0.1
            )

# 추세선을 계산
z = np.polyfit(heights, weights, 1)  # 1: 1차 방정식 / polyfit: 1차 다항식을 이용해서 추세선을 나타내는 기울기와 절편
p = np.poly1d(z)  # 계산된 z를 사용해 다항식 함수 p를 생성
plt.plot(heights, p(heights), '--', alpha=0.8, color='y')  # p로 예측된 값을 선으로 그리는 함수

plt.show()

Matplotlib 사용해보기(선 그래프 plot, subplots)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

기본 데이터는 아래와 같다.

months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales = [100, 120, 90, 140, 160, 180]

# DataFrame으로 만들기
df = pd.DataFrame({
    '월': months,
    '매출': sales
})

line

  • 시간 변화: 매출 추이, 주가변동, 기온변화 등
  • 트렌드 분석: 성장률, 감소율, 계절성 패턴 등
  • 예측한 결과: 머신러닝 구동 후 결과 등
  • 시축을 기준으로 한 비교 분석: 여러가지 지표(년도)를 두고 표현 가능

선차트, 바차트는 통계청 데이터와 같이 가동된 혹은 피벗된 데이터도 표현 가능!

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

# line chart 구현
plt.plot(df['월'], df['매출']) 

plt.title('월별 매출 변화')
plt.ylabel('매출(만원)')
plt.xlabel('2024년')
plt.show()

시축(시간데이터) 다루기

# 데이터
date = pd.date_range('2024-01-01', periods=30, freq='MS')
np.random.seed(0)  # 같은 정보를 보기위해서 랜덤 고정 > 이거 없으면 데이터가 계속 변함

visitors = 1000 + np.random.randint(-100,150,30)
plt.figure(figsize=(8,4))
plt.plot(date, visitors,
         ':',  # 라인 스타일 (-- & -. & : 등으로도 가능) > 라인스타일 만들어주는 위치 중요!
         marker="o",  # 각 포인트에 원하는 마커 찍기 (*, ^, o)
         markersize=15,  # 마커 사이즈
         markerfacecolor='pink',  # 마커 컬러
         markeredgecolor='red',   # 마커 라인 컬러
         linewidth=4  # 라인 굵기
         )

# x축 레이블 기울기 rotations 통해 주기
plt.xticks(rotation=45)  

plt.title('월별 방문자 수')
plt.ylabel('방문자 수')
plt.show()

여러개의 선 그래프 구현

# 데이터
months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales_1 = [100, 120, 90, 140, 160, 180]
sales_2 = [90, 70, 80, 130, 150, 170]
sales_3 = [110, 130, 120, 150, 90, 110]
plt.figure(figsize=(5,3))

plt.plot(months, sales_1,
         ':',
         marker="o",
         markersize=15,
         markerfacecolor='pink',
         markeredgecolor='red',
         linewidth=4
         )

plt.plot(months, sales_2,
         ':',
         marker="o",
         markersize=15,
         markerfacecolor='pink',
         markeredgecolor='red',
         linewidth=4
         )

plt.plot(months, sales_3,
         ':',
         marker="o",
         markersize=15,
         markerfacecolor='pink',
         markeredgecolor='red',
         linewidth=4
         )

plt.xticks(rotation=45) 

plt.title('월별 방문자 수')
plt.ylabel('방문자 수')
plt.show()

라인차트 위 어노테이션

  • 바 차트에서는 text를 입혀주는 형식
  • 선 차트에서는 위치를 맞춰서 어노테이션을 맞춰준다
# 데이터 
months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales = [100, 120, 90, 140, 160, 180]
plt.figure(figsize=(5,3))
plt.plot(months, sales,
         marker=r'$\heartsuit$',
         markersize=10,
         markeredgecolor='red',
         color='pink'
         )

# 수치를 대입하는 어노테이션
for x,y in zip(months, sales):
    # f'{y}', (x,y)에서 f'{y}'는 sales값이 들어가고 
    # (x,y)는 좌표임 (1월에 100, 2월에 120을 표현해라~)
    # textcoords: 마커 위치로 부터 주변 단위 표현
    # xytext=(0,10): x축으로부터 -10포인트 이동, y축으로부터 10포인트 이동
    plt.annotate(f'{y}', (x,y), textcoords='offset points', xytext=(-10,10))

plt.show()

이중축 표현 > subplots

# 데이터  
months = [1, 2, 3, 4, 5, 6]
sales = [100, 120, 90, 140, 160, 180]      # 매출 (백만원)
visitors = [1600, 1450, 950, 1300, 1200, 1600]  # 방문자 (명)
# fig > 테이블을 구현, 위치에 따라 셋팅이 됨 (fig1, fig2...)
# fig1에 맞춰 fig의 ax라는 듯 > (fig1 -> ax1, fig2 -> ax2)
fig1, ax1 = plt.subplots(figsize=(5, 3)) #여러 시각화를 구현할 때 사용이 된다!!

# 왼쪽 레이블
ax1.plot(months, sales, marker=r'$\heartsuit$', markersize=10, markeredgecolor='r', color='pink')
ax1.set_xlabel('월')
ax1.set_ylabel('매출(백만원)', color='brown')

# 이중축 구현하기 위한 핵심!!
ax2 = ax1.twinx() 

# 오른쪽 레이블
ax2.set_ylabel('방문객', color='blue')
ax2 = ax2.plot(months, visitors,'--', marker=r'*', markersize=10, markeredgecolor='y', color='y')

전체에서 일부를 함께 표현해보기

# 데이터 > 전체기간과 특정 구간 동시 표시
days = list(range(1,101))
np.random.seed(42)
data = np.cumsum(np.random.randn(100))
fig, (ax1, ax2) = plt.subplots(2,1,figsize=(6,4)) # 두개의 시각화가 구성이됨(2x1)

# 음수 표현 깨질 때 사용
plt.rcParams['axes.unicode_minus'] = False

ax1.plot(days, data, linewidth=1)
ax1.set_facecolor('black')
ax1.set_title('전체 기간')
ax1.set_ylabel('값')

ax2.plot(days[20:40], data[20:40])  # 특정 부분을 확대
ax2.set_title('20에서 40일 사이 데이터')
ax2.set_ylabel('값')
ax2.grid(alpha=0.1)

# 두 그래프 간 자동 여백 조절
# fig.subplots_adjust(hspace=0.5) > hspace를 통해 간격 세밀 조정 가능
plt.tight_layout()

plt.show()

콤비네이션 바-라인 차트

fig, ax1 = plt.subplots(figsize=(5, 3)) #여러 시각화를 구현할 때 사용이 된다!!

ax1.bar(months, sales)
ax1.set_xlabel('월')
ax1.set_ylabel('매출(백만원)', color='r')

ax2 = ax1.twinx() 
ax2.set_ylabel('방문객', color='blue')
ax2 = ax2.plot(months, visitors,'--', marker=r'$\heartsuit$', markersize=10, markeredgecolor='y', color='pink')

Matplotlib 사용해보기(stack bar, 100% stack bar)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

기본 데이터는 아래와 같다.

# 간단한 매출 데이터 만들기
months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales_05 = [100, 120, 90, 140, 160, 180]
sales_04 = [80, 100, 97, 120, 140, 160]
sales_03 = [120, 140, 110, 160, 180, 200]

# DataFrame으로 만들기
df = pd.DataFrame({
    '월': months,
    '05매출': sales_05,
    '04매출': sales_04,
    '03매출': sales_03
})

여러개의 막대차트 구현

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

x = np.arange(len(months))
width = 0.25

# (표현할 막대의 위치, 데이터, 막대넓이)
plt.bar(x-width, df['05매출'], width)
plt.bar(x, df['04매출'], width)
plt.bar(x+width, df['03매출'], width)

plt.xticks(x, df['월'])

# 레전드 설정
# plt.legend(['2023', '2024', '2025'], loc='upper right')
plt.legend(df.columns[1:], fontsize = 15)  # 레전드의 폰트사이즈
plt.title('년도별 성과')
plt.ylabel('매출(만원)')
plt.xlabel('년도')

# 그리드 / 투명도 설정 
plt.grid(True, alpha=0.3)
plt.show()

Stack Bar

# 데이터: 지역별 온라인/오프라인 매출
regions = ['서울', '부산', '대구', '인천']
online_sales = [150, 120, 80, 100]
offline_sales = [200, 160, 110, 120]

plt.figure(figsize=(4,3))

plt.bar(regions, online_sales)
# online_sales 아래에 표현하겠다 의미
plt.bar(regions, offline_sales, bottom=online_sales)  

plt.title('지역별 온라인/오프라인 매출 비교')
plt.show()

100% Stack Bar

  • 파이차트와 역할이 비슷
  • 데이터의 비율을 표현할 때 사용
# 비율로 변환
total_sales = [online + offline for online, offline in zip(online_sales, offline_sales)]
online_pct = [online/total*100 for online, total in zip(online_sales, total_sales)]
offline_pct = [offline/total*100 for offline, total in zip(offline_sales, total_sales)]

plt.figure(figsize=(8, 6))
plt.bar(regions, online_pct, label='온라인 (%)', color='skyblue')
# bottom=online_pct > 데이터를 비율로 전환후, stack 표현
plt.bar(regions, offline_pct, bottom=online_pct,
        label='오프라인 (%)', color='lightcoral')

plt.title('지역별 온라인/오프라인 매출 비율')
plt.xlabel('지역')
plt.ylabel('비율 (%)')
# y축의 범위를 설정 (최소0, 최대100)
plt.ylim(0, 100)
plt.legend()
plt.show()

Matplotlib 사용해보기(막대차트 bar, barh)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib

import matplotlib.pyplot as plt

기본 데이터는 아래와 같다.

# 간단한 매출 데이터 만들기
months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales = [100, 120, 90, 140, 160, 180]

# DataFrame으로 만들기
df = pd.DataFrame({
    '월': months,
    '매출': sales
})

Bar (bar)

  • 일반적으로 가로축> 범주, 세로축>
  • 데이터간의 크기를 비교하는데에 주로 사용됨
  • 굉장히 기본적이고 많이 사용하는 시각화 중 하나
  • 최대 3개의 정보를 표현가능(가로축, 세로축 색 지정 기준)
  • 격자 나누기 기능을 사용해서 여러 컬럼 다룰수 있기는 함 (추가적인 정보를 표현하고 싶을때)
# plt는 matplotlib의 약어, 형태의 사이즈(가로, 세로)를 지정 
plt.figure(figsize=(4,2))

# bar chart 구현 > 가로, 세로축에 들어갈 데이터 지정 
plt.bar(df['월'], df['매출'])

# 제목 설정
plt.title('월별 매출 변화')
# y축 라벨 설정
plt.ylabel('매출(만원)') 
# x축 라벨 설정
plt.xlabel('2024년')

plt.show()

가로축 Bar (barh)

  • 바차트에서 가로축 정보는 정상형태일때 정보
  • 세로축: 범주, 가로축: 수치
  • 카테고리명이 길때 혹은 카테고리가 많을때
  • 순위를 강조하고 싶을때 사용
plt.figure(figsize=(8,2)) 
plt.barh(df['월'], df['매출'])  

plt.title('월별 매출 변화')
plt.xlabel('매출(만원)')
plt.ylabel('2024년')
plt.show()

데이터 정렬 후 차트 생성해보기

# 데이터 정렬
sales_data = list(zip(months, sales))  # 데이터 zip 통해 묶어줌
sales_data.sort(key=lambda x: x[1], reverse=False)  # 내림차순 정렬
#key = lambda x: x[1] 는 [('1월', 100), ('2월', 120), ('3월', 90), ('4월', 140), ('5월', 160), ('6월', 180)] 에서 뒤에 숫자를 기준으로 정렬한다!!

# 데이터를 다시 x축, y축에 넣을 것을 정리
months_s = [x[0] for x in sales_data]
sales_s = [x[1] for x in sales_data]

plt.figure(figsize=(8,2)) 
plt.barh(months_s, sales_s)  
plt.title('월별 매출 변화')
plt.xlabel('매출(만원)') 
plt.ylabel('2024년') 
plt.show()

Bar Chart 이모저모

  1. 차트 배경 색상 지정 > plt.fugure(facecolor=)r
plt.figure(figsize=(4,2), facecolor='y')
  1. 막대 색상 지정 > plt.bar(color=)
plt.bar(months_s, sales_s, color='skyblue')
  1. 원하는 막대의 색상 지정
# sales_s의 최댓값에만 색상 지정 
color = ['red' if x == max(sales_s) else 'blue' for x in sales_s]
plt.bar(months_s, sales_s, color=color)

# or
# 100만원 넘으면 빨간색, 100만원 이하면 파란색
def color_div(value):
    if value > 100:
        return 'red'
    else:
        return 'blue'

color = [color_div(x) for x in sales_s]
plt.bar(months_s, sales_s, color=color)
  1. 막대 위에 값 표시하기
plt.figure(figsize=(4,2))
bars = plt.bar(months_s, sales_s)  # bars > 변수로 설정해주고 아래서 받기
plt.title('월별 매출 변화')
plt.ylabel('매출(만원)')
plt.xlabel('2024년')

# plt.text > 그래프 위에 글자를 덧씌우는 것
# get_x(): 왼쪽 모서리 좌표 출력
# get_width(): 가로 좌표
# get_height(): 세로 좌표
for bar, value in zip(bars, sales_s):
    # get_x(): 왼쪽 모서리 좌표 출력
    plt.text(bar.get_x()+bar.get_width()/2, bar.get_height(), f'{value}', ha='center', va='bottom')
    plt.ylim(0,200)

plt.show()
  1. 막대 조절
edge = ['black' if x > 100 else 'pink' for x in sales_s]
plt.figure(figsize=(4,2))
plt.bar(months_s, sales_s, color=color,
        width=0.6,  # 너비 조절
        edgecolor=edge,  # 테두리 색상
        linewidth=2,  # 테두리 두께
        alpha=0.5  # 막대 불투명도
        )
plt.title('월별 매출 변화')
plt.ylabel('매출(만원)')
plt.xlabel('2024년')
plt.show()

Matplotlib 한글깨짐 현상 폰트 설치

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


Matplotlib 한글깨짐 현상

Matplotlib 으로 통계차트를 만들다보면 한글깨짐 현상이 발생한다.

이때 아래 코드를 실행해서 한글 폰트를 설치해주자.

# 시각화도구
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# 한글 글씨 폰트 설치 
%%capture
!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf

fm.fontManager.addfont('/usr/share/fonts/truetype/nanum/NanumGothic.ttf')
plt.rcParams['font.family'] = 'NanumGothic'

이때 만약

UsageError: Line magic function `%%capture` not found.

이러한 에러가 떴다면 아래와 같이 해결해보자!

%%capture 가 맨 윗단에 위치해서 실행되어야 하기 때문에 발생하는 것

%%capture
# 시각화도구
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# 한글 글씨 폰트 설치 
!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf

fm.fontManager.addfont('/usr/share/fonts/truetype/nanum/NanumGothic.ttf')
plt.rcParams['font.family'] = 'NanumGothic'

혹은 맥에서는

import matplotlib.pyplot as plt

plt.rc('font', family='AppleGothic')
plt.rcParams['axes.unicode_minus'] = False