When you use custom bin edges in a histogram (like bins=[0,1,2,3,4,5,10,...]), the widths of the bars will naturally vary to reflect the actual bin widths. If you want the bars to appear equally spaced and sized visually (even if the bins are not equal in width), you can simulate a histogram using a bar plot instead of plt.hist.
Here’s how you can do it:
✅ Step-by-step solution using plt.bar:
- Use numpy.histogram to compute the histogram manually.
- Plot the frequencies using plt.bar with a fixed bar width.
Example:
import numpy as np
import matplotlib.pyplot as plt
Example block_sizes data
block_sizes = [1, 2, 2, 3, 5, 10, 20, 20, 50, 100, 500, 1000, 5000, 100000]
Define custom bins
bins = [0, 1, 2, 3, 4, 5, 10, 20, 50, 100, 500, 1000, 5000, 100000]
Compute histogram
counts, bin_edges = np.histogram(block_sizes, bins=bins)
Create labels or positions for bars
x = np.arange(len(counts)) # equally spaced x positions
Plot using bar chart
plt.figure(figsize=(10, 6))
plt.bar(x, counts, width=0.8, color='skyblue', edgecolor='black')
Set x-tick labels to represent bin ranges
bin_labels = [f'{bin_edges[i]}–{bin_edges[i+1]}' for i in range(len(bin_edges)-1)]
plt.xticks(x, bin_labels, rotation=45, ha='right')
plt.title('Histogram of Block Sizes (Equal Bar Widths)')
plt.xlabel('Block Size Range')
plt.ylabel('Frequency')
plt.grid(axis='y', alpha=0.75)
plt.tight_layout()
plt.show()
✅ Result:
This will give you a histogram-like plot where all bars are equally spaced and sized, regardless of the actual bin widths. The x-axis labels will still reflect the true bin ranges.
Let me know if you want to keep the bar widths proportional to bin width but still have equal spacing between them.