-->

Python - Matplotlib Pyplot Part 4: Histograms

Histograms are used to show the frequency distribution of a dataset.

Examples and Explanation

Basic Histogram

data = [1, 2, 2, 3, 3, 3, 4, 4, 5]

plt.hist(data, bins=5)

plt.title("Basic Histogram")

plt.show()

Explanation: The hist() function automatically groups data into bins and shows their frequency.

Customizing Bins

plt.hist(data, bins=[0, 1, 2, 3, 4, 5], color='skyblue', edgecolor='black')

plt.title("Customized Bins Histogram")

plt.show()

Explanation: Customizing bins provides finer control over the data distribution view.

Overlaying Multiple Histograms

data1 = [1, 2, 2, 3, 4]

data2 = [2, 3, 3, 4, 5]

plt.hist(data1, bins=5, alpha=0.5, label='Data 1')

plt.hist(data2, bins=5, alpha=0.5, label='Data 2')

plt.legend()

plt.title("Overlayed Histograms")

plt.show()

Explanation: Overlaying histograms allows for easy comparison between datasets.