[Data Analysis] 데이터 시각화 해보기

2025. 3. 23. 18:21·Data Analysis/Basic
대표적인 파이썬 시각화 라이브러리에는 Matplotlib, Seaborn, Pandas Visualization, Plotly, Bokeh 등이 있는데 오늘은Matplotlib 라이브러리를 이용해 데이러틀 시각화 해보았다
 
https://wikidocs.net/92071
 

01. Matplotlib 기본 사용

![](https://wikidocs.net/images/page/92071/basics_00.png) Matplotlib 라이브러리를 이용해서 그래프를 그리는 일반적인 방…

wikidocs.net

Matplotlib 특징

1. 선 그래프(Line Graph), 막대 그래프(Bar Chart), 산점도(Scatter Plot), 히스토그램(Histogram), 파이 차트(Pie Chart) 등 다양한 유형의 시각화를 지원함

2. 풍부한 옵션과 유연성

레이블, 색상, 선 스타일, 마커 스타일, 글꼴 속성 등 상세한 옵션 조정이 가능하고 목적에 맞게 커스터마이징하여 데이터 시각화 가능

3. 호환성
NumPy, Pandas와 같은 데이터 분석 라이브러리와 자연스럽게 연동되어 데이터 전처리와 분석에 효율적으로 활용 가능하다고 한다.

 

 

 

출력 형식

라이브러리 설치 및 임포트
# pip install matplotlib
import matplotlib.pyplot as plt

%matplotlib inline

 

%matplotlib inline?

주피터 노트북과 같은 인터랙티브 환경에서 matplotlib 그래프를 별도의 팝업 창이 아닌 노트북 셀 내부에 바로 출력하도록 설정하기 위해 사용함 → 하지만 최근 주피터 노트북 버전에서는 그래프가 기본적으로 인라인으로 표시
 
그래도 혹시 모르니 명시적으로 표시해줌
 

그래프 스타일 설정

Matplotlib은 style 기능을 통해 그래프의 전체적인 시각적 스타일을 간편하게 변경할 수 있는 기능을 제공한다. 내장된 스타일 세트를 활용해 배경, 색상 팔레트, 그리드 라인 등의 전반적인 그래프 분위기를 빠르게 변경할 수 있음

 
1) 사용 가능한 스타일 확인: `plt.style.available`
# 사용 가능한 스타일 목록 확인
for style in plt.style.available:
    print(style)
 
2) 스타일 적용:** `plt.style.use('ggplot')`
plt.style.use('ggplot')

폰트 설정

  * 시스템에 설치된 폰트만 사용 가능하다
 
    * `Windows`: 'Calibri', 'Arial', 'Times New Roman' 등
   
    * `macOS`: 'Helvetica', 'Arial' 등
 
# 폰트 설정 모듈 호출
from matplotlib import rcParams

# Times New Roman 폰트를 설정
rcParams['font.family'] = 'Times New Roman'

# 한글 폰트 설정
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['axes.unicode_minus'] = False  # 마이너스 깨짐 방지

그래프 저장

plt.savefig() 

  • Matplotlib 그래프를 이미지 파일로 저장할 때 사용한다
  • 옵션:
    • dpi: 이미지 해상도 (기본값 100)
    • transparent: 배경 투명 여부 (True/False)
    • bbox_inches: 이미지 여백 조정 ('tight' 추천)
import numpy as np

# 데이터 생성
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 데이터 시각화
plt.plot(x, y)
plt.title("Sin Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")

# 그래프 출력
plt.show()

# 그래프 저장 (PNG 형식, 해상도 300 DPI)
plt.savefig('sin_wave.png', dpi=300, bbox_inches='tight')

 

주의:

plt.show() 이후에 plt.savefig()를 호출하면 그래프를 저장하지 못할 수 있다. 항상 'plt.savefig()`를 `plt.show()` 전에 호출

 

파일 형식:

저장되는 파일의 형식은 파일 이름의 확장자에 따라 결정됨 ( 예: .png, .jpg, .pdf, .svg 등 )

