|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +from mpl_toolkits.axes_grid1 import AxesGrid |
| 3 | + |
| 4 | +def get_demo_image(): |
| 5 | + import numpy as np |
| 6 | + from matplotlib.cbook import get_sample_data |
| 7 | + f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) |
| 8 | + z = np.load(f) |
| 9 | + # z is a numpy array of 15x15 |
| 10 | + return z, (-3,4,-4,3) |
| 11 | + |
| 12 | + |
| 13 | +def demo_bottom_cbar(fig): |
| 14 | + """ |
| 15 | + A grid of 2x2 images with a colorbar for each column. |
| 16 | + """ |
| 17 | + grid = AxesGrid(fig, 121, # similar to subplot(132) |
| 18 | + nrows_ncols = (2, 2), |
| 19 | + axes_pad = 0.10, |
| 20 | + share_all=True, |
| 21 | + label_mode = "1", |
| 22 | + cbar_location = "bottom", |
| 23 | + cbar_mode="edge", |
| 24 | + cbar_pad = 0.25, |
| 25 | + cbar_size = "15%", |
| 26 | + direction="column" |
| 27 | + ) |
| 28 | + |
| 29 | + Z, extent = get_demo_image() |
| 30 | + cmaps = [plt.get_cmap("autumn"), plt.get_cmap("summer")] |
| 31 | + for i in range(4): |
| 32 | + im = grid[i].imshow(Z, extent=extent, interpolation="nearest", |
| 33 | + cmap=cmaps[i//2]) |
| 34 | + if i % 2: |
| 35 | + cbar = grid.cbar_axes[i//2].colorbar(im) |
| 36 | + |
| 37 | + for cax in grid.cbar_axes: |
| 38 | + cax.toggle_label(True) |
| 39 | + cax.axis[cax.orientation].set_label("Bar") |
| 40 | + |
| 41 | + # This affects all axes as share_all = True. |
| 42 | + grid.axes_llc.set_xticks([-2, 0, 2]) |
| 43 | + grid.axes_llc.set_yticks([-2, 0, 2]) |
| 44 | + |
| 45 | + |
| 46 | +def demo_right_cbar(fig): |
| 47 | + """ |
| 48 | + A grid of 2x2 images. Each row has its own colorbar. |
| 49 | + """ |
| 50 | + |
| 51 | + grid = AxesGrid(F, 122, # similar to subplot(122) |
| 52 | + nrows_ncols = (2, 2), |
| 53 | + axes_pad = 0.10, |
| 54 | + label_mode = "1", |
| 55 | + share_all = True, |
| 56 | + cbar_location="right", |
| 57 | + cbar_mode="edge", |
| 58 | + cbar_size="7%", |
| 59 | + cbar_pad="2%", |
| 60 | + ) |
| 61 | + Z, extent = get_demo_image() |
| 62 | + cmaps = [plt.get_cmap("spring"), plt.get_cmap("winter")] |
| 63 | + for i in range(4): |
| 64 | + im = grid[i].imshow(Z, extent=extent, interpolation="nearest", |
| 65 | + cmap=cmaps[i//2]) |
| 66 | + if i % 2: |
| 67 | + grid.cbar_axes[i//2].colorbar(im) |
| 68 | + |
| 69 | + for cax in grid.cbar_axes: |
| 70 | + cax.toggle_label(True) |
| 71 | + cax.axis[cax.orientation].set_label('Foo') |
| 72 | + |
| 73 | + # This affects all axes because we set share_all = True. |
| 74 | + grid.axes_llc.set_xticks([-2, 0, 2]) |
| 75 | + grid.axes_llc.set_yticks([-2, 0, 2]) |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | +if 1: |
| 80 | + F = plt.figure(1, (5.5, 2.5)) |
| 81 | + |
| 82 | + F.subplots_adjust(left=0.05, right=0.93) |
| 83 | + |
| 84 | + demo_bottom_cbar(F) |
| 85 | + demo_right_cbar(F) |
| 86 | + |
| 87 | + plt.draw() |
| 88 | + plt.show() |
| 89 | + |
0 commit comments