Search code examples
pythonnumpymatplotlibhistogram

Histogram of integer values with correct x-axis ticks and labels


I have integer values from 0 to n (included) and I would like to plot a histogram with n+1 bars at with the correct x-axis labels. Here is my attempt.

import numpy as np
import matplotlib.pyplot as plt

# Generate integer values
n = 20
values = np.random.randint(low=0, high=(n+1), size=1000)

# Plot histogram
fig, ax = plt.subplots(figsize=(20, 4))
_, bins, _ = ax.hist(values, bins=n+1, edgecolor='k', color='lightsalmon')
ax.set_xticks(bins)
ax.set_xticklabels(bins.astype(int))
plt.show()

It is almost correct, but the x-axis looks weird.

enter image description here


Solution

  • This should do the job.

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Generate integer values
    n = 20
    values = np.random.randint(low=0, high=(n+1), size=1000)
    
    # Plot histogram
    fig, ax = plt.subplots(figsize=(20, 4))
    bins = np.arange(start=-0.5, stop=(n+1), step=1)
    _ = ax.hist(values, bins=bins, edgecolor='k', color='lightsalmon')
    ax.set_xticks(np.arange(n+1)
    plt.show()