Overlapping Histograms with Matplotlib in Python Last Updated : 06 May, 2025 Comments Improve Suggest changes Like Article Like Report Histograms are used to represent the frequencies across various intervals in a dataset. In this article, we will learn how to create overlapping histograms in Python using the Matplotlib library. The matplotlib.pyplot.hist() function will be used to plot these histograms so that we can compare different sets of data on the same chart. This makes it easy to spot patterns and differences in data.Step 1: Imporing the librariesWe will use Matplotlib for plotting graphs and Seaborn for loading datasets and creating visualizations. Python import matplotlib.pyplot as plt import seaborn as sns Step 2: Loading datasetWe will be using the Iris dataset which contains measurements of sepal length, sepal width, petal length and petal width for three different species of Iris flowers. Python data = sns.load_dataset('iris') print(data.head(5)) Output:Iris DatasetStep 3: Ploting HistogramsWe will plot histogram for sepal_length and petal_length. Python plt.hist(data['petal_length'], label='petal_length') plt.hist(data['sepal_length'], label='sepal_length') plt.legend(loc='upper right') plt.title('Overlapping') plt.show() Output:Overlapping HistogramHere, we can see that some part of the histogram for petal_length has been hidden behind the histogram for sepal_length. To properly visualize both the histograms we need to set the transparency parameter i.e alpha to a suitable value. So let's check various values for alpha and find out suitable one.Step 4: Setting TransparencyWe will set alpha=0.5 for both sepal_length and petal_length. Python plt.hist(data['petal_length'], alpha=0.5, label='petal_length') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length') plt.legend(loc='upper right') plt.title('Overlapping with both alpha=0.5') plt.show() Output:Histogram with alpha = 0.5After setting our alpha value to 0.5 we are able to properly see the histograms for both our values even though there is overlapping between them. Let us try to make further changes to our alpha and see its impact on our visualization.Step 5: Setting Different Alpha ValuseWe will set alpha=0.1 for sepal_length and 0.9 for petal_length Python plt.hist(data['petal_length'], alpha=0.9, label='petal_length') plt.hist(data['sepal_length'], alpha=0.1, label='sepal_length') plt.legend(loc='upper right') plt.title('Overlapping with alpha=0.1 and 0.9 for sepal and petal') plt.show() Output:Histogram with a Different AlphaStep 6: Create more than 2 overlapping histograms with customized colors.Now, let us plot more than two overlapping histograms where we need custom colors. Python plt.hist(data['sepal_width'], alpha=0.5, label='sepal_width', color='red') plt.hist(data['petal_width'], alpha=0.5, label='petal_width', color='green') plt.hist(data['petal_length'], alpha=0.5, label='petal_length', color='yellow') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length', color='purple') plt.legend(loc='upper right') plt.show() Output:Histogram with Customized ColorsHere, we created overlapping histograms for four different measurements of the Iris flowers. Each histogram is given a different color and some transparency so we can easily compare how these measurements are distributed. Comment More infoAdvertise with us Next Article Bin Size in Matplotlib Histogram R riyaaggarwal Follow Improve Article Tags : Python Python-matplotlib Practice Tags : python Similar Reads IntroductionMatplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It5 min readEnvironment Setup for MatplotlibMatplotlib is an overall package for creating static, animated, and interactive visualizations in Python. It literally opens up a whole new world of possibilities for you! Especially when it is used with Numpy or Pandas library, one can do unimaginable things. The plots give may give a new insight a1 min readUsing Matplotlib with Jupyter NotebookJupyter Notebook is a free, open-source web app that lets you create and share documents with live code and visualizations. It is commonly used for tasks like cleaning and transforming data, doing statistical analysis, creating visualizations and machine learning.Matplotlib is a popular Python libra2 min readIntroduction to MatplotlibMatplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert y4 min readMatplotlib PyplotPyplot is a submodule of the Matplotlib library in python and beginner-friendly tool for creating visualizations providing a MATLAB-like interface, to generate plots with minimal code. How to Use Pyplot for Plotting?To use Pyplot we must first download the Matplotlib module. For this write the follo2 min readMatplotlib - Axes ClassMatplotlib is one of the Python packages which is used for data visualization. You can use the NumPy library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is used for making 2D plots from data in arrays. Axes class Axes is the most basic and flexible4 min readMultiple PlotsHow to Create Multiple Subplots in Matplotlib in Python?To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with the objects Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid. By default, it returns a figure with a single3 min readHow to Add Title to Subplots in Matplotlib?In this article, we will see how to add a title to subplots in Matplotlib? 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 work3 min readHow to Set a Single Main Title for All the Subplots in Matplotlib?A title in Matplotlib library describes the main subject of plotting the graphs. Setting a title for just one plot is easy using the title() method. By using this function only the individual title plots can be set but not a single title for all subplots. Hence, to set a single main title for all su2 min readHow to Turn Off the Axes for Subplots in Matplotlib?In this article, we are going to discuss how to turn off the axes of subplots using matplotlib module. We can turn off the axes for subplots and plots using the below methods: Method 1: Using matplotlib.axes.Axes.axis() To turn off the axes for subplots, we will matplotlib.axes.Axes.axis() method he2 min readHow to Create Different Subplot Sizes in Matplotlib?In this article, we will learn different ways to create subplots of different sizes using Matplotlib. It provides 3 different methods using which we can create different subplots of different sizes. Methods available to create subplot: Gridspecgridspec_kwsubplot2gridCreate Different Subplot Sizes i4 min readHow to set the spacing between subplots in Matplotlib in Python?Let's learn how to set the spacing between the subplots in Matplotlib to ensure clarity and prevent the overlapping of plot elements, such as axes labels and titles.Let's create a simple plot with the default spacing to see how subplots can sometimes become congested.Pythonimport numpy as np import3 min readWorking with LegendsMatplotlib.pyplot.legend() in PythonA legend is an area describing the elements of the graph. In the Matplotlib library, thereâs a function called legend() which is used to place a legend on the axes. In this article, we will learn about the Matplotlib Legends.Python Matplotlib.pyplot.legend() SyntaxSyntax: matplotlib.pyplot.legend(["6 min readMatplotlib.axes.Axes.legend() in PythonMatplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.2 min readChange the legend position in MatplotlibIn this article, we will learn how to Change the legend position in Matplotlib. Let's discuss some concepts :Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure w2 min readHow to Change Legend Font Size in Matplotlib?Matplotlib is a library for creating interactive Data visualizations in Python. The functions in Matplotlib make it work like MATLAB software. The legend method in Matplotlib describes the elements in the plot. In this article, we are going to Change Legend Font Size in Matplotlib. Using pyplot.lege3 min readHow Change the vertical spacing between legend entries in Matplotlib?Prerequisites: Matplotlib In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module.Create data.Change the vertical spacing between label2 min readUse Multiple Columns in a Matplotlib LegendLegends helps to understand what each element in the plot represents. They help to understand the meaning behind different elements like colors, markers or line styles. If a plot contains many labels a single-column legend may:Take up too much vertical spaceOverlap with the plot andLook messy or clu3 min readHow to Create a Single Legend for All Subplots in Matplotlib?The subplot() function in matplotlib helps to create a grid of subplots within a single figure. In a figure, subplots are created and ordered row-wise from the top left. A legend in the Matplotlib library basically describes the graph elements. The legend() can be customized and adjusted anywhere in3 min readHow to manually add a legend with a color box on a Matplotlib figure ?A legend is basically an area in the plot which describes the elements present in the graph. Matplotlib provides an inbuilt method named legend() for this purpose. The syntax of the method is below : Example: Adding Simple legend Python3 # Import libraries import matplotlib.pyplot as plt # Creating2 min readHow to Place Legend Outside of the Plot in Matplotlib?In this article, we will see how to put the legend outside the plot. 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 t3 min readHow to Remove the Legend in Matplotlib?Matplotlib is one of the most popular data visualization libraries present in Python. Using this matplotlib library, if we want to visualize more than a single variable, we might want to explain what each variable represents. For this purpose, there is a function called legend() present in matplotli5 min readRemove the legend border in MatplotlibA legend helps explain the elements in a plot, and for adding a legend to a plot in Matplotlib, we use the legend() function. A border is added by default to the legend, but there may be some cases when you will prefer not having a border for a cleaner appearance. We will demonstrate how to do it qu2 min readLine ChartLine chart in Matplotlib - PythonMatplotlib is a data visualization library in Python. The pyplot, a sublibrary of Matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. In this article, we will learn about lin6 min readLine plot styles in MatplotlibLine plots are important data visualization elements that can be used to identify relationships within the data. Using matplotlib.pyplot.plot() function we can plot line plots. Styling tools in this helps us customize line plots according to our requirements which helps in better representations. Li3 min readPlot Multiple lines in MatplotlibIn this article, we will learn how to plot multiple lines using 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 designed6 min readChange the line opacity in MatplotlibChanging Line Opacity in Matplotlib means adjusting the transparency level of a line in a plot. Opacity controls how much the background or overlapping elements are visible through the line. A fully opaque line is solid, while a more transparent line allows other elements behind it to be seen. Let's3 min readIncrease the thickness of a line with MatplotlibPrerequisites: Matplotlib Matplotlib is the most widely used library for plotting graphs with the available dataset. Matplotlib supports line chart which are used to represent data over a continuous time span. In line chart, the data value is plotted as points and later connected by a line to show t3 min readHow to Fill Between Multiple Lines in Matplotlib?With the use of the fill_between() function in the Matplotlib library in Python, we can easily fill the color between any multiple lines or any two horizontal curves on a 2D plane. Syntax: matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)2 min readBar PlotBar Plot in MatplotlibA bar plot uses rectangular bars to represent data categories, with bar length or height proportional to their values. It compares discrete categories, with one axis for categories and the other for values.Consider a simple example where we visualize the sales of different fruits:Pythonimport matplo5 min readDraw a horizontal bar chart with MatplotlibMatplotlib is the standard python library for creating visualizations in Python. Pyplot is a module of Matplotlib library which is used to plot graphs and charts and also make changes in them. In this article, we are going to see how to draw a horizontal bar chart with Matplotlib. Creating a vertica2 min readCreate a stacked bar plot in MatplotlibIn this article, we will learn how to Create a stacked bar plot in Matplotlib. Let's discuss some concepts: Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure wi3 min readStacked Percentage Bar Plot In MatPlotLibA Stacked Percentage Bar Chart is a simple bar chart in the stacked form with a percentage of each subgroup in a group. Stacked bar plots represent different groups on the top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It go3 min readPlotting back-to-back bar charts MatplotlibIn 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 d2 min readHow to display the value of each bar in a bar chart using Matplotlib?In this article, we are going to see how to display the value of each bar in a bar chart using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib - Using matplotlib.axes.Axes.text() function.Use matplotlib.pyplot.text() function. Example 1: Using2 min readHow To Annotate Bars in Barplot with Matplotlib in Python?Annotation means adding notes to a diagram stating what values do it represents. It often gets tiresome for the user to read the values from the graph when the graph is scaled down or is overly populated. In this article, we will discuss how to annotate the bar plots created in python using matplotl3 min readHow to Annotate Bars in Grouped Barplot in Python?A Barplot is a graph that represents the relationship between a categoric and a numeric feature. Many rectangular bars correspond to each category of the categoric feature and the size of these bars represents the corresponding value. Using grouped bar plots,  we can study the relationship between m3 min readHistogramPlotting Histogram in Python using MatplotlibHistograms 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 Histogram6 min readCreate a cumulative histogram in MatplotlibThe 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 occurren2 min readHow to plot two histograms together in Matplotlib?Creating the histogram provides the visual representation of data distribution. By using a histogram we can represent a large amount of data and its frequency as one continuous plot. How to plot a histogram using Matplotlib For creating the Histogram in Matplotlib we use hist() function which belon3 min readOverlapping Histograms with Matplotlib in PythonHistograms are used to represent the frequencies across various intervals in a dataset. In this article, we will learn how to create overlapping histograms in Python using the Matplotlib library. The matplotlib.pyplot.hist() function will be used to plot these histograms so that we can compare diffe2 min readBin Size in Matplotlib HistogramBin size in a Matplotlib histogram controls how data is grouped into bins, each bin covers a value range and its height shows the count of data points in that range. Smaller bin sizes give more detailed distributions with many bins, while larger sizes produce fewer bins and a simpler view. For examp3 min readScatter PlotMatplotlib ScatterScatter plots are one of the most fundamental and powerful tools for visualizing relationships between two numerical variables. matplotlib.pyplot.scatter() plots points on a Cartesian plane defined by X and Y coordinates. Each point represents a data observation, allowing us to visually analyze how5 min readHow to add a legend to a scatter plot in Matplotlib ?Adding a legend to a scatter plot in Matplotlib means providing clear labels that describe what each group of points represents. For example, if your scatter plot shows two datasets, adding a legend will display labels for each dataset, helping viewers interpret the plot correctly. We will explore s2 min readHow to Connect Scatterplot Points With Line in Matplotlib?Prerequisite: Scatterplot using Seaborn in Python Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and2 min readHow to create a Scatter Plot with several colors in Matplotlib?Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. In this article, we w3 min readHow to increase the size of scatter points in Matplotlib ?Prerequisites: Matplotlib Scatter plots are the data points on the graph between x-axis and y-axis in matplotlib library. The points in the graph look scattered, hence the plot is named as 'Scatter plot'. The points in the scatter plot are by default small if the optional parameters in the syntax ar2 min readPie ChartPlot a Pie Chart in Python using MatplotlibA Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. Pie charts in Python are widely used in business presentations, reports, and dashboards due to their simplicity and effectiveness in displaying data d8 min readHow to set border for wedges in Matplotlib pie chart?Pie charts can be used for relative comparison of data. Python offers several data visualization libraries to work with. The Matplotlib library offers different types of graphs and inbuild methods and properties to manipulate the graph. The wedges in the pie chart can be given a border using the wed3 min readRadially displace pie chart wedge in MatplotlibPie charts are statistical graphs divided into slices that represent different data values and sum up to 100%. Python is one of the most popularly used programming languages for data visualization. Python has multiple data visualization libraries and Matplotlib is one of them. Matplotlib is widely u3 min read3D PlotsThree-dimensional Plotting in Python using MatplotlibVisualizing data involving three variables often requires three-dimensional plotting to better understand complex relationships and patterns that two-dimensional plots cannot reveal. Pythonâs Matplotlib library, through its mpl_toolkits.mplot3d toolkit, provides powerful support for 3D visualization5 min read3D Scatter Plotting in Python using MatplotlibA 3D Scatter Plot is a mathematical diagram that visualizes data points in three dimensions, allowing us to observe relationships between three variables of a dataset. Matplotlib provides a built-in toolkit called mplot3d, which enables three-dimensional plotting. To create a 3D Scatter Plot, we use3 min read3D Surface plotting in Python using MatplotlibA 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 wi4 min read3D Wireframe plotting in Python using MatplotlibTo 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 libra1 min read3D Contour Plotting in Python using MatplotlibMatplotlib 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 a2 min readTri-Surface Plot in Python using MatplotlibA Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex2 min readSurface plots and Contour plots in PythonSurface plots and contour plots are visualization tools used to represent three-dimensional data in two dimensions. They are commonly used in mathematics, engineering and data analysis to understand the relationships between three variables. In this article, we will understand about surface and cont3 min readHow to change angle of 3D plot in Python?Prerequisites: Matplotlib, NumPy In this article, we will see how can we can view our graph from different angles, Here we use three different methods to plot our graph. Before starting let's see some basic concepts of the required module for this objective. Matplotlib is a multi-platform data visua3 min readHow to animate 3D Graph using Matplotlib?Prerequisites: Matplotlib, NumPy Graphical representations are always easy to understand and are adopted and preferable before any written or verbal communication. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we create a beautiful4 min readWorking with ImagesWorking with Images in Python using MatplotlibMatplotlib 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. Working with Images in Python using Matplotlib The image module in matplotlib library is3 min readPython | Working with PNG Images using MatplotlibMatplotlib 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 was introduced by John Hunter in the year 2002. One of the greatest benefits of visua3 min readHow to Display an Image in Grayscale in Matplotlib?In this article, we are going to depict images using the Matplotlib module in grayscale representation using PIL, i.e. image representation using two colors only i.e. black and white. Syntax: matplotlib.pyplot.imshow(X, cmap=None) Displaying Grayscale image Displaying Grayscale image, store the imag2 min readPlot a Point or a Line on an Image with MatplotlibPrerequisites: Matplotlib Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python. ApproachImport modulesRead the imagePlot the line or point on the imageDisplay the plot/image. Image Used: Im2 min readHow to Draw Rectangle on Image in Matplotlib?Prerequisites: Matplotlib Given an image the task here is to draft a python program using matplotlib to draw a rectangle on it. Matplotlib comes handy with rectangle() function which can be used for our requirement. Syntax: Rectangle(xy, width, height, angle=0.0, **kwargs) Parameters: xy: Lower left2 min readHow to Display an OpenCV image in Python with Matplotlib?The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and vide2 min readCalculate the area of an image using MatplotlibLet us see how to calculate the area of an image in Python using Matplotlib. Algorithm: Import the matplotlib.pyplot module.Import an image using the imread() method.Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.Calcul1 min read Like