JavaScriptを有効にしてください

Matplotlib スタイルによるグラフの見た目の変更

 ·   3 min read

はじめに

matplotlibにはスタイルと呼ばれる、グラフの見た目を変更できるプリセットが用意されている。
スタイルを活用することで、グラフの見た目を簡単に変更できる。

環境

ソフトウェア バージョン
Anaconda3 5.2.0
Python 3.6.5
matplotlib 2.2.2

はじめに

本記事では、各ライブラリを以下のようにインポートしていることを前提とする。

1
2
import matplotlib as mpl
import matplotlib.pyplot as plt

スタイルの設定

以下のコマンドでmatplotlibで利用できるスタイルの一覧をリスト形式で取得できる。

1
plt.style.available

実行結果
matplotlibのバージョンや、他にインストールしているライブラリによって異なる場合がある。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
['bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark-palette',
 'seaborn-dark',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'seaborn',
 'Solarize_Light2',
 'tableau-colorblind10',
 '_classic_test']

この中の1つをplt.style.useで設定すると、グラフの見た目を変更できる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
plt.style.use('ggplot')

fig, ax = plt.subplots()
ax.plot([1,2], [6,3])
ax.plot([1,2], [4,5])
ax.plot([1,2], [3,4])
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_title(style+" style")
ax.legend(["1", "2", "3"], title="Legend")
plt.show()

実行結果
ggplot

なお、デフォルトのグラフは以下の通り。
default

注意したいのが、あるスタイルを設定した後に、別のスタイルを設定しても、グラフの表示に関するパラメータが全て上書きされないこと。例えば、"fast"スタイルで上書きされるパラメータは、わずか3個である。
グラフの見た目を試行錯誤して所望の表示になったとしても、Pythonを再び立ち上げると、同じ表示にならない場合がある。

スタイルの表示例

主なグラフを描画してみる(いずれもデフォルトから直接変更した場合)。

grayscale

モノクロ印刷する場合に。
grayscale

seaborn

seabornから逆輸入されたのかもしれない。
seaborn

なお、公式リファレンスに各スタイルで出力したグラフの一覧がある。
Style sheets reference — Matplotlib 3.3.3 documentation

さらにグラフの見た目を変更する

スタイルのパラメータ設定ファイルは以下のディレクトリにある。

Anaconda3\Lib\site-packages\matplotlib\mpl-data\stylelib

拡張子がmplstyleとなっているが、テキストエディタで編集可能である。
自分でスタイル設定ファイルを作成すれば、スクリプトを描くたびに細かい設定を変更する手間が省ける。

また、現在の設定は以下のコマンドで確認できる。

1
mpl.rcParams

実行結果

1
2
3
4
5
6
RcParams({'_internal.classic_mode': False,
          'agg.path.chunksize': 0,
          'animation.avconv_args': [],
          'animation.avconv_path': 'avconv',
          'animation.bitrate': -1,
(以下略)

RcParamsを変更することで、スタイル設定ファイルを書き換えずにグラフの見た目を変更できる。
また、同じスクリプト内であれば、グラフ作成の度に設定する必要はなくなる。例えば、グラフにグリッドを表示したい場合、以下のように設定する。

1
mpl.rcParams["axes.grid"] = True

参考

matplotlib.style — Matplotlib 3.3.3 documentation
matplotlibのstyleを変える - Qiita

シェアする

Helve
WRITTEN BY
Helve
関西在住、電機メーカ勤務のエンジニア。X(旧Twitter)で新着記事を配信中です

サイト内検索