Data Visualization using Matplotlib in Python
Last Updated : 06 Aug, 2025
Matplotlib is a widely-used Python library used for creating static, animated and
interactive data visualizations. It is built on the top of NumPy and it can easily
handles large datasets for creating various types of plots such as line charts, bar
charts, scatter plots, etc.
2/4
Visualizing Data with Pyplot using Matplotlib
Pyplot is a module in Matplotlib that provides a simple interface for creating plots.
It allows users to generate charts like line graphs, bar charts and histograms with
minimal code. Let’s explore some examples with simple code to understand how
to use it effectively.
1. Line Chart
Line chart is one of the basic plots and can be created using plot() function. It is
used to represent a relationship between two data X and Y on a different axis.
Syntax:
matplotlib.pyplot.plot(x, y)
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Parameter: x, y Coordinates for data points.
Example: This code plots a simple line chart with labeled axes and a title using
Matplotlib.
import matplotlib.pyplot as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
plt.plot(x, y)
plt.title("Line Chart")
plt.ylabel('Y-Axis')
plt.xlabel('X-Axis')
plt.show()
Output
2. Bar Chart
Bar chart displays categorical data using rectangular bars whose lengths are
proportional to the values they represent. It can be plotted vertically or
horizontally to compare different categories.
Syntax:
matplotlib.pyplot.bar(x, height)
Parameter:
x: Categories or positions on x-axis.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
height: Heights of the bars (y-axis values).
Example: This code creates a simple bar chart to show total bills for different days.
X-axis represents the days and Y-axis shows total bill amount.
import matplotlib.pyplot as plt
x = ['Thur', 'Fri', 'Sat', 'Sun']
y = [170, 120, 250, 190]
plt.bar(x, y)
plt.title("Bar Chart")
plt.xlabel("Day")
plt.ylabel("Total Bill")
plt.show()
Output
3. Histogram
Histogram shows the distribution of data by grouping values into bins. The hist()
function is used to create it, with X-axis showing bins and Y-axis showing
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
frequencies.
Syntax:
matplotlib.pyplot.hist(x, bins=None)
Parameter:
x: Input data.
bins: Number of bins (intervals) to group data.
Example: This code plots a histogram to show frequency distribution of total bill
values from the list x. It uses 10 bins and adds axis labels and a title for clarity.
import matplotlib.pyplot as plt
x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20,
20,
21, 22, 23, 24, 25, 25, 26, 28, 30, 32, 35, 36, 38, 40, 42, 44, 48, 50]
plt.hist(x, bins=10, color='steelblue')
plt.title("Histogram")
plt.xlabel("Total Bill")
plt.ylabel("Frequency")
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
4. Scatter Plot
Scatter plots are used to observe relationships between variables. The scatter()
method in the matplotlib library is used to draw a scatter plot.
Syntax:
matplotlib.pyplot.scatter(x, y)
Parameter: x, y Coordinates of the points.
Example: This code creates a scatter plot to visualize the relationship between
days and total bill amounts using scatter().
import matplotlib.pyplot as plt
x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']
y = [170, 120, 250, 190, 160, 130, 240, 200]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.xlabel("Day")
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
plt.ylabel("Total Bill")
plt.show()
Output
5. Pie Chart
Pie chart is a circular chart used to show data as proportions or percentages. It is
created using the pie(), where each slice (wedge) represents a part of the whole.
Syntax:
matplotlib.pyplot.pie(x, labels=None, autopct=None)
Parameter:
x: Data values for pie slices.
labels: Names for each slice.
autopct: Format to display percentage (e.g., '%1.1f%%').
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Example: This code creates a simple pie chart to visualize distribution of different
car brands. Each slice of pie represents the proportion of cars for each brand in the
dataset.
import matplotlib.pyplot as plt
import pandas as pd
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]
data = [23, 10, 35, 15, 12]
plt.pie(data, labels=cars)
plt.title(" Pie Chart")
plt.show()
Output
Pie Chart
6. Box Plot
Box plot is a simple graph that shows how data is spread out. It displays the
minimum, maximum, median and quartiles and also helps to spot outliers easily.
Syntax:
matplotlib.pyplot.boxplot(x, notch=False, vert=True)
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Parameter:
x: Data for which box plot is to be drawn (usually a list or array).
notch: If True, draws a notch to show the confidence interval around the
median.
vert: If True, boxes are vertical. If False, they are horizontal.
Example: This code creates a box plot to show the data distribution and compare
three groups using matplotlib
import matplotlib.pyplot as plt
data = [ [10, 12, 14, 15, 18, 20, 22],
[8, 9, 11, 13, 17, 19, 21],
[14, 16, 18, 20, 23, 25, 27] ]
plt.boxplot(data)
plt.xlabel("Groups")
plt.ylabel("Values")
plt.title("Box Plot")
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
7. Heatmap
Heatmap is a graphical representation of data where values are shown as colors. It
helps visualize patterns, correlations or intensity in a matrix-like format. It is
created using imshow() method in Matplotlib.
Syntax:
matplotlib.pyplot.imshow(X, cmap='viridis')
Parameter:
X: 2D array (data to display as an image or heatmap).
cmap: Sets the color map.
Example: This code creates a heatmap of random 10×10 data using imshow(). It
uses 'viridis' color map and colorbar() adds a color scale.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
data = np.random.rand(10, 10)
plt.imshow(data, cmap='viridis', interpolation='nearest')
plt.colorbar()
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Heatmap')
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Heatmap
Explanation:
np.random.seed(0): Ensures same random values every time (reproducibility).
np.random.rand(10, 10): Generates a 10×10 array of random numbers between
0 and 1.
How to Customize Matplotlib Visualizations?
Customization in Matplotlib allows you to improve look and clarity of plots by
adjusting elements like colors, styles, labels, titles and gridlines. It helps make
visualizations more informative and visually appealing for better data
communication. Let’s explore different ways to customize visualizations:
1. Customizing Line Chart
Line charts can be customized using various properties:
1. Color: Change the color of the line
2. Linewidth: Adjust the width of the line
3. Marker: Change the style of plotted points
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
4. Markersize: Change the size of the markers
5. Linestyle: Define the style of the line like solid, dashed, etc.
Example: This code creates a customized line chart with a green dashed line,
thicker width, large circular markers and labeled axes and title.
import matplotlib.pyplot as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
plt.plot(x, y, color='green', linewidth=3, marker='o', markersize=15,
linestyle='--')
plt.title("Customizing Line Chart")
plt.ylabel('Y-Axis')
plt.xlabel('X-Axis')
plt.show()
Output
Customizing Line Chart
2. Customizing Bar Chart
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Bar charts can be made more informative and visually appealing by customizing:
Color: Fill color of the bars
Edgecolor: Color of the bar edges
Linewidth: Thickness of the edges
Width: Width of each bar
Example: This code creates a customized bar chart with green bars, blue edges,
thicker border lines and labeled axes and title.
import matplotlib.pyplot as plt
x = ['Thur', 'Fri', 'Sat', 'Sun']
y = [170, 120, 250, 190]
plt.bar(x, y, color='green', edgecolor='black', linewidth=2)
plt.title("Customizing Bar Chart")
plt.xlabel("Day")
plt.ylabel("Total Bill")
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Customizing Bar plot
3. Customizing Histogram Plot
To make histogram plots more effective various customizations can be applied:
Bins: Number of groups (bins) to divide data into
Color: Bar fill color
Edgecolor: Bar edge color
Linestyle: Style of the edges like solid, dashed, etc.
Alpha: Transparency level (0 = transparent, 1 = opaque)
Example: This code creates a customized histogram with green bars, blue edges,
dashed border lines, semi-transparent fill and labeled axes and title.
import matplotlib.pyplot as plt
x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16, 16, 17,
18, 18, 19, 20, 20, 21, 22, 23, 24, 25, 25, 26, 28, 30,
32, 35, 36, 38, 40, 42, 44, 48, 50]
plt.hist(x, bins=10, color='green', edgecolor='blue',linestyle='--', alpha=0.5)
plt.title("Customizing Histogram Plot")
plt.xlabel("Total Bill")
plt.ylabel("Frequency")
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Customizing Histogram
4. Customizing Scatter Plot
Scatter plots can be enhanced with:
S: Marker size (single value or array)
C: Color of markers or sequence of colors
Marker: Marker style like circle, diamond, etc.
Linewidths: Width of marker borders
Edgecolor: Color of marker borders
Alpha: Blending value, between 0 (transparent) and 1 (opaque)
Example: This code creates a customized scatter plot using diamond-shaped
markers, where color represents size, marker size reflects the total bill and
transparency is added for better visualization. It includes labeled axes and a title.
import matplotlib.pyplot as plt
x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
y = [170, 120, 250, 190, 180, 130, 260, 200]
size = [2, 3, 4, 2, 3, 2, 4, 3]
bill = [170, 120, 250, 190, 180, 130, 260, 200]
plt.scatter(x, y, c=size, s=bill, marker='D', alpha=0.5)
plt.title("Customizing Scatter Plot")
plt.xlabel("Day")
plt.ylabel("Total Bill")
plt.show()
Output
Customizing Scatter Plot
5. Customizing Pie Chart
To make pie charts more effective and visually appealing use:
Explode: Moving the wedges of the plot
Autopct: Label the wedge with their numerical value.
Color: Colors of the slices
Sadow: Used to create a shadow effect
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Example: This code creates a customized pie chart with colored slices, exploded
segments for emphasis, percentage labels with two decimal places and a shadow
effect for better visual appeal.
import matplotlib.pyplot as plt
import pandas as pd
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]
data = [23, 13, 35, 15, 12]
explode = [0.1, 0.5, 0, 0, 0]
colors = ( "orange", "cyan", "yellow","grey", "green",)
plt.pie(data, labels=cars, explode=explode, autopct='%1.2f%%',colors=colors,
shadow=True)
plt.show()
Output
Matplotlib’s Core Components: Figures and Axes
Before we proceed let’s understand two classes which are important for working
with Matplotlib.
1. Figure class
The Figure class represents the full drawing area or canvas that can hold one or
more plots. It is created using the figure() function and lets user control the overall
size, layout and background of the plot window.
Syntax:
matplotlib.figure.Figure(figsize=None, facecolor=None)
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Parameter:
figsize: Sets size of the figure (width, height) in inches.
facecolor: Sets background color of the figure.
Example:
This code demonstrates how to use Figure class to create a simple line plot. It sets
figure size and background color, adds custom axes, plots data and labels the axes
and title.
import matplotlib.pyplot as plt
# Create a Figure with basic size and background color
fig = plt.figure(figsize=(6, 4), facecolor='lightblue')
# Add Axes to the Figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
ax.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Figure class Representation
Explanation:
fig.add_axes() adds an Axes object to the figure.
[0.1, 0.1, 0.8, 0.8] defines the position left, bottom, width and height as a
fraction of figure size.
2. Axes Class
Axes class represents actual plotting area where data is drawn. It is the most basic
and flexible for creating plots or subplots within a figure. A single figure can
contain multiple axes but each Axes object belongs to only one figure. It can create
an Axes object using axes() function.
Syntax:
axes([left, bottom, width, height])
Example:
This code creates a figure using Figure class and adds a custom axes area to it. It
then plots two line graphs one for x vs y and another for y vs x. The graph includes
axis labels, a title and a legend for better clarity and presentation.
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
fig = plt.figure(figsize=(5, 4))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x, y)
ax.plot(y, x)
ax.set_title("Linear Graph")
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")
ax.legend(labels=('line 1', 'line 2'))
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Advanced Techniques for Visualizing Subplots
We have learned how to add basic parts to a graph to show more information. One
method can be by calling the plot function again and again with a different set of
values as shown in the above example. Now let’s see how to draw multiple graphs
in one figure using some Matplotlib functions and how to create subplots.
1. Using add_axes()
add_axes() method allows us to manually add axes to a figure in Matplotlib. It
takes a list of four values [left, bottom, width, height] to specify the position and
size of the axes.
Example:
This code creates two side-by-side plots using add_axes() one for x vs y and
another for y vs x all in a single figure.
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
fig = plt.figure(figsize=(10, 4))
ax1 = fig.add_axes([0.1, 0.1, 0.35, 0.8])
ax2 = fig.add_axes([0.55, 0.1, 0.35, 0.8])
ax1.plot(x, y)
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
ax2.plot(y, x)
plt.show()
Output
2. Using subplot()
The subplot() method adds a plot to a specified grid position within the current
figure. It takes three arguments: the number of rows, columns and plot index.
Example:
This code uses subplot() to create two plots side by side one for x vs y and the
other for y vs x within same figure.
import matplotlib.pyplot as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
plt.figure()
plt.subplot(121)
plt.plot(x, y)
plt.subplot(122)
plt.plot(y, x)
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
3. Using subplot2grid()
The subplot2grid() creates axes object at a specified location inside a grid and also
helps in spanning the axes object across multiple rows or columns.
Example:
This code uses subplot2grid() to place two stacked plots in a single figure one on
top of the other by defining their positions in a 7-row grid layout.
import matplotlib.pyplot as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
axes1 = plt.subplot2grid (
(7, 1), (0, 0), rowspan = 2, colspan = 1)
axes2 = plt.subplot2grid (
(7, 1), (2, 0), rowspan = 2, colspan = 1)
axes1.plot(x, y)
axes2.plot(y, x)
plt.show()
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Saving Plots Using savefig()
When plots are created using Matplotlib, users may want to save them as image
files for use in reports, presentations or sharing. Matplotlib offers savefig()
function to save the current plot to a file. By changing file extension, users can
store the plot in different formats such as .png, .jpg, .pdf or .svg.
Example:
import matplotlib.pyplot as plt
year = ['2010', '2002', '2004', '2006', '2008']
production = [25, 15, 35, 30, 10]
plt.bar(year, production)
plt.savefig("output.jpg")
plt.savefig("output1", facecolor='y', bbox_inches="tight",pad_inches=0.3,
transparent=True)
Output
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Line chart
Bar chart
Histogram
Scatter plot
Pie chart
Box plot
Heatmap
Comment More info Advertise with us
Explore
Python - Data visualization tutorial 5 min read
What is Data Visualization and Why is It Important? 4 min read
Data Visualization using Matplotlib in Python 11 min read
Data Visualization with Seaborn - Python 9 min read
Data Visualization with Pandas 6 min read
Plotly for Data Visualization in Python 12 min read
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Data Visualization using Plotnine and ggplot2 in Python 6 min read
Introduction to Altair in Python 4 min read
Python - Data visualization using Bokeh 4 min read
Pygal Introduction 5 min read
Do Not Sell or Share My Personal Information
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF