Histogram for discrete values with matplotlib

前端 未结 3 1431
轻奢々
轻奢々 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 01:39

    another version for just handling the simple case in a small amount of code! this time using numpy.unique and matplotlib.vlines:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # same seed/data as Manuel Martinez to make plot easy to compare
    np.random.seed(1337)
    data = np.random.binomial(100, 1/6, 1000)
    
    values, counts = np.unique(data, return_counts=True)
    
    plt.vlines(values, 0, counts, color='C0', lw=4)
    
    # optionally set y-axis up nicely
    plt.ylim(0, max(counts) * 1.06)
    

    giving me:

    which looks eminently readable

提交回复
热议问题