# 기본 저장
plt.savefig('plot.png')

# 고해상도 + 투명 배경 + 여백 제거
plt.savefig('plot.svg', dpi=300)

# 배경 색상 지정
plt.savefig('plot.jpg', facecolor='white', dpi=200)

# PDF 저장
plt.savefig('plot.pdf', facecolor='white', dpi=200)

 

Matplotlib 그래프 생성 방식

1. pyplot 방식
   
   * 그림과 축을 자동으로 관리하여 빠르게 간편한 그래프 생성을 지원하는 방식
   * 간단한 그래프나 실습 목적의 시각화에 적합

2. 객체지향 방식(Object-oriented Interface)
   
   * 명시적으로 그림(Figure)과 축(Axes)을 생성하고 객체의 메서드를 호출하여 그래프를 생성하는 방식
   * 보다 세부적인 제어가 가능하며 복잡한 그래프 생성 시 유리함

 

 

pyplot 방식

그림(Figure)과 축(Axes)의 자동 관리 방식

  • 장점:
    • 간단한 그래프나 빠르게 결과를 확인할 때 가장 널리 사용됨.
    • 코드가 간결해지고, 빠르게 시각화를 확인할 수 있음.
  • 단점:
    • 복잡한 시각화에서는 세부 옵션 설정에 제한이 있음.
    • 고급 기능이나 세부적인 조정이 필요할 경우 불편할 수 있음.
import numpy as np

# 데이터 생성
x = np.linspace(0, 10, 100)

# 데이터 시각화
plt.plot(x, np.sin(x))
plt.show()

 

객체지향 방식

* 사용자가 명시적으로 그림과 축 객체를 생성하고 관리하는 방식

* 그래프의 세부 옵션을 자유롭게 조정할 수 있어 복잡한 시각화 작업 시 효과적임

 

plt.subplots() 함수 사용법

  • plt.subplots(): 여러 개의 서브플롯을 동시에 생성할 때 사용하여 코드를 간결하고 명확하게 작성할 수 있음.
    • plt.subplots(nrows, ncols): 전체 그래프 영역(Figure)을 n행 × n열로 분할하여 서브플롯을 생성. 예를 들어, plt.subplots(1, 1)은 1행 1열로 그래프 1개를 생성.
    • fig: 전체 그래프 영역을 나타내는 Figure 객체. 전체 크기나 레이아웃, 저장 등을 제어할 수 있음.
    • (ax1, ax2): 각각의 서브플롯을 나타내는 Axes 객체들. ax1.plot, ax2.bar와 같이 각 서브플롯에 개별적으로 그래프를 그릴 수 있음.
# 데이터 생성
x = np.linspace(0, 10, 100)

# 1행 1열의 서브플롯 생성
fig, ax = plt.subplots(1, 1, figsize=(10, 5))

# 데이터 시각화
ax.plot(x, np.sin(x))
plt.show()

 

여러 개의 서브플롯 생성

1x2 그리드

# 1x2 그리드의 서브플롯 생성
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))  

# 첫 번째 서브플롯
ax1.plot(x, np.sin(x))
ax1.set_title('sin(x)')

# 두 번째 서브플롯
ax2.plot(x, np.cos(x))
ax2.set_title('cos(x)')

plt.show()

2x2 그리드

# 데이터 생성
x = np.linspace(0, 10, 100)

# 2행 2열 서브플롯 생성
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10, 8))

# 첫 번째 서브플롯
ax1.plot(x, np.sin(x))
ax1.set_title('sin(x)')
ax1.set_xlabel('x')
ax1.set_ylabel('sin(x)')

# 두 번째 서브플롯
ax2.plot(x, np.cos(x), '--')
ax2.set_title('cos(x)')
ax2.set_xlabel('x')
ax2.set_ylabel('cos(x)')

# 세 번째 서브플롯
ax3.plot(x, x)
ax3.set_title('y = x')
ax3.set_xlabel('x')
ax3.set_ylabel('y')

