Add a border around histogram bars in Matplotlib

Python

Matplotlib

Histogram

Add bar border

Luc B.

Python

Matplotlib

Histogram

By default, Matplotlib's histograms lack division or space between adjacent bars. This can make the bars blend together so they're difficult to interpret. There are a couple ways to address this including changing the bar width or adding a border around the bars.

Code Example

Pass a color value as the edgecolor parameter to plt.hist() to change the bar border color.

import matplotlib.pyplot as plt

values = [1, 1, 2, 3, 8, 7, 5, 4, 1, 3, 2, 4, 5, 8, 9]

# Adjust the border color
plt.hist(values, edgecolor="black")

plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()

png

More Examples

Change the Border Width

plt.hist() accepts Matplotlib's rectangle properties. This means you can use the linewidth parameter to make the border thicker or thinner.

# Adjust the border width here
plt.hist(values, edgecolor="black", linewidth=4)

plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()

png