IT박스

Seaborn 플롯을 파일로 저장하는 방법

itboxs 2020. 7. 8. 08:07
반응형

Seaborn 플롯을 파일로 저장하는 방법


다음 코드 ( test_seaborn.py)를 시도했습니다 .

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig("output.png")
#sns.plt.show()

하지만이 오류가 발생합니다.

  Traceback (most recent call last):
  File "test_searborn.py", line 11, in <module>
    fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'

나는 최종 output.png이 존재할 것으로 예상 하고 다음과 같이 보입니다 :

여기에 이미지 설명을 입력하십시오

문제를 어떻게 해결할 수 있습니까?


제거 get_figure하고 그냥 사용하십시오sns_plot.savefig('output.png')

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

제안 된 솔루션은 Seaborn 0.8.1과 호환되지 않습니다

Seaborn 인터페이스가 변경되었으므로 다음 오류가 발생합니다.

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

다음 통화를 통해 수치에 액세스 할 수 있습니다 (Seaborn 0.8.1 호환).

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

이 답변 에서 이전에 것처럼 .

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.


Some of the above solutions did not work for me. The .fig attribute was not found when I tried that and I was unable to use .savefig() directly. However, what did work was:

sns_plot.figure.savefig("output.png")

I am a newer Python user, so I do not know if this is due to an update. I wanted to mention it in case anybody else runs into the same issues as I did.


You should just be able to use the savefig method of sns_plot directly.

sns_plot.savefig("output.png")

코드를 명확하게하기 위해 존재하는 matplotlib 그림에 액세스하려는 경우 다음을 사용하여 sns_plot직접 얻을 수 있습니다

fig = sns_plot.fig

이 경우 get_figure코드에서 가정 한 방법 이 없습니다 .


사용 distplot하고 get_figure사진을 성공적으로 저장합니다.

sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')

이것은 나를 위해 작동

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

sns.figure.savefig("output.png")seaborn 0.8.1에서 사용하면 오류가 발생합니다 .

대신 다음을 사용하십시오.

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

matplotlib figure객체를 만든 다음 다음을 사용할 수도 있습니다 plt.savefig(...).

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig("output.png") # Save that figure

참고로 아래 명령은 seaborn 0.8.1에서 작동 했으므로 초기 답변이 여전히 유효한 것 같습니다.

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

참고 URL : https://stackoverflow.com/questions/32244753/how-to-save-a-seaborn-plot-into-a-file

반응형