# 네 번째 서브플롯
ax4.plot(x, -x)
ax4.set_title('y = -x')
ax4.set_xlabel('x')
ax4.set_ylabel('y')

# 서브플롯 간 간격 자동 조정
plt.tight_layout()

plt.show()

히스토그램(Histogram) 그리기

예시 : 국가별 교통사고 사망률
import pandas as pd

traffic = pd.read_csv("deathrates.csv")
print("데이터프레임 크기:", traffic.shape)
traffic.head()

 

`plt.hist()`
plt.hist(traffic["death"])
plt.show()

`plt.hist()` 파라미터

 
    * `bins`: 급간 개수
   
    * `color`: 막대 색상
   
    * `alpha`: 투명도
   
    * `edgecolor`: 테두리 색상
   
    * `linewidth`: 테두리 선 두께
 
 
히스토그램의 색상을 변경하거나 제목 등을 추가하기 위해 다양한 인자를 사용할 수 있음 → Matplotlib의 모든 그래프에 동일하게 적용 가능함
 
  * `plt.figure()`: 그래프 전체 틀 설정 (크기, 해상도, 배경색 등)

  * `plt.title()`: 그래프 제목 설정 (텍스트, 크기, 위치, 색상 등)
 
  * `plt.xlabel()` / `plt.ylabel()`: 축 이름 지정
 
  * `plt.ylim()` / `plt.xlim()`: 축 범위 설정
 
plt.hist(traffic["death"], 
         bins=6, 
         color= "lightblue", 
         alpha=0.7, 
         edgecolor="black", 
         linewidth=0.5)

plt.show()

 

pyplot 방식

# 그래프 크기 설정
plt.figure(figsize=(8, 5))

# 히스토그램 생성성
plt.hist(traffic["death"], 
         bins=6, 
         color= "lightblue", 
         alpha=0.9, 
         edgecolor="black", 
         linewidth=0.5)

# 제목, 축 레이블 설정
plt.title('Traffic Death Rates', fontsize=14, fontweight='bold', pad=20)
plt.xlabel('Death Rates', fontsize=10, labelpad=10, color='black')         
plt.ylabel('Frequency', fontsize=10, labelpad=10, color='black')   
plt.ylim(0, 20)   

plt.show()

 

객체 지향 방식

# 그림(Figure) 및 축(Axes) 생성
fig, ax = plt.subplots(figsize=(8, 5))

# 히스토그램 생성
ax.hist(traffic["death"], 
    bins=6, 
    color="lightblue", 
    alpha=0.7, 
    edgecolor="black", 
    linewidth=0.5)

# 제목, 축 레이블 설정
ax.set_title('Traffic Death Rates', fontsize=14, fontweight='bold', pad=20)
ax.set_xlabel('Death Rates', fontsize=10, labelpad=10, color='black')
ax.set_ylabel('Frequency', fontsize=10, labelpad=10, color='black')
ax.set_ylim(0, 20)

# 그래프 출력
plt.show()

색상 추가

Matplotlib에서 그래프의 다양한 요소(예: 배경, 선, 텍스트, 축 등)의 색상을 설정할 수 있는데, 일반적으로 색상의 '이름'을 직접 입력하여 색상을 지정하는 방법을 주로 사용함 ( 예: 빨강(red), 파랑(blue), 갈색(brown), 검정색(black) 등등 )

 

from matplotlib import colors

# 사용 가능한 모든 색상 이름 출력
for name, hex in colors.CSS4_COLORS.items():
    print(name, hex)
https://matplotlib.org/stable/gallery/color/named_colors.html
 

List of named colors — Matplotlib 3.10.1 documentation

List of named colors This plots a list of the named colors supported by Matplotlib. For more information on colors in matplotlib see Helper Function for Plotting First we define a helper function for making a table of colors, then we use it on some common

matplotlib.org

막대그래프

예시 : 도시 인구 변화

pop = pd.read_csv("popcities10.csv")
print(pop.shape)
pop.head(10)

