Matplotlib - 5. 데이터와 상호작용

2025. 1. 21. 12:38프로그래밍 (확장)/Python-Matplotlib

Matplotlib은 다양한 데이터 소스와 결합하여 시각화 작업을 수행할 수 있습니다. Pandas와 NumPy 같은 데이터 분석 라이브러리와 통합하거나, 대화형 그래프를 통해 데이터를 탐색하는 기능도 제공합니다. 이 섹션에서는 데이터와 상호작용하는 방법을 다룹니다.


5.1 Pandas와 Matplotlib

개요

Pandas의 DataFrame은 데이터를 구조적으로 관리하는 데 유용하며, Matplotlib과 결합하여 데이터를 쉽게 시각화할 수 있습니다.

예제: Pandas DataFrame 데이터를 시각화

예제:

import pandas as pd
import matplotlib.pyplot as plt

# 데이터 생성
data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Product A": [30, 35, 40, 45, 50],
    "Product B": [20, 25, 30, 35, 40]
}
df = pd.DataFrame(data)

# 그래프 그리기
df.plot(x="Month", y=["Product A", "Product B"], kind="line", marker="o")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales (Units)")
plt.grid(True, linestyle="--", alpha=0.7)
plt.legend(title="Products")
plt.show()

Tip: Pandas의 plot() 함수는 Matplotlib을 내부적으로 사용하며, 막대 그래프, 히스토그램 등 다양한 그래프를 생성할 수 있습니다.


5.2 NumPy와 Matplotlib

개요

NumPy는 대규모 데이터 배열을 처리하는 데 최적화된 라이브러리입니다. Matplotlib과 함께 사용하면 빠르고 효율적으로 데이터를 시각화할 수 있습니다.

예제: NumPy 배열을 사용한 그래프

예제:

import numpy as np
import matplotlib.pyplot as plt

# 데이터 생성
x = np.linspace(0, 10, 100)  # 0부터 10까지 100개의 점 생성
y1 = np.sin(x)
y2 = np.cos(x)

# 그래프 그리기
plt.plot(x, y1, label="Sine Wave")
plt.plot(x, y2, label="Cosine Wave", linestyle="--")
plt.title("Trigonometric Functions")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()

5.3 데이터 파일 불러오기

개요

CSV나 Excel 파일에 저장된 데이터를 불러와 시각화할 수 있습니다.

예제: CSV 데이터를 그래프로 변환

예제:

import pandas as pd
import matplotlib.pyplot as plt
import dask.dataframe as dd

try:
    # 대용량 CSV 파일 읽기
    data = dd.read_csv("large_file.csv")
    data = data.compute()  # Dask DataFrame을 Pandas DataFrame으로 변환

    # 데이터 전처리 (결측치 제거 및 이상치 처리)
    data.dropna(inplace=True)  # 결측치 제거
    data = data[data["Sales"] > 0]  # 이상치 제거

    # 파일 형식 검증
    if not all(col in data.columns for col in ["Month", "Sales"]):
        raise ValueError("Required columns are missing in the file.")

    # 그래프 그리기
    data.plot(x="Month", y="Sales", kind="bar", color="skyblue")
    plt.title("Monthly Sales from CSV")
    plt.xlabel("Month")
    plt.ylabel("Sales (Units)")
    plt.show()

except FileNotFoundError:
    print("Error: The file 'large_file.csv' was not found.")
except pd.errors.EmptyDataError:
    print("Error: The file is empty.")
except MemoryError:
    print("Error: Insufficient memory to process the file.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

예제: Excel 데이터를 그래프로 변환

예제:

# Excel 파일 읽기
data = pd.read_excel("sales_data.xlsx")

# 데이터 전처리 (결측치 제거)
data.dropna(inplace=True)

# 그래프 그리기
data.plot(x="Month", y="Sales", kind="line", marker="o", color="green")
plt.title("Monthly Sales from Excel")
plt.xlabel("Month")
plt.ylabel("Sales (Units)")
plt.show()

Tip: Excel 파일을 처리하려면 openpyxl 또는 xlrd 라이브러리를 설치해야 합니다:

pip install openpyxl

5.4 대화형 그래프

개요

Matplotlib의 widgets 모듈을 사용하면 슬라이더, 버튼 등을 활용하여 대화형 그래프를 생성할 수 있습니다. 이는 데이터 탐색 및 분석에 매우 유용합니다.

예제: 실시간 데이터 업데이트

예제:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import time

# 초기 설정
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
data = np.sin(x)
line, = ax.plot(x, data)

# 실시간 데이터 함수
def get_real_time_data():
    return np.sin(x + time.time())

# 업데이트 함수
def update_plot(frame):
    line.set_ydata(get_real_time_data())
    return line,

ani = FuncAnimation(fig, update_plot, interval=1000)  # 1초마다 업데이트
plt.show()

예제: 슬라이더를 사용한 대화형 그래프

예제:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

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

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)  # 슬라이더 공간 확보

# 그래프 초기 설정
line, = ax.plot(x, y, lw=2)
ax.set_title("Interactive Sine Wave")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")

# 슬라이더 추가
ax_slider = plt.axes([0.25, 0.1, 0.65, 0.03])  # [x, y, width, height]
slider = Slider(ax_slider, "Frequency", 0.1, 5.0, valinit=1.0)

# 슬라이더 업데이트 함수
def update(val):
    freq = slider.val
    line.set_ydata(np.sin(freq * x))
    fig.canvas.draw_idle()

slider.on_changed(update)

# 메모리 관리: 이벤트 핸들러 제거
import weakref
slider_ref = weakref.ref(slider)
plt.show()
del slider_ref

예제: 버튼을 사용한 데이터 업데이트

예제:

from matplotlib.widgets import Button

fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
y = np.sin(x)
line, = ax.plot(x, y, lw=2)
ax.set_title("Button Example")

# 버튼 추가
ax_button = plt.axes([0.8, 0.02, 0.1, 0.05])
button = Button(ax_button, "Reset")

# 버튼 클릭 이벤트 함수
def reset(event):
    line.set_ydata(np.sin(x))
    fig.canvas.draw_idle()

button.on_clicked(reset)
plt.show()