|
| 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 nn in range(2): |
| 17 | + for mm in range(2): |
| 18 | + ax = axs[mm, nn] |
| 19 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (nn + 1), cmap=cm[nn]) |
| 20 | + fig.colorbar(pcm, ax=ax) |
| 21 | +plt.show() |
| 22 | + |
| 23 | +###################################################################### |
| 24 | +# The first column has the same type of data in both rows, so it may |
| 25 | +# be desirable to combine the colorbar which we do by calling |
| 26 | +# `.Figure.colorbar` with a list of axes instead of a single axes. |
| 27 | + |
| 28 | +fig, axs = plt.subplots(2, 2) |
| 29 | +cm = ['RdBu_r', 'viridis'] |
| 30 | +for nn in range(2): |
| 31 | + for mm in range(2): |
| 32 | + ax = axs[mm, nn] |
| 33 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (nn + 1), cmap=cm[nn]) |
| 34 | + fig.colorbar(pcm, ax=axs[:, nn], shrink=0.6) |
| 35 | +plt.show() |
| 36 | + |
| 37 | +###################################################################### |
| 38 | +# Relatively complicated colorbar layouts are possible using this |
| 39 | +# paradigm. Note that this example works far better with |
| 40 | +# ``constrained_layout=True`` |
| 41 | + |
| 42 | +fig, axs = plt.subplots(3, 3, constrained_layout=True) |
| 43 | +for ax in axs.flatten(): |
| 44 | + pcm = ax.pcolormesh(np.random.random((20, 20))) |
| 45 | + |
| 46 | +fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom') |
| 47 | +fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom') |
| 48 | +fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) |
| 49 | +fig.colorbar(pcm, ax=[axs[2, 1]], location='left') |
| 50 | + |
| 51 | + |
| 52 | +plt.show() |
0 commit comments