본문 바로가기
Python Library/Matplotlib

[Matplotlib] 초기화 메서드

by goatlab 2023. 9. 4.
728x90
반응형
SMALL

cla()

 

cla() 명령은 Matplotlib에서 현재 축을 지우는 데 사용된다. ‘축’은 단순히 그림의 일부이며 일반적으로 서브 플롯과 세부 정보이다.

 

import math
import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,2*math.pi,100)
y1=np.sin(x)
y2=np.cos(x)

fig,ax=plt.subplots(2,1)
ax[0].plot(x,y1)
ax[0].set_xlabel("x")
ax[0].set_ylabel("sinx")
ax[0].set_title("Plot of sinx")

ax[1].plot(x,y2)
ax[1].set_xlabel("x")
ax[1].set_ylabel("cosx")
ax[1].set_title("Plot of cosx")
ax[1].cla()

fig.suptitle('Plot of sinx and cosx',fontsize=16) 
fig.tight_layout(pad=3.0)

plt.show()

 

cla() 메서드가 ax[1] 축, 즉 서브 플롯의 두 번째 행을 지우는 것을 볼 수 있다. 축을 지우는 것은 xlabel, ylabel 및 title과 같은 세부 사항이 있는 서브 플롯을 제거하는 것을 의미한다. 그러나 ax[0] 축 또는 맨 위 행의 서브 플롯은 cla()가 ax[1] 축에 의해서만 호출 되었기 때문에 메서드에 의해 변경되지 않는다.

 

clf()

 

clf()는 Matplotlib의 전체 그림을 지운다. 그림은 하위 그림, 하위 축, 제목 및 범례와 같은 그림의 모든 세부 사항으로 구성된 그림의 큰 그림으로 간주할 수 있다.

 

import math
import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,2*math.pi,100)
y1=np.sin(x)
y2=np.cos(x)

fig,ax=plt.subplots(2,1)
ax[0].plot(x,y1)
ax[0].set_xlabel("x")
ax[0].set_ylabel("sinx")
ax[0].set_title("Plot of sinx")


ax[1].plot(x,y2)
ax[1].set_xlabel("x")
ax[1].set_ylabel("cosx")
ax[1].set_title("Plot of cosx")

fig.suptitle('Plot of sinx and cosx',fontsize=16) 
fig.tight_layout(pad=3.0)

plt.clf()
plt.show()

 

clf() 메서드가 플롯의 모든 것을 지우는 것을 볼 수 있다. 이 프로세스에는 모든 축이 포함된다. 그러나 플롯 창은 여전히 ​​존재하며 다른 수치를 생성하는 데 재사용할 수 있다. 그리고 각 축에 clf() 메서드를 사용할 수 없다.

 

close()

 

close()는 Matplotlib에서 Figure 창을 닫고 plt.show() 메서드를 호출할 때 아무것도 나타나지 않는다.

 

import math
import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,2*math.pi,100)
y1=np.sin(x)
y2=np.cos(x)

fig,ax=plt.subplots(2,1)
ax[0].plot(x,y1)
ax[0].set_xlabel("x")
ax[0].set_ylabel("sinx")
ax[0].set_title("Plot of sinx")


ax[1].plot(x,y2)
ax[1].set_xlabel("x")
ax[1].set_ylabel("cosx")
ax[1].set_title("Plot of cosx")

fig.suptitle('Plot of sinx and cosx',fontsize=16) 
fig.tight_layout(pad=3.0)

plt.close()
plt.show()

 

close() 메서드가 Figure를 지우고 창을 닫으므로 스크립트는 출력을 생성하지 않는다. plt.show() 프로세스를 사용하면 아무 것도 볼 수 없다.

 

MemoryError: In RendererAgg: Out of memory

 

matplotlib의 그래프를 저장할 때 이미지를 그리는 데 필요한 메모리를 할당하기 때문에 반복문을 사용할 시 "MemoryError: In RendererAgg: Out of memory" 에러 메시지를 띄운다.

 

plt.close('all')
plt.clf()

 

반복문에 위 코드를 추가하면 메모리 누수를 해결할 수 있다.

728x90
반응형
LIST