|
| 1 | +""" |
| 2 | +================= |
| 3 | +Placing Colorbars |
| 4 | +================= |
| 5 | +
|
| 6 | +Colorbars indicate the quantitative extent of image data. Placing in |
| 7 | +a figure is non-trivial because room needs to be made for them. |
| 8 | +
|
| 9 | +The simplest case is just attaching a colorbar to each axes: |
| 10 | +""" |
| 11 | +import matplotlib.pyplot as plt |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +fig, axs = plt.subplots(2, 2) |
| 15 | +cm = ['RdBu_r', 'viridis'] |
| 16 | +for col in range(2): |
| 17 | + for row in range(2): |
| 18 | + ax = axs[row, col] |
| 19 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (nn + 1), |
| 20 | + cmap=cm[col]) |
| 21 | + fig.colorbar(pcm, ax=ax) |
| 22 | +plt.show() |
| 23 | + |
| 24 | +###################################################################### |
| 25 | +# The first column has the same type of data in both rows, so it may |
| 26 | +# be desirable to combine the colorbar which we do by calling |
| 27 | +# `.Figure.colorbar` with a list of axes instead of a single axes. |
| 28 | + |
| 29 | +fig, axs = plt.subplots(2, 2) |
| 30 | +cm = ['RdBu_r', 'viridis'] |
| 31 | +for col in range(2): |
| 32 | + for row in range(2): |
| 33 | + ax = axs[row, col] |
| 34 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (nn + 1), |
| 35 | + cmap=cm[col]) |
| 36 | + fig.colorbar(pcm, ax=axs[:, col], shrink=0.6) |
| 37 | +plt.show() |
| 38 | + |
| 39 | +###################################################################### |
| 40 | +# Relatively complicated colorbar layouts are possible using this |
| 41 | +# paradigm. Note that this example works far better with |
| 42 | +# ``constrained_layout=True`` |
| 43 | + |
| 44 | +fig, axs = plt.subplots(3, 3, constrained_layout=True) |
| 45 | +for ax in axs.flat: |
| 46 | + pcm = ax.pcolormesh(np.random.random((20, 20))) |
| 47 | + |
| 48 | +fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom') |
| 49 | +fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom') |
| 50 | +fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) |
| 51 | +fig.colorbar(pcm, ax=[axs[2, 1]], location='left') |
| 52 | + |
| 53 | + |
| 54 | +plt.show() |
0 commit comments