|
12 | 12 | import numpy as np
|
13 | 13 | import matplotlib.pyplot as plt
|
14 | 14 | import matplotlib.colors as mcolors
|
15 |
| -from matplotlib import gridspec |
| 15 | +from mpl_toolkits.axes_grid1 import make_axes_locatable |
16 | 16 |
|
17 | 17 | # Generate random data
|
18 |
| -x = np.random.random(100).reshape(10, 10) |
| 18 | +x = np.random.random((10, 10)) |
19 | 19 |
|
20 | 20 | # Compute histogram
|
21 | 21 | counts, bins = np.histogram(x)
|
22 | 22 |
|
23 | 23 | # Set up colormap and normalization
|
24 |
| -cmap = plt.colormaps['viridis'] |
| 24 | +cmap = plt.get_cmap('viridis') |
25 | 25 | norm = mcolors.BoundaryNorm(bins, cmap.N)
|
26 | 26 |
|
27 |
| -# Create figure with constrained_layout for better spacing |
28 |
| -fig = plt.figure(figsize=(8, 4), constrained_layout=True) |
29 |
| -gs = gridspec.GridSpec(1, 3, width_ratios=[4, 0.2, 1], figure=fig) |
30 |
| - |
31 |
| -# Main image |
32 |
| -ax_img = fig.add_subplot(gs[0]) |
33 |
| -im = ax_img.imshow(x, cmap=cmap, norm=norm) |
34 |
| -ax_img.set_title("Image") |
35 |
| - |
36 |
| -# Colorbar |
37 |
| -cax = fig.add_subplot(gs[1]) |
38 |
| -cbar = plt.colorbar(im, cax=cax) |
| 27 | +fig, ax = plt.subplots() |
| 28 | +im = ax.imshow(x, cmap=cmap, norm=norm) |
| 29 | +cbar = plt.colorbar(im, ax=ax) |
39 | 30 | cbar.set_label('Value')
|
40 | 31 |
|
41 |
| -# Histogram |
42 |
| -ax_hist = fig.add_subplot(gs[2]) |
| 32 | +# Create an axes on the right side of ax. The width of cax will be 20% of ax and the padding between cax and ax will be fixed at 0.05 inch. |
| 33 | +divider = make_axes_locatable(ax) |
| 34 | +cax = divider.append_axes("right", size="20%", pad=0.05) |
| 35 | + |
| 36 | +# Plot histogram |
43 | 37 | midpoints = bins[:-1] + np.diff(bins) / 2
|
44 |
| -ax_hist.barh(midpoints, counts, height=np.diff(bins), color=cmap(norm(midpoints)), edgecolor='k') |
45 |
| -ax_hist.set_yticks(bins) |
46 |
| -ax_hist.set_xlabel('Count') |
47 |
| -ax_hist.set_ylabel('Value') |
48 |
| -ax_hist.margins(0) |
49 |
| -for spine in ax_hist.spines.values(): |
50 |
| - spine.set_visible(False) |
| 38 | +cax.barh(midpoints, counts, height=np.diff(bins), color=cmap(norm(midpoints))) |
| 39 | +cax.set_yticks(bins) |
| 40 | +cax.set_xlabel('Count') |
| 41 | +cax.set_ylabel('Value') |
| 42 | +cax.invert_yaxis() # Optional: to match the orientation of imshow |
51 | 43 |
|
| 44 | +plt.tight_layout() |
52 | 45 | plt.show()
|
53 | 46 |
|
54 |
| -print("Colorbar with histogram example completed.") |
0 commit comments