Matplotlib - arosh/arosh.github.com GitHub Wiki
figsize
plt.figure(figsize=(width_inch, height_inch))
によってインチ単位で設定ができる.この設定によって文字サイズや余白の大きさのバランスが決まるので,作図するときにはこの設定を最初にやることを勧める.解像度はplt.savefig
のdpi
オプションで決める.
A4用紙に2段組の資料の場合はfigsize=(4, 3)
,A4用紙に1段組の資料の場合はfigsize=(8, 6)
がちょうど良いと思う.
seabornを使う場合は seaborn.set_context
も検討したほうが良い
参考: https://nkmk.github.io/blog/python-seaborn-matplotlib/
plt.gca()
plt.hoge
が使えなくて ax.hoge
が必要となる場合がしばしばある.あまりお行儀が良いとは思えないのだが,plt.gca()
で現在のaxisが取れる.
箱ひげ図
MatplotlibやRが出力するデフォルトの箱ひげ図は,箱の1.5倍の長さ以上のものは外れ値とみなすので,日本の教科書で習うものと少しルールが異なる.以下のページに一度目を通すことを勧める.
- http://stackoverflow.com/questions/17725927/boxplots-in-matplotlib-markers-and-outliers
- http://mathtrain.jp/hakohige
日本の教科書で習うものに準拠する場合はplt.boxplot(data, showmeans=True, whis='range')
などの設定が必要.
v1.4から whis=[2.5, 97.5]
のような指定もできるようになった。
参考: http://stackoverflow.com/a/21998600
plt.figure(figsize=(4, 3))
ax = plt.gca()
box_values = [df.loc[:, name] for name in names]
ax.boxplot(box_values)
ax.set_xticklabels(names)
ax.set_ylim(0.0, 1.0)
ax.set_ylabel('Awesome-measure')
plt.tight_layout()
plt.show()
# plt.savefig('foo.pdf')
箱ひげ図のラベルを斜めに
ax.set_xticklabels
のrotation
オプションで回転させたくなるが,それは罠である.ラベルを斜めにするときは,ラベルのテキストの末端を軸に合わせるのがルールだが,rotation
オプションはテキストの中心が軸に合うように設定されるので,適切ではない.fig.autofmt_xdate()
を使えば良い.
正解
fig = plt.gcf()
ax = plt.gca()
ax.set_xticklabels(names)
fig.autofmt_xdate()
plt.tight_layout()
plt.savefig('foo.pdf')
まちがい
labels = ax.set_xticklabels(names, rotation=45)
plt.tight_layout()
plt.savefig('foo.pdf', bbox_extra_artists=labels, bbox_inches='tight')
カテゴリ毎に色分け
散布図の各データにカテゴリが設定されている場合には,色で識別できるようにしておいたほうが便利である.
plt.figure(figsize=(4, 3))
names = ['type-A', 'type-B']
categories = ['cat-A', 'cat-B', 'cat-C', 'cat-D']
# 色の設定(GoogleのMaterial Color Paletteをパクったような気がするが,どうだったか忘れた)
colors = [(x[0]/255, x[1]/255, x[2]/255, 1.0) for x in [(244,67,54), (76,175,80), (103,58,183), (255,193,7)]]
for cat, color in zip(categories, colors):
xs = df.loc[df.loc[:, 'category'] == cat, names[0]]
ys = df.loc[df.loc[:, 'category'] == cat, names[1]]
plt.scatter(xs, ys, s=30, facecolor='none', edgecolor=color)
# scatterの標準の凡例はあまりかっこよくない.カラーバーにしておいたほうが良さそうである.
patches = [Patch(color=color, label=cat) for cat, color in zip(categories, colors)]
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim(0.4, 1)
plt.ylim(0.4, 1)
plt.xlabel(names[0])
plt.ylabel(names[1])
plt.tight_layout()
# legendを枠の外に出す方法
# http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot
# ncolは1行あたりのアイテム数なので,カテゴリ数によって適切に設定する.
# bbox_to_anchorはlegendの表示位置なので適切に設定する.
lgd = plt.legend(handles=patches, ncol=2, loc='upper center', bbox_to_anchor=(0.5, -0.2))
plt.show()
# plt.savefig('foo.pdf', bbox_extra_artists=(lgd, ), bbox_inches='tight')
離散値のヒストグラム
それはヒストグラムではなくて棒グラフである。棒グラフではなくて箱ひげ図のほうが適切ではないか再考したほうが良い。
Matplotlibのplt.bar
はイマイチなのでpandasを使ったほうが簡単。
https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py
def DiscreteHist(count, xmin=None, xmax=None, figsize=(4, 3)):
import numpy as np
import pandas as pd
if xmax is None:
xmax = np.max(count)
xs = np.arange(0, xmax+1)
ys = np.bincount(count, minlength=xmax+1)
ys = ys[:xmax+1]
if xmin is not None:
xs = xs[xmin:]
ys = ys[xmin:]
pd.DataFrame({'x': xs, 'y': ys}).plot(x='x', y='y', kind='bar', facecolor='none', figsize=figsize, legend=False)
traceplot
アヒル本 p.13 の図のようなtraceplotを表示する。
参考: http://statmodeling.hatenablog.com/entry/pystan-rstanbook-chap5-1
from matplotlib import gridspec
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax1 = plt.subplot(gs[0])
trace = ms[:,:,fit.sim['fnames_oi'].index('a')]
for i in range(trace.shape[1]):
ax1.plot(trace[:,i], alpha=0.5, label='chain%d' % (i + 1))
ax1.legend(loc='lower right')
ax1.set_xlabel('iteration')
ax1.set_ylabel('value')
ax2 = plt.subplot(gs[1], sharey=ax1)
for i in range(trace.shape[1]):
seaborn.kdeplot(trace[:,i], vertical=True, alpha=0.5, ax=ax2)
plt.tight_layout()