Matplotlibのヒートマップ#
公開日
Matplotlibでヒートマップを出力するには、ax.pcolor
を使用します。ax.pcolor
の最初の引数に2次元配列を与えます。
import numpy as np
import matplotlib.pyplot as plt
C = np.arange(50).reshape(5, 10)
fig, ax = plt.subplots()
ax.pcolor(C)
plt.show()
![../_images/0988e6b92a63e55df5474d482e50c873c76b673cb306f0e38bbaf33523ed5310.png](../_images/0988e6b92a63e55df5474d482e50c873c76b673cb306f0e38bbaf33523ed5310.png)
ここで、C
は以下のような5行10列の2次元配列です。ヒートマップも5行10列で出力されています。
C
array([[ 0, 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, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])
カラーマップの指定#
cmap
オプションでカラーマップを指定します。
fig, ax = plt.subplots()
ax.pcolor(C, cmap="Reds")
plt.show()
![../_images/64c78fb2c2d159fc057701a6417f513ad0c790581009204a1b7d7740faa8a7ca.png](../_images/64c78fb2c2d159fc057701a6417f513ad0c790581009204a1b7d7740faa8a7ca.png)
指定可能なカラーマップについては、以下のページも参照下さい。
カラーバーを表示する場合、plt.colorbar
を使用します。ax.pcolor
の戻り値はPolyCollection
というクラスのオブジェクトです。これをplt.colorbar
の最初の引数とします。また、ax
オプションにカラーバーを表示するグラフ(ここではax
)を指定します。
fig, ax = plt.subplots()
mappable = ax.pcolor(C, cmap="Reds")
plt.colorbar(mappable, ax=ax)
plt.show()
![../_images/c04b350d84198ef66cc2f0c819f439a25c4d719fa481f43175ce377ea8bd3095.png](../_images/c04b350d84198ef66cc2f0c819f439a25c4d719fa481f43175ce377ea8bd3095.png)
表示するカラーマップの範囲を固定したい場合、最小値と最大値をそれぞれvmin
, vmax
で指定します。
カラーバーにラベルを付ける場合、plt.colorbar
の戻り値を取得(以下ではcbar
としています)し、この戻り値のset_label
メソッドを使用します。
fig, ax = plt.subplots()
mappable = ax.pcolor(C, cmap="Reds", vmin=10, vmax=40)
cbar = plt.colorbar(mappable, ax=ax)
cbar.set_label('Value')
plt.show()
![../_images/328e0bbf0d378a3737d6566838294186a73b24deacf47cdafed1727f82c01377.png](../_images/328e0bbf0d378a3737d6566838294186a73b24deacf47cdafed1727f82c01377.png)
目盛りの指定#
ヒートマップの横幅と縦軸の目盛りを指定する場合、以下のようにax.pcolor
の1, 2番目の引数に配列として与えます。また、shading="auto"
と指定します(この指定は必須ではありませんが、省略すると警告が出ます)。
X = np.arange(5,15) # 横幅の目盛り
Y = np.arange(5,10) # 縦幅の目盛り
fig, ax = plt.subplots()
ax.pcolor(X, Y, C, shading="auto")
plt.show()
![../_images/1644ec20fdd039b669b6c693e067278d6b1c93911e58e2531205f521c26de555.png](../_images/1644ec20fdd039b669b6c693e067278d6b1c93911e58e2531205f521c26de555.png)
y軸の反転#
y軸の上下を反転させる場合、ax.invert_yaxis()
メソッドを用います。
fig, ax = plt.subplots()
ax.pcolor(C)
ax.invert_yaxis()
plt.show()
![../_images/5a96c6006ae8bfba37902617392e78a8ae09334a6eb75599deb1af99467bd70b.png](../_images/5a96c6006ae8bfba37902617392e78a8ae09334a6eb75599deb1af99467bd70b.png)
同様にx軸の左右を反転させる場合、ax.invert_xaxis()
メソッドを用います。
軸ラベル、タイトルの追加#
x, y軸のラベルはそれぞれax.set_xlabel
, ax.set_ylabel
で追加できます。また、グラフの上部にタイトルを追加する場合、ax.set_title
メソッドを使います。
fig, ax = plt.subplots()
ax.pcolor(C)
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_title("Heatmap")
plt.show()
![../_images/7b775b1971d2a27153e162ca54ea2f906a3e751a7c56abd431d66f347b504518.png](../_images/7b775b1971d2a27153e162ca54ea2f906a3e751a7c56abd431d66f347b504518.png)