이 문서는
Python REPL(Read-Eval-Print Loop) 환경에서
matplotlib을 대화형으로 사용하는 예제임.
아래 코드는 Python 명령 프롬프트나 IPython과 같은 REPL 환경에서 단계별로 실행할 수 있음:
# 먼저 필요한 라이브러리를 import
import matplotlib.pyplot as plt
import numpy as np
# 대화형(REPL, or interactive) 모드 활성화
plt.ion()
# 데이터 생성
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 그래프 생성
fig, ax = plt.subplots()
line, = ax.plot(x, y, 'b-')
ax.set_title('Interactive Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True)
위 코드를 실행하면 그래프 창이 즉시 나타남.
이제 REPL에서 다음 명령을 하나씩 입력하여 그래프와 상호작용할 수 있음:
# 위상 변경해보기
y = np.sin(x + 1)
line.set_ydata(y)
fig.canvas.draw()
# 주파수 변경해보기
y = np.sin(2 * x)
line.set_ydata(y)
fig.canvas.draw()
# 진폭 변경해보기
y = 0.5 * np.sin(x)
line.set_ydata(y)
fig.canvas.draw()
# 직선 그려보기
y = 0.1 * x
line.set_ydata(y)
fig.canvas.draw()
# y축 범위 변경해보기
ax.set_ylim(-2, 2)
fig.canvas.draw()
# 그래프 제목 변경해보기
ax.set_title('Modified in REPL')
fig.canvas.draw()
# 그래프 색상 변경해보기
line.set_color('red')
fig.canvas.draw()
# 선 스타일 변경해보기
line.set_linestyle('--')
fig.canvas.draw()
각 명령을 실행할 때마다 그래프가 실시간으로 업데이트되므로,
사용자는 계속해서 REPL에서 명령을 입력하면서 그래프를 조작할 수 있음.
마지막으로, 대화형 세션을 종료하려면:
# 대화형 모드 비활성화
plt.ioff()
# 그래프 창 유지 (필요한 경우)
plt.show()
이런 방식으로 Python REPL 환경에서 matplotlib 그래프를 대화형으로 조작하고 실시간으로 변화를 관찰할 수 있음.
'Python > matplotlib' 카테고리의 다른 글
[matplotlib] Canvas, Render, and Event : Backend 구성 Layers (1) | 2024.06.11 |
---|---|
[matplotlib] Summary : 작성중 (2) | 2024.06.03 |
[matplotlib] Object Oriented Style Tutorial (1) | 2024.06.03 |
[matplotlib] Tutorial: Scripting Style (0) | 2024.06.03 |
[matplotlib] Scripting Layer vs. Artist Layer (0) | 2024.06.02 |