The Wayback Machine - http://web.archive.org/web/20240910173102/https://www.geeksforgeeks.org/plotting-histogram-in-python-using-matplotlib/
Open In App

Plotting Histogram in Python using Matplotlib

Last Updated : 09 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Histograms are a fundamental tool in data visualization, providing a graphical representation of the distribution of data. They are particularly useful for exploring continuous data, such as numerical measurements or sensor readings. This article will guide you through the process of Plot Histogram in Python using Matplotlib, covering the essential steps from data preparation to generating the histogram plot.

What is Matplotlib Histograms?

A Histogram represents data provided in the form of some groups. It is an accurate method for the graphical representation of numerical data distribution. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency.

Creating a Matplotlib Histogram

To create a Matplotlib histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values that fall into each of the intervals. Bins are identified as consecutive, non-overlapping intervals of variables.The matplotlib.pyplot.hist() function is used to compute and create a histogram of x. 

The following table shows the parameters accepted by matplotlib.pyplot.hist() function : 

Attribute Parameter
x array or sequence of array
bins optional parameter contains integer or sequence or strings
density Optional parameter contains boolean values
range Optional parameter represents upper and lower range of bins
histtype optional parameter used to create type of histogram [bar, barstacked, step, stepfilled], default is “bar”
align optional parameter controls the plotting of histogram [left, right, mid]
weights optional parameter contains array of weights having same dimensions as x
bottom location of the baseline of each bin
rwidth optional parameter which is relative width of the bars with respect to bin width
color optional parameter used to set color or sequence of color specs
label optional parameter string or sequence of string to match with multiple datasets
log optional parameter used to set histogram axis on log scale

Plotting Histogram in Python using Matplotlib

Here we will see different methods of Plotting Histogram in Matplotlib in Python:

  • Basic Histogram
  • Customized Histogram with Density Plot
  • Customized Histogram with Watermark
  • Multiple Histograms with Subplots
  • Stacked Histogram
  • 2D Histogram (Hexbin Plot)

Create a Basic Histogram in Matplotlib

Let’s create a basic histogram in Matplotlib using Python of some random values. 

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate random data for the histogram
data = np.random.randn(1000)
 
# Plotting a basic histogram
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
 
# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Basic Histogram')
 
# Display the plot
plt.show()


Output: 

 Histogram in Python using Matplotlib

Customized Histogram in Matplotlib with Density Plot

Let’s create a customized histogram with a density plot using Matplotlib and Seaborn in Python. The resulting plot visualizes the distribution of random data with a smooth density estimate.

Python3




import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
 
# Generate random data for the histogram
data = np.random.randn(1000)
 
# Creating a customized histogram with a density plot
sns.histplot(data, bins=30, kde=True, color='lightgreen', edgecolor='red')
 
# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Density')
plt.title('Customized Histogram with Density Plot')
 
# Display the plot
plt.show()


Output:

 Histogram Matplotlib

Customized Histogram with Watermark

Create a customized histogram using Matplotlib in Python with specific features. It includes additional styling elements, such as removing axis ticks, adding padding, and setting a color gradient for better visualization.

Python3




import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
 
 
# Creating dataset
np.random.seed(23685752)
N_points = 10000
n_bins = 20
 
# Creating distribution
x = np.random.randn(N_points)
y = .8 ** x + np.random.randn(10000) + 25
legend = ['distribution']
 
# Creating histogram
fig, axs = plt.subplots(1, 1,
                        figsize =(10, 7),
                        tight_layout = True)
 
 
# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
    axs.spines[s].set_visible(False)
 
# Remove x, y ticks
axs.xaxis.set_ticks_position('none')
axs.yaxis.set_ticks_position('none')
   
# Add padding between axes and labels
axs.xaxis.set_tick_params(pad = 5)
axs.yaxis.set_tick_params(pad = 10)
 
# Add x, y gridlines
axs.grid(b = True, color ='grey',
        linestyle ='-.', linewidth = 0.5,
        alpha = 0.6)
 
