Help us understand the problem. What is going on with this article?

matplotlibでcolorbarを図にあわせる

More than 5 years have passed since last update.

matplotlibのaxis関数は便利で、簡単に座標を調整してくれます。
axis("tight")で余白をなるべく少なくしてくれますし、
axis("image")で同じ事をアスペクト比を保ったまましてくれます。
しかしcolorbarを付けるとややこしくなります。
以下のような単純な場合を考えます:

import numpy as np
import matplotlib.pyplot as plt

Nx = 100
Ny = 20

a = np.random.rand(Ny, Nx)

x = range(Nx)
y = range(Ny)
X, Y = np.meshgrid(x, y)

plt.pcolormesh(X, Y, a)
plt.axis("image")
plt.colorbar()

normal.png

この時colorbarがどのように出てほしいかは個人の趣味と思いますが
これは私の好みではありません。

そこで登場するのがmake_axes_locatableです。

from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()

image = ax.pcolormesh(X, Y, a)
ax.axis("image")

divider = make_axes_locatable(ax)
ax_cb = divider.new_horizontal(size="2%", pad=0.05)
fig.add_axes(ax_cb)
plt.colorbar(image, cax=ax_cb)

fit.png

複数の図を生成する場合はこちらのコンパクトな方が良いと思います。
なお複数の図を生成する場合には

fig = plt.figure()
ax = plt.subplot(311)

のように取得すれば後は同じです。

ricos
FEMによる構造解析、機械学習の専門家集団。計算資源のクラウド提供もしています。
https://www.ricos.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした