Histogram for discrete values with matplotlib

前端 未结 3 1442
轻奢々
轻奢々 2020-12-30 01:28

I sometimes have to histogram discrete values with matplotlib. In that case, the choice of the binning can be crucial: if you histogram [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] u

3条回答
  •  再見小時候
    2020-12-30 02:05

    Perhaps a less-complete answer than J Richard Snape's, but one that I recently learned and that I found intuitive and easy.

    import numpy as np
    import matplotlib.pyplot as plt
    
    # great seed
    np.random.seed(1337)
    
    # how many times will a fair die land on the same number out of 100 trials.
    data = np.random.binomial(n=100, p=1/6, size=1000)
    
    # the trick is to set up the bins centered on the integers, i.e.
    # -0.5, 0.5, 1,5, 2.5, ... up to max(data) + 1.5. Then you substract -0.5 to
    # eliminate the extra bin at the end.
    bins = np.arange(0, data.max() + 1.5) - 0.5
    
    # then you plot away
    fig, ax = plt.subplots()
    _ = ax.hist(data, bins)
    ax.set_xticks(bins + 0.5)
    

    Turns out that around 16/100 throws will be the same number!

提交回复
热议问题