# Add Text watermark
fig.text(0.9, 0.15, 'Jeeteshgavande30',
         fontsize = 12,
         color ='red',
         ha ='right',
         va ='bottom',
         alpha = 0.7)
 
# Creating histogram
N, bins, patches = axs.hist(x, bins = n_bins)
 
# Setting color
fracs = ((N**(1 / 5)) / N.max())
norm = colors.Normalize(fracs.min(), fracs.max())
 
for thisfrac, thispatch in zip(fracs, patches):
    color = plt.cm.viridis(norm(thisfrac))
    thispatch.set_facecolor(color)
 
# Adding extra features   
plt.xlabel("X-axis")
plt.ylabel("y-axis")
plt.legend(legend)
plt.title('Customized histogram')
 
# Show plot
plt.show()


Output : 

 Histogram using Matplotlib

Multiple Histograms with Subplots

Let’s generates two histograms side by side using Matplotlib in Python, each with its own set of random data and provides a visual comparison of the distributions of data1 and data2 using histograms.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate random data for multiple histograms
data1 = np.random.randn(1000)
data2 = np.random.normal(loc=3, scale=1, size=1000)
 
# Creating subplots with multiple histograms
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 4))
 
axes[0].hist(data1, bins=30, color='Yellow', edgecolor='black')
axes[0].set_title('Histogram 1')
 
axes[1].hist(data2, bins=30, color='Pink', edgecolor='black')
axes[1].set_title('Histogram 2')
 
# Adding labels and title
for ax in axes:
    ax.set_xlabel('Values')
    ax.set_ylabel('Frequency')
 
# Adjusting layout for better spacing
plt.tight_layout()
 
# Display the figure
plt.show()


Output:

Screenshot-2023-12-05-222526

Stacked Histogram using Matplotlib

Let’s generates a stacked histogram using Matplotlib in Python, representing two datasets with different random data distributions. The stacked histogram provides insights into the combined frequency distribution of the two datasets.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate random data for stacked histograms
data1 = np.random.randn(1000)
data2 = np.random.normal(loc=3, scale=1, size=1000)
 
# Creating a stacked histogram
plt.hist([data1, data2], bins=30, stacked=True, color=['cyan', 'Purple'], edgecolor='black')
 
# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Stacked Histogram')
 
# Adding legend
plt.legend(['Dataset 1', 'Dataset 2'])
 
# Display the plot
plt.show()


Output:

Screenshot-2023-12-05-222933

Plot 2D Histogram (Hexbin Plot) using Matplotlib

Let’s generates a 2D hexbin plot using Matplotlib in Python, provides a visual representation of the 2D data distribution, where hexagons convey the density of data points. The colorbar helps interpret the density of points in different regions of the plot.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate random 2D data for hexbin plot
x = np.random.randn(1000)
y = 2 * x + np.random.normal(size=1000)
 
# Creating a 2D histogram (hexbin plot)
plt.hexbin(x, y, gridsize=30, cmap='Blues')
 
# Adding labels and title
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('2D Histogram (Hexbin Plot)')
 
# Adding colorbar
plt.colorbar()
 
# Display the plot
plt.show()


Output:

Screenshot-2023-12-05-222826

Conclusion

Plotting Matplotlib histograms is a simple and straightforward process. By using the hist() function, we can easily create histograms with different bin widths and bin edges. We can also customize the appearance of histograms to meet our needs



Previous Article
Next Article

Similar Reads

