3

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()
3
  • A histogram is to show distribution. If you change the sizing of them it can be misleading. Perhaps a bar chart is more of what you're looking for? Commented Jul 15, 2020 at 5:16
  • Good point. Although in some cases we only need to know there's a fat tail Commented Jul 15, 2020 at 5:57
  • See answers there : stackoverflow.com/questions/43005462/… Commented Oct 11, 2022 at 15:45

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Wow... this is bigger job than I'd expect! But using barplot is clever
@PawinData Most sophisticated job is changing x-axis labels... without that, the code can be clear and short.
Just using ax.set_xticklabels without ax.set_xticks can be tricky, as they are set automatically. Better set ax.set_xticks(range(len(bin_range))) and ax.set_xticklabels(x_labels) without inserting the empty strings.
@JohanC thx. Your method is so nice. Updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.