matplotlib.pyplotのsubplotsの目盛について

概要と動機

Pythonではじめる機械学習の中でたびたび出てくるmatplotlib.pyplot.subplotsの使い方の中でも、なるほどと思ったので書き留めておくことにする。


サブプロットの使い方

まずsubplotsの使い方はよく知られているように、

import matplotlib.pyplot as plt
from sklearn.datasets import fetch_lfw_people


people = fetch_lfw_people(min_faces_per_person=20, resize=.7)
image_shape = people.images[0].shape

fix, axes = plt.subplots(3, 4, figsize=(9,9),subplot_kw=({"xticks":(), "yticks":()}))
for target, image, axis in zip(people.target, people.images, axes.ravel()):
    axis.imshow(image)
    axis.set_title(people.target_names[target])
plt.show()

のように使用します。

ここでデータセットはLabeled Faced in the Wildの顔画像を使用しており、下記のようにモジュールを定義して読み込みます。

from sklearn.datasets import fetch_lfw_people
people = fetch_lfw_people(min_faces_per_person=20, resize=.7)

本題の目盛

fix, axes = plt.subplots(3, 4, figsize=(9,9),subplot_kw=({"xticks":(), "yticks":()}))

subplotsの関数の中に、見慣れないsubplot_kw=({"xticks":(), "yticks":()})という引数が紛れています。
初めの引数3は3行、次の引数4は4列のサブプロット作成し、
次のfigsizeは(9,9)サイズのfigsizieでsubplotsを描画し、
subplot_kw??これはなんだ??
となりました。
そこで、このsubplot_kwのありなしを比較してみましょう。
まず、subplot_kw=({"xticks":(), "yticks":()})ありの場合、
f:id:chihayaChitose:20180930223150p:plain

では、subplot_kw=({"xticks":(), "yticks":()})なしの場合、
f:id:chihayaChitose:20180930223209p:plain

ぱっと見違いがわかりませんが、上記画像ではサブプロットの画像に目盛がありませんが、下記画像では目盛がありますね。
subplot_kwはこのように目盛を制御することが出来ます。


蛇足

import matplotlib.pyplot as plt
from sklearn.datasets import fetch_lfw_people


people = fetch_lfw_people(min_faces_per_person=20, resize=.7)
image_shape = people.images[0].shape

fix, axes = plt.subplots(3, 4, figsize=(9,9))
for target, image, axis in zip(people.target, people.images, axes.ravel()):
    axis.imshow(image)
    axis.set_title(people.target_names[target])
plt.xticks()
plt.yticks()
plt.show()

蛇足ですが、
上記のようにsubplot_kw=({'xticks':(), "yticks":()})ではなく、

plt.xticks()
plt.yticks()

を用いると、
f:id:chihayaChitose:20180930224311p:plain
このようになり、subplotsのそれぞれの画像の目盛には影響を与えません。
当然ですよね、plt.xticks()やplt.yticks()はsubplotsの制御ではなく、pltの制御なのですから。