Skip to content

Commit 3574a7e

Browse files
authored
Add example to histogram colorbar on galleries (matplotlib#30107)
1 parent 7c49d52 commit 3574a7e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
=====================
3+
Histogram as colorbar
4+
=====================
5+
6+
This example demonstrates how to use a colored histogram instead of a colorbar
7+
to not only show the color-to-value mapping, but also visualize the
8+
distribution of values.
9+
"""
10+
11+
import matplotlib.pyplot as plt
12+
import numpy as np
13+
14+
import matplotlib.colors as mcolors
15+
16+
# surface data
17+
delta = 0.025
18+
x = y = np.arange(-2.0, 2.0, delta)
19+
X, Y = np.meshgrid(x, y)
20+
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
21+
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
22+
Z = Z1**0.25 - Z2**0.5
23+
24+
# colormap & normalization
25+
bins = 30
26+
cmap = plt.get_cmap("RdYlBu_r")
27+
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
28+
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)
29+
30+
# main plot
31+
fig, ax = plt.subplots(layout="constrained")
32+
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)
33+
34+
# inset histogram
35+
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95]) # left, bottom, width, height
36+
37+
# plot histogram
38+
counts, _ = np.histogram(Z, bins=bin_edges)
39+
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
40+
distance = midpoints[1] - midpoints[0]
41+
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))
42+
43+
# styling
44+
cax.spines[:].set_visible(False)
45+
cax.set_yticks(bin_edges)
46+
cax.tick_params(axis="both", which="both", length=0)
47+
48+
plt.show()

0 commit comments

Comments
 (0)