Matplotlib Tutorial
Last Updated : 23 Jul, 2025
Matplotlib 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. It offers a
variety of plotting functionalities, including line plots, bar charts, histograms, scatter plots and 3D
visualizations. Created by John D. Hunter in 2003, Matplotlib has become a fundamental tool for data
visualization in Python, extensively used by data scientists, researchers and engineers worldwide.
To learn Matplotlib step-by-step, refer to our page: Matplotlib Step-by-Step Guide.
Important Facts to know:
Matplotlib Pyplot: The pyplot module is a collection of functions that make Matplotlib work like
MATLAB, providing a simple interface for creating plots.
Figure and Axes: In Matplotlib, figures represent the overall container, while axes refer to the
individual plots within a figure.
Integration with Pandas: Matplotlib works seamlessly with Pandas DataFrames, enabling efficient
data visualization.
What is Matplotlib in Python used for?
With Matplotlib, we can perform a wide range of visualization tasks, including:
Creating basic plots such as line, bar and scatter plots.
Customizing plots with labels, titles, legends and color schemes.
Adjusting figure size, layout and aspect ratios.
Saving plots in various formats like PNG, PDF and SVG.
Combining multiple plots into subplots for better data representation.
Creating interactive plots using the widget module.
Learn Matplotlib
Now that we know what Matplotlib is and its uses, let’s move towards the tutorial part. Below, you will
find sections ranging from basic to advanced topics that will help you master Matplotlib.
Matplotlib Basics
In this section, we will explore the fundamentals of Matplotlib. We will start with an introduction, learn
how to install it and understand its core functionalities. Additionally, we will cover how to use Jupyter
Notebook for interactive visualizations.
Matplotlib Introduction
Introduction to Matplotlib
Last Updated : 11 Jul, 2025
Matplotlib 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 your boring data
into interactive plots and graphs, Matplotlib is the tool for you.
To learn Matplotlib from scratch to detail, refer to our article: Matplotlib Tutorial.
Example of a Plot in Matplotlib:
Let's create a simple line plot using Matplotlib, showcasing the ease with which you can visualize data.
import [Link] as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
[Link](x, y)
[Link]()
Output:
Simplest plot in
Matplotlib
Components or Parts of Matplotlib Figure
Anatomy of a Matplotlib Plot: This section dives into the key components of a Matplotlib plot, including
figures, axes, titles, and legends, essential for effective data visualization.
The parts of a Matplotlib figure include (as shown in the figure above):
Figure: The overarching container that holds all plot elements, acting as the canvas for visualizations.
Axes: The areas within the figure where data is plotted; each figure can contain multiple axes.
Axis: Represents the x-axis and y-axis, defining limits, tick locations, and labels for data interpretation.
Lines and Markers: Lines connect data points to show trends, while markers denote individual data
points in plots like scatter plots.
Title and Labels: The title provides context for the plot, while axis labels describe what data is being
represented on each axis.
Matplotlib Pyplot
Pyplot is a module within Matplotlib that provides a MATLAB-like interface for making plots. It
simplifies the process of adding plot elements such as lines, images, and text to the axes of the current
figure. Steps to Use Pyplot:
Import Matplotlib: Start by importing [Link] as plt.
Create Data: Prepare your data in the form of lists or arrays.
Plot Data: Use [Link]() to create the plot.
Customize Plot: Add titles, labels, and other elements using methods like [Link](), [Link](), and
[Link]().
Display Plot: Use [Link]() to display the plot.
Let's visualize a basic plot, and understand basic components of matplotlib figure:
import [Link] as plt
x = [0, 2, 4, 6, 8]
y = [0, 4, 16, 36, 64]
fig, ax = [Link]()
[Link](x, y, marker='o', label="Data Points")
ax.set_title("Basic Components of Matplotlib Figure")
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")
[Link]()
Output:
Basic Components
of matplotlib figure
Different Types of Plots in Matplotlib
Matplotlib offers a wide range of plot types to suit various data visualization needs. Here are some of the
most commonly used types of plots in Matplotlib:
1. Line Graph
2. Bar Chart
3. Histogram
4. Scatter Plot
5. Pie Chart
6. 3D Plot
and many more..
Bar chart and Pie chart
For learning about the different types of plots in Matplotlib, please read Types of Plots in Matplotlib.
Key Features of Matplotlib
Versatile Plotting: Create a wide variety of visualizations, including line plots, scatter plots, bar
charts, and histograms.
Extensive Customization: Control every aspect of your plots, from colors and markers to labels and
annotations.
Seamless Integration with NumPy: Effortlessly plot data arrays directly, enhancing data manipulation
capabilities.
High-Quality Graphics: Generate publication-ready plots with precise control over aesthetics.
Cross-Platform Compatibility: Use Matplotlib on Windows, macOS, and Linux without issues.
Interactive Visualizations: Engage with your data dynamically through interactive plotting features.
What is Matplotlib Used For?
Matplotlib is a Python library for data visualization, primarily used to create static, animated, and
interactive plots. It provides a wide range of plotting functions to visualize data effectively.
Key Uses of Matplotlib:
Basic Plots: Line plots, bar charts, histograms, scatter plots, etc.
Statistical Visualization: Box plots, error bars, and density plots.
Customization: Control over colors, labels, gridlines, and styles.
Subplots & Layouts: Create multiple plots in a single figure.
3D Plotting: Surface plots and 3D scatter plots using mpl_toolkits.mplot3d.
Animations & Interactive Plots: Dynamic visualizations with FuncAnimation.
Integration: Works well with Pandas, NumPy and Jupyter Notebooks.
Line chart in Matplotlib - Python
Last Updated : 23 Jul, 2025
Matplotlib 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 line charts and matplotlib simple line plots
in Python. Here, we will see some of the examples of a line chart in Python
using Matplotlib:
Matplotlib Simple Line Plot
Example 1: In this example, a simple line chart is generated using NumPy to define
data values. The x-values are evenly spaced points, and the y-values are calculated
as twice the corresponding x-values.
import [Link] as plt
import numpy as np
x = [Link]([1, 2, 3, 4]) # X-axis
y = x*2 # Y-axis
[Link](x, y)
[Link]()
Output
Simple line plot between X and Y data
Explanation: This is a basic line chart where x contains four points and y is
calculated as twice of each x value. [Link]() creates the line and [Link]() renders
the plot.
Example 2: We can see in the above output image that there is no label on the x-axis
and y-axis. Since labeling is necessary for understanding the chart dimensions. In the
following example, we will see how to add labels, Ident in the charts.
import [Link] as plt
import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
[Link](x, y)
[Link]("X-axis") # Label for the X-axis
[Link]("Y-axis") # Label for the Y-axis
[Link]("Any suitable title") # Chart title
[Link]()
Output
Simple line plot with labels and title
Line Chart with Annotations
In this example, a line chart is created using sample data points. Annotations
displaying the x and y coordinates are added to each data point on the line chart for
enhanced clarity.
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](figsize=(8, 6))
[Link](x, y, marker='o', linestyle='-')
# Add annotations
for i, (xi, yi) in enumerate(zip(x, y)):
[Link](f'({xi}, {yi})', (xi, yi), textcoords="offset points", xytext=(0, 10),
ha='center')
[Link]('Line Chart with Annotations')
[Link]('X-axis Label')
[Link]('Y-axis Label')
[Link](True)
[Link]()
Output
Explanation: data points are marked with circles (marker='o') and labeled
using [Link]() to show their exact coordinates.
Multiple Line Charts Using Matplotlib
We can display more than one chart in the same container by
using [Link]() function. This will help us in comparing the different charts and
also control the look and feel of charts.
import [Link] as plt
import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Any suitable title")
[Link]() # show first chart
[Link]()
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
[Link](x1, y1, '-.')
[Link]()
Output
Explanation: Here, two different line charts are plotted sequentially in separate
figures using [Link](). The first plot uses solid lines (default), and the second uses
a dashed-dot pattern ('-.').
Multiple Plots on the Same Axis
Here, we will see how to add 2 plots within the same axis.
import [Link] as plt
import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
# first plot with X and Y data
[Link](x, y)
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
# second plot with x1 and y1 data
[Link](x1, y1, '-.')
[Link]("X-axis data")
[Link]("Y-axis data")
[Link]('multiple plots')
[Link]()
Output
Explanation: This plots two lines in the same figure and on the same axes. It allows
direct comparison of different datasets. The second line uses a different style for
visual distinction.
Fill the Area Between Two Lines
Using the pyplot.fill_between() function we can fill in the region between two line plots
in the same graph. This will help us in understanding the margin of data between two
line plots based on certain conditions.
import [Link] as plt
import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
[Link](x, y)
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
[Link](x, y1, '-.')
[Link]("X-axis data")
[Link]("Y-axis data")
[Link]('multiple plots')
plt.fill_between(x, y, y1, color='green', alpha=0.5)
[Link]()
Output
Fill the area between Y and Y1 data
corresponding to X-axis data
Explanation: Highlights the area between two line plots using plt.fill_between(). The
alpha parameter adjusts transparency.
Bar Plot in Matplotlib
Last Updated : 12 Jul, 2025
A 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:
import [Link] as plt
import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Output:
Simple bar plot for fruits sales
What is a Bar Plot?
A bar plot (or bar chart) is a graphical representation that uses rectangular bars to
compare different categories. The height or length of each bar corresponds to the
value it represents. The x-axis typically shows the categories being compared, while
the y-axis shows the values associated with those categories. This visual format
makes it easy to compare quantities across different groups.
This function takes several parameters:
x: The categories (e.g., fruits).
height: The corresponding values (e.g., sales).
width: The width of the bars (default is 0.8).
bottom: The baseline for the bars (default is 0).
align: How to align bars ('center' or 'edge')
Why Use Bar Plots?
Bar plots are significant because they provide a clear and intuitive way to visualize
categorical data. They allow viewers to quickly grasp differences in size or quantity
among categories, making them ideal for presenting survey results, sales data, or any
discrete variable comparisons.
Syntax: [Link](x, height, width, bottom, align)
Customizing Bar Colors
You can customize the color of the bars by using the color parameter in
the bar() function:
import [Link] as plt
import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, color='violet')
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Output:
Changed color to Violet
Creating Horizontal Bar Plots
For horizontal bar plots, you can use the barh() function. This function works similarly
to bar(), but it displays bars horizontally:
import [Link] as plt
import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Output:
Horizontal Plots
Adjusting Bar Width
You can control the width of the bars using the width parameter:
import [Link] as plt
import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, width=0.3)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Output:
bar plot with low width()
Multiple bar plots
Multiple bar plots are used when comparison among the data set is to be done when
one variable is changing. We can easily convert it as a stacked area bar chart, where
each subgroup is displayed by one on top of the others. It can be plotted by varying
the thickness and position of the bars. Following bar plot shows the number of
students passed in the engineering branch:
import numpy as np
import [Link] as plt
barWidth = 0.25
fig = [Link](figsize =(12, 8))
IT = [12, 30, 1, 8, 22]
ECE = [28, 6, 16, 5, 10]
CSE = [29, 3, 24, 25, 17]
br1 = [Link](len(IT))
br2 = [x + barWidth for x in br1]
br3 = [x + barWidth for x in br2]
[Link](br1, IT, color ='r', width = barWidth,
edgecolor ='grey', label ='IT')
[Link](br2, ECE, color ='g', width = barWidth,
edgecolor ='grey', label ='ECE')
[Link](br3, CSE, color ='b', width = barWidth,
edgecolor ='grey', label ='CSE')
[Link]('Branch', fontweight ='bold', fontsize = 15)
[Link]('Students passed', fontweight ='bold', fontsize = 15)
[Link]([r + barWidth for r in range(len(IT))],
['2015', '2016', '2017', '2018', '2019'])
[Link]()
[Link]()
Output:
Stacked bar plot
Stacked bar plots represent different groups on top of one another. The height of the
bar depends on the resulting height of the combination of the results of the groups. It
goes from the bottom to the value instead of going from zero to value. The following
bar plot represents the contribution of boys and girls in the team.
import numpy as np
import [Link] as plt
N=5
boys = (20, 35, 30, 35, 27)
girls = (25, 32, 34, 20, 25)
boyStd = (2, 3, 4, 1, 2)
girlStd = (3, 5, 2, 3, 3)
ind = [Link](N)
width = 0.35
fig = [Link](figsize =(10, 7))
p1 = [Link](ind, boys, width, yerr = boyStd)
p2 = [Link](ind, girls, width,
bottom = boys, yerr = girlStd)
[Link]('Contribution')
[Link]('Contribution by the teams')
[Link](ind, ('T1', 'T2', 'T3', 'T4', 'T5'))
[Link]([Link](0, 81, 10))
[Link]((p1[0], p2[0]), ('boys', 'girls'))
[Link]()
Output:
Matplotlib Scatter
Last Updated : 31 May, 2025
Scatter plots are one of the most fundamental and powerful tools for visualizing
relationships between two numerical variables. [Link]() plots
points on a Cartesian plane defined by X and Y coordinates. Each point represents a
data observation, allowing us to visually analyze how two variables correlate, cluster
or distribute. For example:
import [Link] as plt
import numpy as np
x = [Link]([12, 45, 7, 32, 89, 54, 23, 67, 14, 91])
y = [Link]([99, 31, 72, 56, 19, 88, 43, 61, 35, 77])
[Link](x, y)
[Link]("Basic Scatter Plot")
[Link]("X Values")
[Link]("Y Values")
[Link]()
Output
Using [Link]()
Explanation: [Link](x, y) creates a scatter plot on a 2D plane to visualize the
relationship between two variables, with a title and axis labels added for clarity and
context.
Syntax
[Link](x, y, s=None, c=None, marker=None, cmap=None,
alpha=None, edgecolors=None, label=None)
Parameters:
Parameter Description
x, y Sequences of data points to plot
s Marker size (scalar or array-like)
c Marker color
marker Shape of the marker
cmap Colormap for mapping numeric values to colors
alpha Transparency (0 = transparent, 1 = opaque)
edgecolors Color of marker edges
label Legend label for the dataset
Returns: This function returns a PathCollection object representing the scatter plot
points. This object can be used to further customize the plot or to update it
dynamically.
Examples
Example 1: In this example, we compare the height and weight of two different groups
using different colors for each group.
x1 = [Link]([160, 165, 170, 175, 180, 185, 190, 195, 200, 205])
y1 = [Link]([55, 58, 60, 62, 64, 66, 68, 70, 72, 74])
x2 = [Link]([150, 155, 160, 165, 170, 175, 180, 195, 200, 205])
y2 = [Link]([50, 52, 54, 56, 58, 64, 66, 68, 70, 72])
[Link](x1, y1, color='blue', label='Group 1')
[Link](x2, y2, color='red', label='Group 2')
[Link]('Height (cm)')
[Link]('Weight (kg)')
[Link]('Comparison of Height vs Weight between two groups')
[Link]()
[Link]()
Output
Using [Link]()
Explanation: We define NumPy arrays x1, y1 and x2, y2 for height and weight data
of two groups. Using [Link](), Group 1 is plotted in blue and Group 2 in red, each
with labels. The x-axis and y-axis are labeled "Height (cm)" and "Weight (kg)" for
clarity.
Example 2: This example demonstrates how to customize a scatter plot using
different marker sizes and colors for each point. Transparency and edge colors are
also adjusted.
x = [Link]([3, 12, 9, 20, 5, 18, 22, 11, 27, 16])
y = [Link]([95, 55, 63, 77, 89, 50, 41, 70, 58, 83])
a = [20, 50, 100, 200, 500, 1000, 60, 90, 150, 300] # size
b = ['red', 'green', 'blue', 'purple', 'orange', 'black', 'pink', 'brown', 'yellow',
'cyan'] # color
[Link](x, y, s=a, c=b, alpha=0.6, edgecolors='w', linewidth=1)
[Link]("Scatter Plot with Varying Colors and Sizes")
[Link]()
Output
Using [Link]()
Explanation: NumPy arrays x and y set point coordinates, a defines marker sizes
and b assigns colors. [Link]() plots the points with transparency, white edges and
linewidth. A title is added before displaying the plot.
Example 3: This example shows how to create a bubble plot where the size of each
point (bubble) represents a variable's magnitude. Edge color and alpha transparency
are also used.
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
sizes = [30, 80, 150, 200, 300] # Bubble sizes
[Link](x, y, s=sizes, alpha=0.5, edgecolors='blue', linewidths=2)
[Link]("Bubble Plot Example")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
Output
Plotting Histogram in Python using Matplotlib
Last Updated : 22 Sep, 2025
Histograms are one of the most fundamental tools in data visualization. They provide
a graphical representation of data distribution, showing how frequently each value or
range of values occurs. Histograms are especially useful for analyzing continuous
numerical data, such as measurements, sensor readings, or experimental results.
A histogram is a type of bar plot where:
The X-axis represents intervals (called bins) of the data.
The Y-axis represents the frequency of values within each bin.
Unlike regular bar plots, histograms group data into bins to summarize data
distribution effectively.
Creating a Matplotlib Histogram
1. Divide the data range into consecutive, non-overlapping intervals called bins.
2. Count how many values fall into each bin.
3. Use the [Link]() function to plot the histogram.
The following table shows the parameters accepted by [Link]() function
:
Attribute Parameter
x Array or sequence of numerical data.
Number of bins (int) or specific intervals
bins
(array).
If True, normalizes histogram to show
density
probability instead of frequency.
range Tuple specifying lower and upper limits of bins.
Type of histogram: bar, barstacked, step,
histtype
stepfilled. Default: bar.
align Bin alignment: left, right, mid.
weights Array of weights for each data point.
bottom Baseline for bins.
rwidth Relative width of bars (0–1).
Color of bars. Can be a single color or
color
sequence.
Attribute Parameter
label Label for legend.
log If True, uses logarithmic scale on Y-axis.
Plotting Histogram in Python using Matplotlib
Here we will see different methods of Plotting Histogram in Matplotlib in Python:
1. Basic Histogram
2. Customized Histogram with Density Plot
3. Customized Histogram with Watermark
4. Multiple Histograms with Subplots
5. Stacked Histogram
6. 2D Histogram (Hexbin Plot)
1. Basic Histogram
import [Link] as plt
import numpy as np
# Generate random data for the histogram
data = [Link](1000)
# Plotting a basic histogram
[Link](data, bins=30, color='skyblue', edgecolor='black')
# Adding labels and title
[Link]('Values')
[Link]('Frequency')
[Link]('Basic Histogram')
# Display the plot
[Link]()
Output
Explanation:
Generates 1000 random numbers from a standard normal distribution.
Plots a histogram with 30 bins, sky-blue bars, and black edges.
Adds X and Y axis labels and a title.
Displays the histogram plot.
This is the simplest way to visualize data distribution.
Plot a Pie Chart in Python using Matplotlib
Last Updated : 12 Jul, 2025
A 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 distributions. In this article, we will explore how to
create a pie chart in Python using the Matplotlib library, one of the most widely used
libraries for data visualization in Python.
Table of Content
Why Use Pie Charts?
Basic Structure of a Pie Chart
Plotting a Pie Chart in Matplotlib
Customizing Pie Charts
Creating a Nested Pie Chart in Python
Creating 3D Pie Charts
Why Use Pie Charts?
Pie charts provide a visual representation of data that makes it easy to compare parts
of a whole. They are particularly useful when:
Displaying relative proportions or percentages.
Summarizing categorical data.
Highlighting significant differences between categories.
However, while pie charts are useful, they also have limitations. They can become
cluttered with too many categories or lead to misinterpretation if not designed
thoughtfully. Despite this, a well-crafted pie chart using Matplotlib can significantly
enhance the presentation of your data.
Basic Structure of a Pie Chart
A pie chart consists of slices that represent different categories. The size of each slice
is proportional to the quantity it represents. The following components are essential
when creating a pie chart in Matplotlib:
Data: The values or counts for each category.
Labels: The names of each category, which will be displayed alongside the slices.
Colors: Optional, but colors can be used to differentiate between slices effectively.
Matplotlib API has pie() function in its pyplot module which create a pie
chart representing the data in an array. let's create pie chart in python.
Syntax: [Link](data, explode=None, labels=None, colors=None,
autopct=None, shadow=False)
Parameters:
data represents the array of data values to be plotted, the fractional area of each
slice is represented by data/sum(data)
labels is a list of sequence of strings which sets the label of each wedge.
color attribute is used to provide color to the wedges.
autopct is a string used to label the wedge with their numerical value.
shadow is used to create shadow of wedge.
Plotting a Pie Chart in Matplotlib
Let's create a simple pie chart using the pie() function in Matplotlib. This function is
a powerful and easy way to visualize the distribution of categorical data.
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)
# show plot
[Link]()
Output:
Customizing Pie Charts
Once you are familiar with the basics of pie charts in Matplotlib, you can start
customizing them to fit your needs. A pie chart can be customized on the basis
several aspects:
startangle: This attribute allows you to rotate the pie chart in
Python counterclockwise around the x-axis by the specified degrees.. By adjusting
this angle, you can change the starting position of the first wedge, which can
improve the overall presentation of the chart.
shadow: This boolean attribute adds a shadow effect below the rim of the pie.
Setting this to True can make your chart stand out and give it a more three-
dimensional appearance, enhancing the overall look of your pie chart in
Matplotlib.
wedgeprops: This parameter accepts a Python dictionary to customize the
properties of each wedge in the pie chart. You can specify various attributes such
as linewidth, edgecolor, and facecolor. This level of customization allows you to
enhance the visual distinction between wedges, making your matplotlib pie
chart more informative.
frame: When set to True, this attribute draws a frame around the pie chart. This
can help emphasize the chart's boundaries and improve its visibility, making it
clearer when presenting data.
autopct: This attribute controls how the percentages are displayed on the wedges.
You can customize the format string to define the appearance of the percentage
labels on each slice.
The explode parameter separates a portion of the chart, and colors define each
wedge's color. The autopct function customizes text display, and legend and title
functions enhance chart readability and aesthetics.
# Import libraries
import numpy as np
import [Link] as plt
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating explode data
explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)
# Creating color parameters
colors = ("orange", "cyan", "brown",
"grey", "indigo", "beige")
# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}
# Creating autocpt arguments
def func(pct, allvalues):
absolute = int(pct / 100.*[Link](allvalues))
return "{:.1f}%\n({:d} g)".format(pct, absolute)
# Creating plot
fig, ax = [Link](figsize=(10, 7))
wedges, texts, autotexts = [Link](data,
autopct=lambda pct: func(pct, data),
explode=explode,
labels=cars,
shadow=True,
colors=colors,
startangle=90,
wedgeprops=wp,
textprops=dict(color="magenta"))
# Adding legend
[Link](wedges, cars,
title="Cars",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
[Link](autotexts, size=8, weight="bold")
ax.set_title("Customizing pie chart")
# show plot
[Link]()
Output:
By leveraging the capabilities of the [Link]() function in Matplotlib, we can create
informative and visually appealing pie charts that help to communicate with data
effectively. Whether you are presenting data to stakeholders or creating visual aids for
your reports, mastering the art of plotting pie charts in Python is a valuable skill.
Creating a Nested Pie Chart in Python
A nested pie chart is an effective way to represent hierarchical data, allowing you to
visualize multiple categories and subcategories in a single view. In Matplotlib, you
can create a nested pie chart by overlaying multiple pie charts with different radii.
Below, we’ll explore how to create this type of chart in Python.
Here’s a simple example of how to create a nested pie chart using Matplotlib:
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
size = 6
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
data = [Link]([[23, 16], [17, 23],
[35, 11], [29, 33],
[12, 27], [41, 42]])
# normalizing data to 2 pi
norm = data / [Link](data)*2 * [Link]
# obtaining ordinates of bar edges
left = [Link]([Link](0,
[Link]()[:-1])).reshape([Link])
# Creating color scale
cmap = plt.get_cmap("tab20c")
outer_colors = cmap([Link](6)*4)
inner_colors = cmap([Link]([1, 2, 5, 6, 9,
10, 12, 13, 15,
17, 18, 20]))
# Creating plot
fig, ax = [Link](figsize=(10, 7),
subplot_kw=dict(polar=True))
[Link](x=left[:, 0],
width=[Link](axis=1),
bottom=1-size,
height=size,
color=outer_colors,
edgecolor='w',
linewidth=1,
align="edge")
[Link](x=[Link](),
width=[Link](),
bottom=1-2 * size,
height=size,
color=inner_colors,
edgecolor='w',
linewidth=1,
align="edge")
[Link](title="Nested pie chart")
ax.set_axis_off()
# show plot
[Link]()
Output:
The outer pie chart represents the main categories, while the inner pie chart
represents subcategories related to one of those main categories. This structure is
particularly useful for showing proportions within proportions, helping viewers
quickly grasp the relationships within the data.
Center Circle: The centre_circle is added to create the donut effect, providing a
clean visual separation between the outer and inner pie charts.
As with a regular pie chart in Python, you can customize various attributes, such
as startangle, shadow, autopct, and wedgeprops, to enhance the overall aesthetics of
your nested pie chart.