Jak zapisać wykres Seaborn do pliku

Wypróbowałem następujący kod (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()

Ale dostaję ten błąd:

  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'

Oczekuję, że finał output.png będzie istniał i będzie wyglądał tak:

Tutaj wpisz opis obrazka

Jak mogę rozwiązać problem?

Author: neversaint, 2015-08-27

10 answers

Usuń get_figure i po prostu użyj sns_plot.savefig('output.png')

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
sns_plot.savefig("output.png")
 144
Author: Overclover,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-15 16:01:00

Sugerowane rozwiązania są niezgodne z Seaborn 0.8.1

Podając następujące błędy, ponieważ interfejs Seaborn się zmienił:

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

Następujące wywołania umożliwiają dostęp do rysunku (kompatybilne z Seaborn 0.8.1):

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

Jak widać wcześniej w tej odpowiedzi.

Aktualizacja: Ostatnio użyłem obiektu PairGrid z seaborn do wygenerowania wykresu podobnego do tego w w tym przykładzie. W tym przypadku, ponieważ GridPlot nie jest obiekt wykresu, jak np. sns.swarmplot, nie posiada funkcji get_figure (). Jest to możliwe, aby uzyskać bezpośredni dostęp do rysunku matplotlib przez

fig = myGridPlotObject.fig

Jak poprzednio sugerowano w innych postach w tym wątku.

 275
Author: Salvatore Cosentino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-15 07:02:13

Niektóre z powyższych rozwiązań nie działały dla mnie. Atrybut .fig nie został znaleziony, gdy próbowałem tego i nie mogłem użyć .savefig() bezpośrednio. Jednak to, co zadziałało, to:

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

Jestem nowszym użytkownikiem Pythona, więc nie wiem, czy jest to spowodowane aktualizacją. Chciałem o tym wspomnieć na wypadek, gdyby ktoś inny napotkał te same problemy, co ja.

 46
Author: BazookaDave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-03 21:09:58

Powinieneś być w stanie bezpośrednio użyć savefig metody sns_plot.

sns_plot.savefig("output.png")

Dla jasności z kodem jeśli chcesz uzyskać dostęp do rysunku matplotlib, na którym znajduje się sns_plot, możesz uzyskać go bezpośrednio za pomocą

fig = sns_plot.fig

W tym przypadku nie ma metody get_figure jak zakłada Twój kod.

 14
Author: Simon Gibbons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-27 09:18:10

Mniej linii dla poszukiwaczy 2019:

import matplotlib.pyplot as plt
import seaborn as sns

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

Uwaga aktualizacja: size została zmieniona na height.

 13
Author: Jade Cacho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-19 04:32:12

Używam distplot i get_figure aby zapisać zdjęcie pomyślnie.

sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')
 9
Author: Terry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-12 03:55:49

To działa dla mnie

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')
 3
Author: Niraj D Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-29 09:24:05

Możliwe jest również utworzenie obiektu matplotlib figure, a następnie użycie 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
 3
Author: tttthomasssss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-02 22:27:11

W seaborn 0.8.1 pojawi się błąd podczas używania sns.figure.savefig("output.png").

Zamiast:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")
 1
Author: shekhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-03 23:34:34

Dla twojej informacji, poniższe polecenie działało w seaborn 0.8.1 więc domyślam się, że początkowa odpowiedź jest nadal ważna.

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")
 -4
Author: Sudhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 20:25:58