ronantakizawa/codereview-bench huggingface dataset:
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# Adjust image position to allow space
plt.subplots_adjust(right=0.78, top=0.92, bottom=0.08)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
bar_height = 1 / len(counts)
cax.barh(midpoints, counts, height=bar_height, color=cmap(norm(midpoints)))

# === Clean up ===
for spine in cax.spines.values():
    spine.set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6) 

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
The bars are too thin to see properly.  Suggest something like: 

```suggestion
cax.barh(midpoints, counts, height=np.median(np.diff(bins))*0.8, color=cmap(norm(midpoints)))
```

Code after:
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# Adjust image position to allow space
plt.subplots_adjust(right=0.78, top=0.92, bottom=0.08)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
bar_height = 1 / len(counts)
cax.barh(midpoints, counts, height=np.median(np.diff(bins))*0.8, color=cmap(norm(midpoints)))

# === Clean up ===
for spine in cax.spines.values():
    spine.set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6) 

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
```suggestion
cax.spines[:].set_visible(False)
```
It's nicer to showcase the none loop version 


Code after:
"""
=====================
Histogram as colorbar
=====================

This example demonstrates how to use a colored histogram instead of a colorbar
to not only show the color-to-value mapping, but also visualize the
distribution of values.
"""

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors

# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
"""
=========================
Histogram as Colorbar
=========================

This example demonstrates how to create a colorbar for an image and
add a histogram of the data values alongside it. This is useful for
visualizing the distribution of values mapped to colors.

"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.ticker import MaxNLocator

# === Surface Data ===
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-((X+1)*1.3)**2 - ((Y+1)*1.3)**2)
Z2 = 2.5*np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1**0.25 - Z2**0.5)

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu_r')
norm = mcolors.BoundaryNorm(bins, cmap.N)

Review comment (suggestion):
```suggestion
=====================
Histogram as colorbar
=====================
```


Code after:
"""
=====================
Histogram as colorbar
=====================

This example demonstrates how to use a colored histogram instead of a colorbar
to not only show the color-to-value mapping, but also visualize the
distribution of values.
"""

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors

# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

cax.barh(midpoints, counts, height=height, color=colors)

# === Clean up ===
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6)

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
`set_major_locator` annihilates the effect of `set_yticks`. You can only have one. - Though I think the defaults are fine and you don't need to customize anything.

Code after:
"""
=====================
Histogram as colorbar
=====================

This example demonstrates how to use a colored histogram instead of a colorbar
to not only show the color-to-value mapping, but also visualize the
distribution of values.
"""

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors

# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

cax.barh(midpoints, counts, height=height, color=colors)

# === Clean up ===
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6)

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (refactor):
Maybe leave out to simplify code and resulting plot. It's not uncommon that colorbars are used without an explicit label if the imaged value is clear from context.

Code after:
"""
=====================
Histogram as colorbar
=====================

This example demonstrates how to use a colored histogram instead of a colorbar
to not only show the color-to-value mapping, but also visualize the
distribution of values.
"""

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors

# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
Z = (Z1**0.25 - Z2**0.5)

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu_r')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

cax.barh(midpoints, counts, height=height, color=colors)

# === Clean up ===
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6)

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
```suggestion
# styling
```
This can summarize all the following commands

Code after:
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
# === Surface Data ===
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-((X+1)*1.3)**2 - ((Y+1)*1.3)**2)
Z2 = 2.5*np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1**0.25 - Z2**0.5)

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu_r')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

cax.barh(midpoints, counts, height=height, color=colors)

# === Clean up ===
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6)

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
```suggestion
midpoints = (bins[:-1] + bins[1:]) / 2
```
is somewhat simpler.

Code after:
# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
Z1 = np.exp(-((X+1)*1.3)**2 - ((Y+1)*1.3)**2)
Z2 = 2.5*np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1**0.25 - Z2**0.5)

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu_r')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = bins[:-1] + np.diff(bins) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

cax.barh(midpoints, counts, height=height, color=colors)

# === Clean up ===
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Axis labels ===
cax.set_xlabel('Count', labelpad=10)
cax.set_ylabel('Value', labelpad=6)

# === Ticks ===
cax.set_yticks(bins)
cax.yaxis.set_major_locator(MaxNLocator(nbins=8))

plt.show()



Review comment (suggestion):
Somewhat simpler:
```suggestion
distance = midpoints[1] - midpoints[0]

cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))
```
Since bins are equidistant, one difference is enough. Also, if expressions are simple enough, we can inline them in the function call. This creates less mental overhead as it eliminates temporary variables that are later only reassigned to an equally named parameter.

E.g. this now reads
> plot barh with a height of 0.8 times the distance

whereas before 
> set height as 0.8 times the distance and plot barh with height set to that height

Code after:
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:
# === Surface Data ===
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-((X+1)*1.3)**2 - ((Y+1)*1.3)**2)
Z2 = 2.5*np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1**0.25 - Z2**0.5)

# === Histogram from actual Z data ===
counts, bins = np.histogram(Z, bins=30)

# === Colormap & Normalization ===
cmap = plt.get_cmap('RdYlBu_r')
norm = mcolors.BoundaryNorm(bins, cmap.N)

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = midpoints = (bins[:-1] + bins[1:]) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

distance = midpoints[1] - midpoints[0]

cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Ticks ===
cax.set_yticks(bins)

plt.show()


Review comment (suggestion):
```suggestion
midpoints = (bins[:-1] + bins[1:]) / 2
```

Code after:
# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()
Repository: matplotlib/matplotlib
File: galleries/examples/color/colorbar_histogram.py (Python)

Code before:

# === Main Plot ===
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap,
               origin='lower', extent=[-3, 3, -3, 3],
               norm=norm)

# === Inset Histogram – Positioning adjusted ===
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# === Plot Histogram ===
midpoints = midpoints = (bins[:-1] + bins[1:]) / 2
height = np.median(np.diff(bins)) * 0.8
colors = cmap(norm(midpoints))

distance = midpoints[1] - midpoints[0]

cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.margins(0)
cax.tick_params(axis='both', which='both', length=0)

# === Ticks ===
cax.set_yticks(bins)

plt.show()


Review comment (suggestion):
```suggestion
cax.set_yticks(bins)
cax.tick_params(axis='both', which='both', length=0)
```
ticks is a subset of styling for these purposes

Code after:
"""
=====================
Histogram as colorbar
=====================

This example demonstrates how to use a colored histogram instead of a colorbar
to not only show the color-to-value mapping, but also visualize the
distribution of values.
"""

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors

# surface data
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)
Z2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)
Z = Z1**0.25 - Z2**0.5

# colormap & normalization
bins = 30
cmap = plt.get_cmap("RdYlBu_r")
bin_edges = np.linspace(Z.min(), Z.max(), bins + 1)
norm = mcolors.BoundaryNorm(bin_edges, cmap.N)

# main plot
fig, ax = plt.subplots(layout="constrained")
im = ax.imshow(Z, cmap=cmap, origin="lower", extent=[-3, 3, -3, 3], norm=norm)

# inset histogram
cax = ax.inset_axes([1.18, 0.02, 0.25, 0.95])  # left, bottom, width, height

# plot histogram
counts, _ = np.histogram(Z, bins=bin_edges)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
distance = midpoints[1] - midpoints[0]
cax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))

# styling
cax.spines[:].set_visible(False)
cax.set_yticks(bin_edges)
cax.tick_params(axis="both", which="both", length=0)

plt.show()