matplotlib — Figure와 Axes
이 토픽을 마치면
matplotlib의 Figure/Axes 구조를 이해하고, 기본적인 그래프를 직접 그릴 수 있습니다.
matplotlib이 뭔가
matplotlib(맷플롯립)은 Python에서 그래프와 차트를 그리는 라이브러리입니다. 데이터를 눈으로 보면 숫자만 볼 때보다 패턴이 훨씬 잘 보입니다.
python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]
plt.plot(x, y)plt.show()plt는 matplotlib.pyplot의 관례적 약어입니다.
Figure와 Axes
matplotlib의 핵심 구조는 두 가지입니다.
text
Figure (도화지)
└── Axes (그래프 영역)
├── x축 (x-axis)
├── y축 (y-axis)
├── 제목 (title)
└── 데이터 (lines, bars, points...)- Figure: 전체 그림 영역. 도화지.
- Axes: 실제 그래프가 그려지는 공간. 하나의 Figure에 여러 Axes를 넣을 수 있음.
python
import matplotlib.pyplot as plt
# Figure와 Axes 명시적 생성fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])ax.set_title("My First Plot")ax.set_xlabel("X axis")ax.set_ylabel("Y axis")
plt.show()plt.subplots()는 Figure와 Axes를 동시에 만들어 줍니다. 이 방식이 가장 권장됩니다.
선 그래프 (Line Plot)
시간에 따른 변화를 보여줄 때 사용합니다.
python
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]sales = [100, 120, 90, 150, 130]
fig, ax = plt.subplots(figsize=(8, 5))ax.plot(months, sales, marker="o", color="blue", linewidth=2)ax.set_title("Monthly Sales")ax.set_ylabel("Sales")ax.grid(True, alpha=0.3)
plt.show()marker="o": 각 데이터 점에 원 표시figsize=(8, 5): 가로 8인치, 세로 5인치grid(True): 격자 표시
막대 그래프 (Bar Chart)
카테고리별 비교에 사용합니다.
python
import matplotlib.pyplot as plt
languages = ["Python", "JS", "Java", "C++"]users = [30, 25, 20, 15]
fig, ax = plt.subplots()ax.bar(languages, users, color=["#3776AB", "#F7DF1E", "#B07219", "#00599C"])ax.set_title("Programming Language Popularity")ax.set_ylabel("Users (%)")
plt.show()ax.bar()에 색상 리스트를 넘기면 각 막대에 다른 색을 지정할 수 있습니다.
산점도 (Scatter Plot)
두 변수 사이의 관계를 보여줍니다.
python
import matplotlib.pyplot as pltimport numpy as np
np.random.seed(42)x = np.random.randn(50)y = 2 * x + np.random.randn(50) * 0.5
fig, ax = plt.subplots()ax.scatter(x, y, alpha=0.7, color="coral")ax.set_title("Scatter Plot Example")ax.set_xlabel("X")ax.set_ylabel("Y")
plt.show()alpha=0.7은 투명도입니다. 점이 많이 겹칠 때 유용합니다.
여러 그래프 한 번에
python
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# 첫 번째: 선 그래프axes[0].plot([1, 2, 3], [1, 4, 9])axes[0].set_title("Line")
# 두 번째: 막대 그래프axes[1].bar(["A", "B", "C"], [5, 3, 7])axes[1].set_title("Bar")
# 세 번째: 산점도axes[2].scatter([1, 2, 3, 4], [4, 1, 3, 2])axes[2].set_title("Scatter")
plt.tight_layout()plt.show()plt.subplots(1, 3)은 1행 3열의 서브플롯을 만듭니다. tight_layout()은 그래프 간 겹침을 자동으로 조정합니다.
저장하기
python
# 화면에 보여주기 대신 파일로 저장fig.savefig("chart.png", dpi=150, bbox_inches="tight")dpi=150: 해상도 (기본 100)bbox_inches="tight": 여백 자동 조절- 지원 포맷: PNG, PDF, SVG, JPG