By default, Matplotlib’s plt.hist draws each bar with a width that corresponds to the width of the bin. That is why if your bins are unevenly spaced, the bars will also have different widths.
If your goal is to display the histogram data using bars of a uniform (or “equal”) width regardless of the bin sizes, you’ll need to manually compute the histogram counts and then plot them using, for example, plt.bar. This way, you can control the bar width and position independently from the bin widths.
Below is an example of how you can do this:
import numpy as np
import matplotlib.pyplot as plt
# Example data (replace with your actual data)
block_sizes = np.random.randint(0, 100000, size=1000)
# Define your custom bins
bins = [0, 1, 2, 3, 4, 5, 10, 20, 50, 100, 500, 1000, 5000, 100000]
# Compute the histogram counts using NumPy
counts, bin_edges = np.histogram(block_sizes, bins=bins)
# Create labels for each bin (optional)
bin_labels = []
for i in range(len(bin_edges) - 1):
bin_labels.append(f"{bin_edges[i]}-{bin_edges[i+1]}")
# Number of bars (bins)
num_bars = len(counts)
# Plot using plt.bar with equal bar widths
plt.figure(figsize=(10, 6))
bar_width = 0.8 # uniform width for each bar
x_positions = np.arange(num_bars) # positions for the bars
plt.bar(x_positions, counts, width=bar_width, color='skyblue', edgecolor='black')
# Set x-ticks to be centered under each bar and label them with bin ranges
plt.xticks(x_positions, bin_labels, rotation=45)
plt.title('Histogram of Block Sizes (Uniform Bar Widths)')
plt.xlabel('Block Size Range')
plt.ylabel('Frequency')
plt.grid(axis='y', alpha=0.75)
plt.tight_layout() # Adjust layout to prevent clipping of tick-labels
plt.show()
Explanation
-
Computing the Histogram Manually:
We use np.histogram to compute the counts for each bin defined in bins.
-
Preparing Bar Positions and Labels:
Instead of using the bin edges as positions (which would be uneven), we assign each bar a position using np.arange(num_bars). We then create string labels that describe each bin range.
-
Plotting with plt.bar:
By plotting with plt.bar, you control the width (here set uniformly to 0.8) and the x positions. This way, even if the numerical width of each bin is different, the visual representation (the bars) will have the same width.
This approach lets you visually compare the counts across bins with equal spacing, even though the bins themselves are defined with different numerical ranges.