|
53 | 53 | fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom')
|
54 | 54 | fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6)
|
55 | 55 | fig.colorbar(pcm, ax=[axs[2, 1]], location='left')
|
| 56 | +plt.show() |
| 57 | + |
| 58 | +###################################################################### |
| 59 | +# Colorbars with fixed-aspect-ratio axes |
| 60 | +# ====================================== |
| 61 | +# |
| 62 | +# Placing colorbars for axes with a fixed aspect ratio pose a particular |
| 63 | +# challenge as the parent axes changes size depending on the data view. |
| 64 | + |
| 65 | +fig, axs = plt.subplots(2, 2, constrained_layout=True) |
| 66 | +cmaps = ['RdBu_r', 'viridis'] |
| 67 | +for col in range(2): |
| 68 | + for row in range(2): |
| 69 | + ax = axs[row, col] |
| 70 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), |
| 71 | + cmap=cmaps[col]) |
| 72 | + if col == 0: |
| 73 | + ax.set_aspect(2) |
| 74 | + else: |
| 75 | + ax.set_aspect(1/2) |
| 76 | + if row == 1: |
| 77 | + fig.colorbar(pcm, ax=ax, shrink=0.6) |
| 78 | +plt.show() |
56 | 79 |
|
| 80 | +###################################################################### |
| 81 | +# One way around this issue is to use an `.Axes.inset_axes` to locate the |
| 82 | +# axes in axes co-ordinates. Note that if you zoom in on the axes, and |
| 83 | +# change the shape of the axes, the colorbar will also change position. |
57 | 84 |
|
| 85 | +fig, axs = plt.subplots(2, 2, constrained_layout=True) |
| 86 | +cmaps = ['RdBu_r', 'viridis'] |
| 87 | +for col in range(2): |
| 88 | + for row in range(2): |
| 89 | + ax = axs[row, col] |
| 90 | + pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), |
| 91 | + cmap=cmaps[col]) |
| 92 | + if col == 0: |
| 93 | + ax.set_aspect(2) |
| 94 | + else: |
| 95 | + ax.set_aspect(1/2) |
| 96 | + if row == 1: |
| 97 | + cax = ax.inset_axes([1.04, 0.2, 0.05, 0.6], transform=ax.transAxes) |
| 98 | + fig.colorbar(pcm, ax=ax, cax=cax) |
58 | 99 | plt.show()
|
0 commit comments