matplotlib, なかなか覚えられないよね
今週末の国際会議論文*1締切に向けて今月は完全に死んでおります。
matplotlibの使い方。pylabを使うのもあるけど。
これを見れば大体はOK.
まずはインポート
import matplotlib
matploblib.use('Agg')
import matplotlib.pyplot as plt
1、2行目はバックグラウンドユーズ、つまり
画面に出力せずに直接ファイルに書き出すための書き方。
画面に出力していいなら3行目だけでOK。
figure作成-->描画
fig = plt.figure(data)
plt.plot()
plt.show()
matlabのfigure()からの流れと大体似ていますね。
subplotも同様に出来るようです。figure(f)でfigure枠を選択、subplot(s)でsubplot枠を選択、になるようです。
14/11/25追記
ただ、いろいろ操作するときにはfigureじゃなくてaxesでやることも多いようですね・・・
このあたり、関数が被っていたり被っていなかったり面倒なのですが。
ともあれ、figure()よりは、subplot()で作っちまうのがいいようです。
fig, ax = plt.subplots()
# axesハンドラ関数を使うときはaxを使って
# figureハンドラ関数を使うときはfigを使う
21/01/26 追記
素晴らしい説明を見つけた
つまり、figureってのは絵全体のコンテナで、実際のそれぞれのグラフ描画はaxesが受け持っている。
ptl.tileとかするときは、subplot(111)を暗黙的に触っているから、絵が一枚の時はこれをつかう。
subplots()だと、figureが一つとaxesの配列が返ってくる。各グラフの処理はaxになる。
ははー
グラフ書いたり描画したり
x = range(itr)
y_gibbs = gibbs_data[0:itr, 2]
y_em = em_data[0:itr, 2]
plt.plot(x, y_gibbs, label='Gibbs', linestyle='--', linewidth=1)
plt.plot(x, y_em, label='EM', linestyle='--', linewidth=2)
plt.legend(loc=4)
ax.set_xlabel("iterations")
ax.set_ylabel("marginalized predictive log likelihood")
ax.set_title("Evolutions of inference")
Gibbsの結果とEMの結果を並べる、的な。
legend(凡例)の位置も選べます。
ファイル出力
save_name = data_name + "_Gibbs_EM_compare"
plt.savefig(save_name + '.eps')
plt.savefig(save_name + '.png')
Colormap
沢山あるけど覚えられない!これがまとめ↓
http://matplotlib.org/examples/color/colormaps_reference.html
tickとlabelの位置を真ん中にする
行列とかarrayのように、インデックスデータの可視化の時とかに必要になるやつですね。
pltじゃなくてax = sumplots()でaxis上で作業する流派の方がいろいろできるのかなぁ。
python - Moving x-axis to the top of a plot in matplotlib - Stack Overflow
import matplotlib.pyplot as plt import numpy as np column_labels = list('ABCD') row_labels = list('WXYZ') data = np.random.rand(4,4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=plt.cm.Blues)# put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False) ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)# want a more natural, table-like display ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show()
21/01/26 subplotsのとき
こんな感じでやるといいよ
fig, ax = plt.subplots(1,2) # axはaxesオブジェクトの配列ax[0].bar(range(K), cluster_sizes_i, align="center")ax[0].set_xlabel("i cluster")ax[0].set_ylabel("membership")ax[1].bar(range(K), cluster_sizes_r, align="center")ax[1].set_xlabel("r cluster")ax[1].set_ylabel("membership")plt.tight_layout() # subplots, 大体きたない配置になるので、これを呼ぶときれいにはまる
title_str = "K-means clustering on NMF factors: num_factor: " + str(num_factor) + ", K: " + str(K)fig.suptitle(title_str) # 全体タイトルplt.subplots_adjust(top=0.9) # 全体タイトルとsubplotsの間に距離をとるsavefig_name = "cluster_membership_numF" + str(num_factor) + "_K" + str(K) + ".png"plt.savefig(savefig_name)plt.show()