`plt.bar()`
plt.bar(pop['municipality'][:10], pop['pop10'][:10])
plt.show()

x축의 도시 이름이 정확하게 표시되지 않는 문제는 `plt.figure()` 또는 `plt.xticks(rotation=60)`를 사용하여 효율적으로 해결할 수 있음
plt.figure(figsize=(10, 5))
plt.bar(pop['municipality'][:10], pop['pop10'][:10])
# plt.xticks(rotation=45)  # x축 레이블 회전
plt.show()

plt.figure(figsize=(12, 8))
plt.bar(pop['municipality'][:10], pop['pop10'][:10] / 1000) # 인구 단위 변환
plt.title('Population Change in Selected Cities')
plt.xlabel('City')
plt.ylabel('Population (in thousands)')

plt.show()

 

수평 막대 `plt.barh()`

# 그래프 크기 설정
plt.figure(figsize=(12, 8))

# 막대 그래프 생성
plt.barh(pop['municipality'][:10], pop['pop10'][:10] / 1000)

# 제목 및 축 라벨 추가 
plt.title('Population Change in Selected Cities')
plt.xlabel('Population (in thousands)')
plt.ylabel('City')

plt.show()

여러 막대 그리기

# 그래프 크기 설정
plt.figure(figsize=(12, 8))

# 도시 선택
selected_cities = pop['municipality'][:10]
pop_2000 = pop['pop00'][:10] / 1000
pop_2005 = pop['pop05'][:10] / 1000
pop_2010 = pop['pop10'][:10] / 1000

# X축의 위치 설정
x = np.arange(len(selected_cities))

# 막대그래프 그리기
plt.bar(x, pop_2000, width=0.2, label='2000 years')
plt.bar(x + 0.2, pop_2005, width=0.2, label='2005 years')
plt.bar(x + 0.4, pop_2010, width=0.2, label='2010 years')

# X축에 도시 이름 표시
plt.xticks(x + 0.2, selected_cities)

# 범례 표시
plt.legend()

# 제목 및 축 라벨 추가
plt.title('Population Change in Selected Cities')
plt.xlabel('Population (in thousands)')
plt.ylabel('City')

# 그래프 표시
plt.show()

원형 그래프

plt.pie(pop['pop10'][:10], labels=pop['municipality'][:10])
plt.show()

 

 

옵션

  * `explode`: 특정 조각을 강조하기 위해 중심에서 살짝 떨어뜨리는 설정 (리스트 형식, 예: [0.1, 0, 0, ...])
 
  * `labels`: 각 조각에 표시될 항목 이름 (예: 도시 이름)
 
  * `autopct`: 각 항목의 비율을 자동 계산하여 표시 ('%1.1f%%'는 소수점 1자리 퍼센트로 표시)
 
  * `shadow`: 입체감을 주기 위한 그림자 효과
 
  * `startangle`: 그래프가 시작되는 각도를 나타내며, 90도는 위쪽에서 시작함

 

# 그래프 크기 설정
plt.figure(figsize=(12, 8))

