Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a histogram with variable-width bins in Python?

Suppose I have data [1,2,3, 7,8,9,9, 20,30,40,100,1000] for which I want to draw a histogram with Python. All the bins I care about is [0,5], [5,10], and [10, +∞). How can I do it?

The following wouldn't do it, of course.

import matplotlib.pyplot as plt

data = [1,2,3, 7,8,9,9, 20,30,40,100,1000]
plt.figure()
plt.hist(data, bins=5, color="rebeccapurple")
plt.show()
like image 274
Paw in Data Avatar asked Jun 29 '26 04:06

Paw in Data


1 Answers

In case of forcing to show a histogram with customized x-range, you might need to process your data first.

I made a list of ranges and also x_ticklabels to show x-axis with range.

import matplotlib.pyplot as plt
import numpy as np

data = [1,2,3, 7,8,9,9, 20,30,40,100,1000,500,200]
data = np.array(data)
bin_range = [
    [0, 5],
    [5, 10],
    [10, 10000] # enough number to cover range
]

data2plot = np.zeros(len(bin_range))

for idx, (low, high) in enumerate(bin_range):
    data2plot[idx] = ((low <= data) & (data < high)).sum()
    
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(range(len(bin_range)), data2plot)

x_labels = [
    f"{low}~{high}" for idx, (low, high) in enumerate(bin_range)
]

ax.set_xticks(range(len(bin_range)))
ax.set_xticklabels(x_labels)
plt.show()

enter image description here

like image 194
ilkyu tony lee Avatar answered Jun 30 '26 17:06

ilkyu tony lee