배움 기록/Programming

[python] plt.savefig 이미지 잘리는 경우, 해결방법 3가지

Spezi 2023. 3. 27. 17:16
반응형

matplotlib을 사용해서 plot 을 하다보면 plt.show는 전체 이미지를 잘 보여주면서, plt.savefig를 하는경우 이미지가 잘려서 저장되는 문제를 발견할 수 있다.

 

이를 해결할 수 있는 방법들을 찾아봤다

  • plt.savefig('xxx',bbox_inches='tight')  bbox_inches='tight' 를 사용
  • plt.tight_layout() 를 적용

아래 페이지를 참고했다.

 

https://stackoverflow.com/questions/37427362/plt-show-shows-full-graph-but-savefig-is-cropping-the-image

 

Plt.show shows full graph but savefig is cropping the image

My code is succesfully saving images to file, but it is cropping important details from the right hand side. Answers exist for fixing this problem when it arises for plt.show, but it is the savefig

stackoverflow.com

 

그런데 위의 두가지 방법을 다 적용했는데도 안되는 경우가 있다면,

  • 다른 파일 형식으로 저장하기

라는 방법도 시도할 수 있다. 예를들어 계속 png로 savefig를 했는데 이미지가 잘려나간 것이 확인되면, pdf 나 jpeg로 저장을 다시 해보면 온전한 이미지가 저장된것을 확인할 수 있었다.  그 이유는... 잘 모르겠는데 누가 알면 댓글로 알려주십시오.

 

fig, ax = plt.subplots()
df['feature'].plot.hist(figsize=(8, 6), ax=ax)
plt.tight_layout()
plt.savefig(plot_dir / 'hist.jpeg', bbox_inches='tight')
plt.clf()

 

 

 


배움을 기록하기 위한 공간입니다. 

수정이 필요한 내용이나 공유하고 싶은 것이 있다면 언제든 댓글로 남겨주시면 환영입니다 :D

 

반응형