LoginSignup
18
28

More than 3 years have passed since last update.

(Matplotlibに不慣れな人向け) Seabornでグラフを描くときのtips

Last updated at Posted at 2017-08-22

この記事では、ごくごく細かいtipsを紹介します。といいつつ大半はmatplotlibの使い方になってしまった面もありますが、matplotlibに触ったことがない人がSeabornをいきなり使おうとしたときにつまるポイント(よそではmatplotlibの知識が前提となって解説されているところ)を補足する役割では役立つと思い書いてみます。

描画したグラフを表示する

matplotlib側の機能で、描画したあとにplt.show()を呼ぶと表示されます。

showyourplot.py
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns  # cf. https://www.reddit.com/r/learnpython/comments/5oscmr/why_is_seaborn_commonly_imported_as_sns/

Z = np.random.random(1000)

sns.distplot(Z, kde=False)  # kdf stands for Kernel Density Estimation, which is disabled here.
plt.show()

image.png
このようにウインドウが出てきてグラフが見えます。ここから手動で保存することもできます。

描画したグラフを自動で保存する

こちらもmatplotlibの機能で保存します。上のコードの最後に足してください。

plt.savefig("seaborntest.png")  # save as png file

seaborntest.png
このようなファイルがseaborntest.pngというファイル名で保存されました。

plt.savefig("seaborntest.pdf")  # output format detected automatically

と拡張子を変えてやるだけでpdfで保存できます。ベクトルデータが残っているので、あとから必要に応じてAdobe Illustratorなどで修正することもできます。

グラフがいくつも重なって描画されてしまうことを防ぐ

上の例でも二つ重なってしまっていますが、特にたくさんのグラフを描いて保存するときにはそのつど前に描画した内容を消してやる必要があります。そのためにはplt.clf()を呼びます。

savemanyplots.py
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

for i in range(10):
    plt.clf()  # flush previous drawings
    sns.set_context('poster')  # use large fonts
    Z = np.random.random(1000)
    sns.distplot(Z, kde=False)
    plt.savefig("seaborntest{0}.png".format(i),dpi=300)  # output high-resolution png

image.png
それぞれ内容の違う出力が10件生成できました。また、ここではset_context('poster')で文字サイズを大きくし、savefigのオプションで'dpi=300'として高精細なグラフを生成しています。

フォントをいじる

用途にもよりますが、斜体や上付き文字、下付き文字を使いたい場面もあることでしょう。以下にirisのデータをいじったサンプルを示します。このようにTeX記法で書けばそのとおりに反映されます。ついでにx軸ラベルを消し、y軸ラベルは変更しています。また、カラーパレットも変更しています。

tweakfonts.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

iris = sns.load_dataset('iris')
iris = iris.replace('setosa', '$sp. \mathrm{str.}$')  # italic and roman
iris = iris.replace('versicolor', '$\mathbf{amp^R}$')  # bold with superstring
iris = iris.replace('virginica', '$mutant_1$')  # italic with substring

sns.set_context('poster')
fig = sns.barplot(x='species',y='sepal_length',data=iris,palette='gray')
fig.set_xlabel('')  # no label on the categorical axis
fig.set_ylabel("Survival Rate")  # refine the y-axis label
plt.savefig('survival.png')

survival.png

リンク

一般的なSeabornの使い方についてはすでに解説されている方がいるのでこれらを参照してください。
http://qiita.com/hik0107/items/3dc541158fceb3156ee0
http://qiita.com/koji_france/items/47fbb89b0922251a20bb
http://qiita.com/koji_france/items/87c5d4d08fdc3ad0e9b4
https://nkmk.github.io/blog/python-seaborn-matplotlib/

18
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
28