Can I assign a graph or plot to a variable?

Suhyeon Lee·2025년 7월 3일

강의를 듣다 보니 그래프/플롯과 관련해 내용이 자꾸 헷갈렸다.
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.



  • Matplotlib에서 Figure 객체를 재사용하거나 변수에 할당하는 방법에 대해 정확히 이해하기
    1. plt.figure()plt.plot()의 차이
      • plt.figure(): 새로운 Figure 객체(캔버스)를 생성하고 이를 변수(fig)에 할당할 수 있음
      • plt.plot(): 현재 활성화된 Figure와 Axis에 선 그래프를 그림
        ※ Figure 객체를 반환하지 않음! → Line2D 객체의 리스트
    2. Figure 객체를 변수에 저장하고 재사용하기
      fig=plt.figure()
      ax=fig.add_subplot(111)
      ax.plot(x,y)
      • fig: Figure 객체의 참조값을 가짐
      • ax: Axes 객체의 참조값을 가짐
        → 같은 세션 내에서라면 다른 셀에서 fig를 다시 불러와서 조작하거나 저장할 수 있음


plt.figure() vs. plt.subplots()

  • matplotlib에서 Figure와 Axes를 생성하는 대표적인 방법

차이점

plt.figure()

  • 기능: 새로운 Figure(도화지)만 생성
    • Axes(실제 그래프가 그려지는 영역)는 자동으로 생성하지 않음
    • Axes를 추가하려면 fig.add_subplot() 또는 fig.add_axes()를 별도로 사용해야 함
fig = plt.figure()
ax = fig.add_subplot(111)  # 1행 1열, 첫 번째(유일한) subplot
ax.plot(x, y)

plt.subplots()

  • 기능: Figure와 Axes(들)를 한 번에 생성
  • 반환값: (fig, ax) 튜플 (Figure 객체와 Axes 객체)
  • subplot(서브플롯) 레이아웃을 쉽게 만들 수 있음
  • 가장 많이 쓰이는 방식
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)

어떤 경우에 어떤 것을 쓰는 게 좋은가?

  • 간단한 그래프, 혹은 여러 개의 subplot이 필요할 때는 plt.subplots()가 더 편리 & 권장
  • plt.figure()는 아주 커스텀한 Figure만 만들고, Axes를 나중에 복잡하게 추가할 때 주로 사용
  • matplotlib 공식 문서와 커뮤니티에서도 plt.subplots() 사용을 권장하는 추세

요약

함수생성 객체특징 및 용도
plt.figure()FigureFigure만 생성, Axes는 별도로 추가해야 함
plt.subplots()Figure, AxesFigure와 Axes를 한 번에 생성, 가장 많이 사용


With Seaborn

  • seaborn의 "axes-level" 함수(예: sns.lineplot, sns.histplot, sns.boxplot, sns.scatterplot 등)는 ax 파라미터를 지원합니다.
  • 이 파라미터에 원하는 matplotlib의 Axes 객체(ax)를 넘기면 해당 Axes에 그래프가 그려집니다.
    • fig, ax = plt.subplots()로 만든 ax에 seaborn의 axes-level plot 함수에서 ax=ax로 지정하면 원하는 Axes에 seaborn 그래프를 그릴 수 있습니다.
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 함수만 가능!

    • figure-level 함수(예: sns.relplot, sns.catplot, sns.pairplot, sns.displot 등)는 자체적으로 Figure와 Axes를 생성하므로, 기존의 ax에 그릴 수 없습니다.
  • 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)

figure-level 함수

  • figure-level 함수는 seaborn에서 자체적으로 Figure와 Axes를 생성하고, 전체 Figure(여러 subplot 포함)를 관리합니다.
    • 따라서 seaborn의 figure-level 함수는 plt.figure()로 만든 Figure에 직접 그릴 수 없습니다.
    • 대표적인 예시: sns.relplot, sns.catplot, sns.lmplot, sns.pairplot, sns.displot 등
  • 왜 plt.figure()와 함께 쓸 수 없나요?
    • figure-level 함수는 내부적으로 새로운 Figure를 생성
    • 반환값은 matplotlib Figure가 아니라 seaborn의 FacetGrid, PairGrid, JointGrid 등
    • 따라서, 이미 생성한 Figure(fig = plt.figure())에 직접 그릴 수 없음!
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure()
# 아래 코드는 fig에 그려지지 않음!
# sns.relplot()은 fig와 무관하게 자체적으로 Figure를 만들기 때문
sns.relplot(data=..., x=..., y=...)
plt.show()
  • figure-level 함수의 올바른 사용법
    • 별도로 Figure를 만들 필요 없이, figure-level 함수만 호출
    • 필요하다면 반환된 Grid 객체에서 Figure를 가져올 수 있음
g = sns.relplot(data=..., x=..., y=...)
g.fig.suptitle("My Title")  # Figure 객체에 접근 가능
g.savefig("my_plot.png")    # 저장도 가능

요약

함수 유형기존 Figure/Axes에 그리기자체 Figure 생성반환값
axes-levelO (ax=ax 파라미터)XAxesSubplot
figure-levelXOGrid 객체 (FacetGrid 등)

결론

  • figure-level 함수는 plt.figure()로 만든 Figure에 직접 그릴 수 없습니다.
  • 별도로 Figure를 만들 필요 없이, figure-level 함수만 호출하면 됩니다.
  • Grid 객체의 .fig 속성을 통해 Figure에 접근할 수 있습니다.

Datapane 관련 블로그 글

profile
2 B R 0 2 B

0개의 댓글