Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Creating Histograms in Matplotlib

3 min readOct 3, 2024

--

Introduction to Histograms in Matplotlib

In this blog, we will explore how to create histograms using Matplotlib, a popular Python plotting library. We will go through the code step by step to understand how it works, and how you can customize histograms to suit your needs.

import matplotlib.pyplot as plt
import numpy as np

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

plt.hist(data, bins=7)

plt.savefig("Plots/fig_with_histogram.png")
plt.clf()

data = np.random.randn(1000)

plt.hist(data, bins=30, color='green', edgecolor='black', density=True, cumulative=True)

plt.savefig("Plots/fig_with_histogram_color.png")
plt.clf()

Two different histogram examples will be demonstrated: one with a simple frequency count and another with more advanced customizations like color, edgecolor, and cumulative distribution.

Importing Required Libraries

import matplotlib.pyplot as plt
import numpy as np

We first import the required libraries: matplotlib.pyplot for plotting and numpy for handling numerical data. By importing matplotlib.pyplot as plt, we can use its functions in a more concise manner. Similarly, importing numpy as np makes the code more readable and easier to manage.

Creating a Simple Frequency Histogram

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

plt.hist(data, bins=7)

plt.savefig("Plots/fig_with_histogram.png")
plt.clf()

Explanation:

Data Creation: The list data contains a frequency distribution of numbers ranging from 1 to 7. Each number has a different frequency count, making it suitable for a histogram plot.

Histogram Plotting: We plot the histogram using the plt.hist() function, which takes the data and the number of bins as parameters. Here, bins=7 ensures the data is split into 7 categories (1–7).

Saving and Clearing the Plot: After plotting the histogram, the plt.savefig() function saves the plot as an image file, and plt.clf() clears the current figure to prepare for the next plot.

Output Example:

You can expect to see a simple frequency histogram with 7 bins, showing the distribution of the data in the range of 1 to 7.

Figure with histogram in matplotlib

Creating a Histogram with Customizations

data = np.random.randn(1000)

Random Data Generation: The function np.random.randn(1000) generates 1000 random numbers from a standard normal distribution (mean = 0, standard deviation = 1). This data will be used for the histogram.

Get Someone’s stories in your inbox

Join Medium for free to get updates from this writer.

Histogram with Customizations:

plt.hist(data, bins=30, color='green', edgecolor='black', density=True, cumulative=True)

— bins=30: The data is split into 30 bins.

— color=’green’: The bars of the histogram are filled with green color.

— edgecolor=’black’: The edges of the bars are outlined in black, making them more distinct.

— density=True: This normalizes the histogram, so the area under the histogram integrates to 1, turning the frequency counts into probability density.

— cumulative=True: This generates a cumulative histogram, meaning each bar shows the sum of the frequencies up to that point.

Saving and Clearing the Plot

plt.savefig("Plots/fig_with_histogram_color.png")
plt.clf()

Just like the previous example, the plot is saved and cleared after generation.

Output Example:

This will generate a cumulative histogram with 30 bins, colored green with black edges. The histogram will display the normalized density of the data.

Figure with customized histogram in matplotlib

Conclusion

In this blog, we covered the basics of creating histograms in Matplotlib. The first example illustrated how to create a simple frequency histogram, while the second example showcased a more advanced plot with customizations like color, edge color, cumulative distribution, and normalization.

These techniques can be adapted to a wide range of datasets to effectively visualize frequency distributions.

To view the other codes, feel free to check out my GitHub. Stay updated with my progress by following me on Twitter.

Thank you for following along, and I hope this guide helps you in creating your own customized histograms!

--

--

Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development