강의를 듣다 보니 그래프/플롯과 관련해 내용이 자꾸 헷갈렸다.
또 Datapane 쓸 때 그래프를 변수에 넣는 걸 보고 그래프를 그릴 때 처음부터 변수에 잘 넣고 시작하면 편할 것 같아서 조금 찾아보았다.
In programming, you can assign a graph or plot to a variable, but it's not the graph itself that's stored, but rather a reference to it (like a figure handle). This allows you to manipulate the plot programmatically, save it, or reuse it later.
Here's how it works in Python, using matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create the plot and assign it to the variable 'fig'
fig = plt.figure() # Create a new figure
plt.plot(x, y) # Plot data on the figure
plt.title("Sine Wave") # Added a title
plt.xlabel("X-axis") # Added an x-axis label
plt.ylabel("Y-axis") # Added a y-axis label
# You can now refer to the plot using the 'fig' variable.
# For example, to save it:
# fig.savefig("sine_wave.png")
# Or to display it:
plt.show()
# You can also access the axes object
ax = fig.gca()
# and modify it further. For example:
# ax.set_xlim([0, 5])
# Alternatively, you can get the current figure using gcf
# and assign it to a variable.
fig2 = plt.gcf()
# This will point to the same figure as the one created above.
Explanation:
1. plt.figure(): This creates a new figure object and returns a reference to it. This reference is assigned to the variable fig.
2. plt.plot(x, y): This command plots the data on the currently active figure (which is the one referenced by fig).
3. fig.savefig("sine_wave.png"): This method saves the figure (the plot) to a file.
4. plt.show(): This displays the figure on your screen.
5. fig.gca(): This gets the current axes object of the figure. You can use this to modify the plot's appearance (e.g., set axis limits, labels, etc.).
6. plt.gcf(): This gets the current figure object. Useful if you want to refer to the active plot without explicitly creating a new one or if you are working with multiple plots.
plt.figure()와 plt.plot()의 차이plt.figure(): 새로운 Figure 객체(캔버스)를 생성하고 이를 변수(fig)에 할당할 수 있음plt.plot(): 현재 활성화된 Figure와 Axis에 선 그래프를 그림fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y)fig: Figure 객체의 참조값을 가짐ax: Axes 객체의 참조값을 가짐fig를 다시 불러와서 조작하거나 저장할 수 있음fig = plt.figure()
ax = fig.add_subplot(111) # 1행 1열, 첫 번째(유일한) subplot
ax.plot(x, y)
fig, ax = plt.subplots() # 1개의 Figure와 1개의 Axes 생성
ax.plot(x, y)
# 여러 개의 subplot이 필요할 때도 매우 편리
fig, axs = plt.subplots(2, 2) # 2x2 그리드의 Axes 배열 생성
axs[0, 0].plot(x, y)
| 함수 | 생성 객체 | 특징 및 용도 |
|---|---|---|
| plt.figure() | Figure | Figure만 생성, Axes는 별도로 추가해야 함 |
| plt.subplots() | Figure, Axes | Figure와 Axes를 한 번에 생성, 가장 많이 사용 |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
sns.lineplot(x=x, y=y, ax=ax) # ax에 직접 그림
ax.set_title("Sine Wave with Seaborn")
plt.show()
axes-level 함수만 가능!
seaborn 공식 문서와 커뮤니티에서도 이 방식(axes-level 함수 + ax 파라미터 사용)을 권장함
여러 subplot에 각각 seaborn 그래프를 그릴 때도 매우 유용
fig, (ax1, ax2) = plt.subplots(1, 2)
sns.histplot(data=data1, x='col', ax=ax1)
sns.boxplot(data=data2, y='col', ax=ax2)
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
# 아래 코드는 fig에 그려지지 않음!
# sns.relplot()은 fig와 무관하게 자체적으로 Figure를 만들기 때문
sns.relplot(data=..., x=..., y=...)
plt.show()
g = sns.relplot(data=..., x=..., y=...)
g.fig.suptitle("My Title") # Figure 객체에 접근 가능
g.savefig("my_plot.png") # 저장도 가능
| 함수 유형 | 기존 Figure/Axes에 그리기 | 자체 Figure 생성 | 반환값 |
|---|---|---|---|
| axes-level | O (ax=ax 파라미터) | X | AxesSubplot |
| figure-level | X | O | Grid 객체 (FacetGrid 등) |