LoginSignup
0
5

More than 3 years have passed since last update.

カラーバーを自作する

Last updated at Posted at 2021-04-20

はじめに

こういうカラーバーをデータ要らずで描きたい
sample_cbar.png

方法

忙しい人向けコード全部はこちら:

import matplotlib.pyplot as plt
import matplotlib.colors

cm = plt.cm.get_cmap("magma")
norm = matplotlib.colors.Normalize(vmin=0, vmax=100)
fig = plt.figure()
cax = fig.add_axes([0,0,1,0.2])
fig.colorbar(plt.cm.ScalarMappable(norm, cm), cax=cax, orientation="horizontal")
plt.show()

解説

(1) カラーマップを定義する(今回は"magma"を選択)

cm = plt.cm.get_cmap("magma")

(2) 正規化幅を決める(今回は0から100を選択)

norm = matplotlib.colors.Normalize(vmin=0, vmax=100)

(3) figurecax を定義する

fig = plt.figure()
cax = fig.add_axes([0,0,1,0.2]) # [x, y, width, height]

(4) ScalarMappableを自作して fig.colorbar に与える

fig.colorbar(plt.cm.ScalarMappable(norm, cm), cax=cax, orientation="horizontal")

通常,この第一引数には ax.imshow などで描画された Artist を mappable オブジェクトとして渡すことでカラーバーに用いられるカラーマップと値の対応が判断される。
ここでは,そのような mappable オブジェクトを自作することで,思い通りのカラーバーを得ている。

おわりに

例えばデータの値に応じて ax.plot の色を変えた場合など, mappable オブジェクトが自動生成されない際に便利だと思います。

0
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5