make a histogram based on number of buckets from a list in python

You can create a histogram based on the number of buckets from a list in Python by using the Matplotlib and NumPy libraries. Here is an example code:

main.py
import matplotlib.pyplot as plt
import numpy as np

# Create a list of random numbers
data = np.random.normal(size=1000)

# Set the number of buckets (bins) for the histogram
num_bins = 20

# Create the histogram
n, bins, patches = plt.hist(data, num_bins, density=True, alpha=0.6, color='b')

# Add labels and title to the plot
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')

# Add a grid to the plot
plt.grid(True)

# Show the plot
plt.show()
465 chars
23 lines

In this code, we first import the necessary libraries. We then create a list of random numbers using NumPy's random.normal() function. We set the number of buckets (bins) for the histogram using the num_bins variable. We create the histogram using Matplotlib's hist() function and pass in the data, number of bins, and other optional parameters like density, alpha, and color. Finally, we add a title, labels, and a grid to the plot before showing it using plt.show().

gistlibby LogSnag