fontsize=Xか{“fontsize”:X}か?
前々回から、matplotlibでフォントサイズを指定するのは「fontsize=X」か「{“fontsize”:X}」か、色々なコマンドに対して試しています。
そして前回は軸名を表示するxlabel、ylabel、set_xlabel、set_ylabelに対して試してみました。

今回は凡例を表示するlegend、そして軸の数値のフォントを変更するtick_paramsを試してみましょう。
どちらのコマンドも普通のグラフの場合でも、またsubplotsを使い、複数のグラフを表示した場合でも使えます。
ということで基本のプログラムはなるべく簡単にこんな感じにしてみました。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend()
plt.tick_params()
plt.show()
実行結果

と言うことで試していきましょう。
legendのフォントサイズ
まずはlegendから試していきます。
legendに関しては前は「prop={“size”: X}」と記述していました。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend(prop={"size": 20})
plt.tick_params()
plt.show()
実行結果

凡例のフォントサイズが大きくなりました。
次に「prop={“size”: X}」と似ているという理由から、「{“fontsize”:X}」を試してみましょう。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend({"fontsize": 20})
plt.tick_params()
plt.show()
実行結果

エラーにはならなかったものの、「graph」と表示していた凡例が「fontsize」に変わってしまいました。
またフォントサイズも変化していません。
意図した形ではないので、残念ながらこれはダメということで。
次は「fontsize=X」を試してみます。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend(fontsize=20)
plt.tick_params()
plt.show()
実行結果

凡例の「graph」のフォントサイズが大きくなりました。
ということでlegendには「fontsize=X」、もしくは「prop={“size”: X}」でフォントサイズを変更でき、「{“fontsize”:X}」ではできないと言う結果になりました。
tick_paramsのフォントサイズ
最後に軸の数値のフォントを変えるtick_paramsに対して「{“fontsize”:X}」、「fontsize=X」を試してみましょう。
まずは「{“fontsize”:X}」から。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend()
plt.tick_params({"fontsize":20})
plt.show()
実行結果
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-44-e0b533869bab> in <module>
7
8 plt.legend()
----> 9 plt.tick_params({"fontsize":20})
10
11 plt.show()
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in tick_params(axis, **kwargs)
2967 @docstring.copy(Axes.tick_params)
2968 def tick_params(axis='both', **kwargs):
-> 2969 return gca().tick_params(axis=axis, **kwargs)
2970
2971
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in tick_params(self, axis, **kwargs)
3000
3001 """
-> 3002 cbook._check_in_list(['x', 'y', 'both'], axis=axis)
3003 if axis in ['x', 'both']:
3004 xkw = dict(kwargs)
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/__init__.py in _check_in_list(values, **kwargs)
2162 raise ValueError(
2163 "{!r} is not a valid value for {}; supported values are {}"
-> 2164 .format(v, k, ', '.join(map(repr, values))))
ValueError: {'fontsize': 20} is not a valid value for axis; supported values are 'x', 'y', 'both'
エラーがでました。
「{‘fontsize’: 20} is not a valid value for axis」とあるように有効な値ではありませんとのことらしいです。
では「fontsize=X」を試しみます。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend()
plt.tick_params(fontsize=20)
plt.show()
実行結果
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-49-84655b4cbc2a> in <module>
7
8 plt.legend()
----> 9 plt.tick_params(fontsize=20)
10
11 plt.show()
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in tick_params(axis, **kwargs)
2967 @docstring.copy(Axes.tick_params)
2968 def tick_params(axis='both', **kwargs):
-> 2969 return gca().tick_params(axis=axis, **kwargs)
2970
2971
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in tick_params(self, axis, **kwargs)
3007 xkw.pop('labelleft', None)
3008 xkw.pop('labelright', None)
-> 3009 self.xaxis.set_tick_params(**xkw)
3010 if axis in ['y', 'both']:
3011 ykw = dict(kwargs)
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in set_tick_params(self, which, reset, **kw)
872 if which == 'minor' or which == 'both':
873 dicts.append(self._minor_tick_kw)
--> 874 kwtrans = self._translate_tick_kw(kw)
875
876 # this stashes the parameter changes so any new ticks will
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in _translate_tick_kw(kw)
939 raise ValueError(
940 "keyword %s is not recognized; valid keywords are %s"
--> 941 % (key, kwkeys))
942 kwtrans.update(kw)
943 return kwtrans
ValueError: keyword fontsize is not recognized; valid keywords are ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', 'grid_agg_filter', 'grid_alpha', 'grid_animated', 'grid_antialiased', 'grid_clip_box', 'grid_clip_on', 'grid_clip_path', 'grid_color', 'grid_contains', 'grid_dash_capstyle', 'grid_dash_joinstyle', 'grid_dashes', 'grid_drawstyle', 'grid_figure', 'grid_fillstyle', 'grid_gid', 'grid_in_layout', 'grid_label', 'grid_linestyle', 'grid_linewidth', 'grid_marker', 'grid_markeredgecolor', 'grid_markeredgewidth', 'grid_markerfacecolor', 'grid_markerfacecoloralt', 'grid_markersize', 'grid_markevery', 'grid_path_effects', 'grid_picker', 'grid_pickradius', 'grid_rasterized', 'grid_sketch_params', 'grid_snap', 'grid_solid_capstyle', 'grid_solid_joinstyle', 'grid_transform', 'grid_url', 'grid_visible', 'grid_xdata', 'grid_ydata', 'grid_zorder', 'grid_aa', 'grid_c', 'grid_ds', 'grid_ls', 'grid_lw', 'grid_mec', 'grid_mew', 'grid_mfc', 'grid_mfcalt', 'grid_ms']
こちらもエラーになってしまいました。
エラーとしては「keyword fontsize is not recognized; valid keywords are […]」ということで「fontsize」というキーワードはない。
そしてカギカッコ内にある[‘size’, ‘width’…]などがキーワードだと言っています。
そう、実はtick_paramsに対しては「fontsize」ではなく、「labelsize」なんです。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value, label="graph")
plt.legend()
plt.tick_params(labelsize=20)
plt.show()
実行結果

「labelsize」で、ちゃんとフォントサイズを変更することができました。
まとめ
ということでこれまでの結果をまとめてみましょう。
fontsize=X | {“fontsize”:X} | その他 | |
title | ○ | ○ | |
suptitle | ○ | × | |
xlabel ylabel | ○ | ○ | |
set_xlabel set_ylabel | ○ | ○ | |
legend | ○ | × | prop={“size”: X} |
tick_params | × | × | labelsize=X |
tick_paramで「fontsize」が使えないのは、知識不足だったとして、他のもので言うと全てのコマンドで「fontsize=X」が使えました。
反面、{“fontsize”: X}はsuptitleやlegendでは使えないと言う結果になりました。
と言うことはとりあえずフォントサイズを変えたい場合は「fontsize=X」という記述の仕方をしてみて、ダメなら調べると言うのが良さそうです。
ということで3回にわたって試してきた「{“fontsize” : X}」「fontsize=X」検討ですが、「fontsize=X」上がったところで締め括りたいと思います。
ではでは今回はこんな感じで。
コメント