# 각 도시에 대해 돌출 정도 설정 (예: 첫 번째 도시만 돌출)
explode = (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # 첫 번째 도시만 0.1만큼 돌출

# 원형 그래프 생성
plt.pie(pop['pop10'][:10], 
        explode=explode, 
        labels=pop['municipality'][:10],
        autopct='%1.1f%%', 
        shadow=True, 
        startangle=90)

plt.axis('equal')  # 원의 형태를 유지
plt.title('Population Distribution in Cities')
plt.show()

 

산점도

예시: 항공사 아웃 소싱 데이터

 

`plt.scatter()`
plt.scatter(flights["outsourcing"], flights["delays"])
plt.show()

* x와 y 좌표를 지정하지 않는 경우에는 함수에 전달된 첫 번째 데이터 배열이 x 좌표로 인식되고 두 번째 데이터 배열이 y 좌표로 자동으로 인식됨

*  `plt.scatter()` 함수를 통해 생성되는 산점도는 다음과 같이 다양한 인자를 사용하여 효과적으로 표현될 수 있음
 
   * `marker`: 각 데이터 포인트의 마커(모양)를 지정
     * 예: `'s'`=정사각형, `'x'`=x표, `'d'`=다이아몬드 등
 
   * `s`: 각 점의 크기를 설정
 
   * `c`: 점의 색상을 설정
     * 예: `'b'`=파랑, `'g'`=초록, `'k'`=검정, `'y'`=노랑 등
 
plt.scatter(flights["outsourcing"], flights["delays"], marker='o', s=30, c='g')

 

https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#sphx-glr-gallery-lines-bars-and-markers-marker-reference-py
 

Marker reference — Matplotlib 3.10.1 documentation

Marker reference Matplotlib supports multiple categories of markers which are selected using the marker parameter of plot commands: For a list of all markers see also the matplotlib.markers documentation. For example usages see Marker examples. import matp

matplotlib.org

 

plt.plot() 함수를 통해 똑같이 사용 가능

plt.plot(flights["outsourcing"], flights["delays"], marker = 'x', linestyle='None')  # 'o' 마커를 사용하여 점으로 표시
plt.show()​
x = [10, 20, 30, 40, 50, 60, 70]     
y = [5, 7, 10, 13, 15, 18, 22]          

plt.plot(x, y, marker='o', linestyle=':', linewidth=2)
plt.show()
* `plt.plot()` 함수에서 `linestyle` 인자를 통해 다양한 유형의 선(line)을 추가할 수 있음
 
  * `'-'`: 실선 (solid line)

  * `'--'`: 파선 (dashed line)

  * `'-.'`: 일점쇄선 (dash-dot line)

  * `':'`: 점선 (dotted line)

* 선의 두께는 `linewidth` 인자를 통해 설정이 가능함
 

 

 

`plt.axhline()`
그래프에 수평선을 추가하여 특정 기준선이나 임계값을 시각적으로 강조할 때 유용함
 
plt.scatter(flights["outsourcing"], flights["delays"], marker='v')
plt.axhline(y=20, color='b', linestyle='--', linewidth=1)
plt.show()

'Data Analysis > Basic' 카테고리의 다른 글

[Data Analysis] 워드 임베딩 (Word Embedding) 정리  (0) 2025.05.01
[Data Analysis] 데이터 전처리 해보기  (0) 2025.03.29
[Data Analysis] 데이터 정제 및 분석 해보기  (0) 2025.03.23
[Data Analysis] Pandas 라이브러리 연습 2  (0) 2025.03.20
[Data Analysis] Pandas 라이브러리 연습  (0) 2025.02.25
'Data Analysis/Basic' 카테고리의 다른 글
  • [Data Analysis] 워드 임베딩 (Word Embedding) 정리
  • [Data Analysis] 데이터 전처리 해보기
  • [Data Analysis] 데이터 정제 및 분석 해보기
  • [Data Analysis] Pandas 라이브러리 연습 2
임승택
임승택
"Hello, I am Lim Seungtaek, a computer engineering student. Nice to meet you!"
  • Lim's Technology
    임승택
    임승택
    "Welcome to Lim's Technology!"
  • 누적 조회수
    총 회
    구독하기
    • 분류 전체보기 (102)
      • Blog (10)
      • Computer Vision (44)
        • Computer Vision (4)
        • Paper reviews (24)
        • Project (8)
        • Basic (8)
      • LLM (8)
        • Paper reviews (3)
        • Project (3)
        • Basic (2)
      • Data Analysis (11)
        • Basic (8)
        • Project (3)
      • Computer Graphics (2)
        • Basic (2)
      • Robotics (5)
        • Paper reviews (3)
        • Basic (2)
      • Technology Notes (15)
      • Memo (5)
  • 인기 글

  • 최근 댓글

  • 최근 글

임승택
[Data Analysis] 데이터 시각화 해보기
상단으로

티스토리툴바