'How to add bins without interrupting edges in an histogram

I tried to modify the histogram such that the binning number(height) of the original histogram should be greater or equal to 3, if the binning number is not greater or equal to three then add those consecutive bins. But I am unable to plot the modified histogram.
Solution 1:[1]
You could calculate the histogram values via np.histogram(...). And then loop through the values and bin edges to draw the combined bars one by one:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.uniform(0, 10, 20)
values, bins = np.histogram(x, bins=np.arange(np.floor(x.min()), x.max() + 1))
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5), sharey=True)
bars = ax1.bar(bins[:-1], values, width=np.diff(bins), align='edge', facecolor='skyblue', edgecolor='black')
ax1.bar_label(bars, label_type='center', fontsize=20)
left = bins[0]
current_sum = 0
for val, right in zip(values, bins[1:]):
current_sum += val
if current_sum >= 3 or right == bins[-1]:
bar = ax2.bar(left, current_sum, width=right - left, align='edge', facecolor='skyblue', edgecolor='black')
ax2.bar_label(bar, label_type='center', fontsize=20)
left = right
current_sum = 0
ax2.tick_params(labelleft=True)
for ax in (ax1, ax2):
ax.set_xticks(np.arange(np.floor(bins[0]), bins[-1] + 1))
plt.tight_layout()
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

