ipython Notebookで、最初にpandas Seriesオブジェクトを作成し、次にインスタンスメソッド.hist()を呼び出すことにより、ブラウザーに図が表示されます。
この図をファイルに保存する方法を知りたいです(右クリックして名前を付けて保存するのではなく、スクリプトで必要なコマンドを意味します)。
回答:
次のFigure.savefig()ような方法を使用します。
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
で終わる必要はありませんpdf、多くのオプションがあります。ドキュメントをチェックしてください。
または、pyplotインターフェイスを使用savefigし、関数としてを呼び出すだけで、最後に作成した図を保存できます。
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
import matplotlib.pyplot as pltおよびplt.close()。
fig.clf()、図をクリアするために実行できます。
あなたが使用することができますax.figure.savefig():
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
これはax.get_figure().savefig()、Philip Cloudの回答で示唆されているように、実用的なメリットはないため、最も美的に満足できるオプションを選択できます。実際、get_figure()単に次を返しますself.figure:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'した場合は、複数の列をプロットしている可能性がありますs.hist(columns=['colA', 'colB'])。この場合、axはすべての軸の配列になります。ax[0].get_figure()またはax[0][0].get_figure()