Plotting a Histogram with Total Height Equal to 1: A Technical Guide
Histograms are a fundamental tool in data visualization, providing a graphical representation of numerical data. One common requirement in histogram plotting is to ensure that the total height of the bars equals 1, which is particularly useful when dealing with probability distributions. This article will delve into the technical aspects of plottin
3 min read
Plot 2-D Histogram in Python using Matplotlib
In this article, we are going to learn how to plot 2D histograms using Matplotlib in Python. The graphical representation of the distribution of a dataset is known as a histogram. They can be used to show the frequency of values using in a dataset using bins which are obtained by dividing the data into a set of intervals. A histogram that shows the
4 min read
3D Wireframe plotting in Python using Matplotlib
To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: C/C++ Code # importing modules from
1 min read
3D Contour Plotting in Python using Matplotlib
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look at a 3d contour diagram of a 3d cosine function. Th
2 min read
3D Surface plotting in Python using Matplotlib
A Surface Plot is a representation of three-dimensional dataset. It describes a functional relationship between two independent variables X and Z and a designated dependent variable Y, rather than showing the individual data points. It is a companion plot of the contour plot. It is similar to the wireframe plot, but each face of the wireframe is a
4 min read
3D Scatter Plotting in Python using Matplotlib
A 3D Scatter Plot is a mathematical diagram, the most basic version of three-dimensional plotting used to display the properties of data as three variables of a dataset using the cartesian coordinates.To create a 3D Scatter plot, Matplotlib's mplot3d toolkit is used to enable three dimensional plotting.Generally 3D scatter plot is created by using
2 min read
Plotting cross-spectral density in Python using Matplotlib
Matplotlib is a comprehensive library consisting of modules that are used for Data Visualization just like MATLAB. Pyplot is a further module which makes functions and methods executable. Plotting Cross-Spectral Density The cross-spectral density compares two signals, each from different source taking into account both amplitude and phase differenc
2 min read
Plotting multiple bar charts using Matplotlib in Python
A multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many customizations such as Multiple bar plots, stacked bar plots, horizontal bar charts. Multiple bar charts are generally used for comparing different entities. In this article, plotting multiple bar charts are discussed. Example 1: Simple multiple bar chart In
4 min read
Plotting a Spectrogram using Python and Matplotlib
Prerequisites: Matplotlib A spectrogram can be defined as the visual representation of frequencies against time which shows the signal strength at a particular time. In simple words, a spectrogram is nothing but a picture of sound. It is also called voiceprint or voice grams. A spectrogram is shown using many colors which indicates the signal stren
3 min read
Three-dimensional Plotting in Python using Matplotlib
3D plots are very important tools for visualizing data that have three dimensions such as data that have two dependent and one independent variable. By plotting data in 3d plots we can get a deeper understanding of data that have three variables. We can use various matplotlib library functions to plot 3D plots. Example Of Three-dimensional Plotting
6 min read
Plotting Various Sounds on Graphs using Python and Matplotlib
In this article, we will explore the way of visualizing sounds waves using Python and Matplotlib. Modules Needed 1. Matplotlib: Install Matplotlib using the below command: pip install matplotlib 2. Numpy: Numpy gets installed automatically installed with Matplotlib. Although, if you face any import error, use the below command to install Numpy pip
3 min read
How to fill color by groups in histogram using Matplotlib?
In this article, we are going to see how to fill color by the group in the histogram using Matplotlib in Python. Method 1: Using pivot() method In this method, we are going to use the pivot method which returns an organized DataFrame based on specified index/column values. Syntax: DataFrameName.pivot(index='indexLabel', columns='columnLabel', value
2 min read
How to plot a histogram with various variables in Matplotlib in Python?
In this article, we are going to see how to plot a histogram with various variables in Matplotlib using Python. A histogram is a visual representation of data presented in the form of groupings. It is a precise approach for displaying numerical data distribution graphically. It's a type of bar plot in which the X-axis shows bin ranges and the Y-axi
3 min read
Different plotting using pandas and matplotlib
We have different types of plots in matplotlib library which can help us to make a suitable graph as you needed. As per the given data, we can make a lot of graph and with the help of pandas, we can create a dataframe before doing plotting of data. Let's discuss the different types of plot in matplotlib by using Pandas. Use these commands to instal
4 min read
Plotting A Square Wave Using Matplotlib, Numpy And Scipy
Prerequisites: linspace, Mathplotlib, Scipy A square wave is a non-sinusoidal periodic waveform in which the amplitude alternates at a steady frequency between the fixed minimum and maximum values, with the same duration at minimum and maximum. Graphical representations are always easy to understand and are adopted and preferable before any written
2 min read
Plotting a Sawtooth Wave using Matplotlib
Prerequisites: MatplotlibScipy A sawtooth waveform is a non-sinusoidal waveform because its teeth look like a saw. In an inverse (or reverse) sawtooth waveform the wave suddenly ramps downwards and then rises sharply. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we plot sawtooth
1 min read
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand
2 min read
Adding labels to histogram bars in Matplotlib
In this article, we are going to discuss how to add labels to histogram bars in matplotlib. Histograms are used to display continuous data using bars. It looks similar to the bar graph. It shows the count or frequency of element that falls under the category mentioned in that range it means, taller the graph, higher the frequency of that range. To
2 min read
Create a cumulative histogram in Matplotlib
The histogram is a graphical representation of data. We can represent any kind of numeric data in histogram format. In this article, We are going to see how to create a cumulative histogram in Matplotlib Cumulative frequency: Cumulative frequency analysis is the analysis of the frequency of occurrence of values. It is the total of a frequency and a
2 min read
Bin Size in Matplotlib Histogram
Prerequisites: Matplotlib A histogram is a graphical representation of the distribution of data given by the user. Its appearance is similar to Bar-Graph except it is continuous. The towers or bars of a histogram are called bins. The height of each bin shows how many values from that data fall into that range. Width of each bin is = (max value of d
4 min read
Add a border around histogram bars in Matplotlib
Prerequisites: Matplotlib In this article, we will see how can we can add a border around histogram bars in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module.Create data.Add border around histogram bars.Normally plot the data.Display plot. Below is the Implementation: Exampl
2 min read
Add space between histogram bars in Matplotlib
Matplotlib is a plotting library in Python programming language and it's by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram using matplotlib in python, it lacks division or spac
2 min read
How to Plot Histogram from List of Data in Matplotlib?
In this article, we are going to see how to Plot a Histogram from a List of Data in Matplotlib in Python. The histogram helps us to plot bar-graph with specified bins and can be created using the hist() function. Syntax: hist( dataVariable, bins=x, edgecolor='anyColor' ) Parameters: dataVariable- Any variable that holds a set of data. It can be a l
3 min read
Plotting back-to-back bar charts Matplotlib
In this article, we will learn how to plot back-to-back bar charts in matplotlib in python. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It w
2 min read
Introduction to 3D Plotting with Matplotlib
In this article, we will be learning about 3D plotting with Matplotlib. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, Matplotlib.pyplot.gca(), etc. Creating an Empty 3D Plot: In the below code, we will be creati
15+ min read
Plotting In A Non-Blocking Way With Matplotlib
When we plot a graph with Matplotlib, by default the execution of the code is stopped/blocked when it is viewed/drawn until the view window is closed. However, in certain cases, one may want to remove this blocking behavior and see the graph as soon as it is plotted or updated without blocking the program execution. This article addresses this issu
5 min read
Plotting Only the Upper/Lower Triangle of a Heatmap in Matplotlib
Heatmaps are a powerful visualization tool used to represent data in a matrix format, where individual values are represented by colors. They are particularly useful for visualizing correlation matrices, where the symmetric nature of the matrix makes it redundant to display both the upper and lower triangles. This article will guide you through the
4 min read
Plotting Bar Graph in Matplotlib from a Pandas Series
Bar graphs are one of the most common types of data visualizations used to represent categorical data with rectangular bars. Each bar's height or length corresponds to the value it represents. In Python, the combination of Pandas and Matplotlib libraries provides a powerful toolset for creating bar graphs. This article will guide you through the pr
3 min read
Compute the histogram of a set of data using NumPy in Python
Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated. Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None) Case 1: Computing the Numpy Histogram with th
2 min read
Visualizing Colors in Images Using Histogram in Python
In this article, we will discuss how to visualize colors in an image using histogram in Python. An image consists of various colors and we know that any color is a combination of Red, Green, Blue. So Image consists of Red, Green, Blue colors. So using Histogram we can visualize how much proportion we are having RGB colors in a picture. Histogram ac
2 min read