0% found this document useful (0 votes)
1 views

Matplotlib

Matplotlib is a low-level graph plotting library in Python, primarily used for data visualization and created by John D. Hunter. It includes a submodule called Pyplot, which simplifies the plotting process and allows for various plot types such as line graphs, bar charts, and scatter plots. The document also details the anatomy of a Matplotlib plot, including figures, axes, and markers, along with examples of how to create and customize plots.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Matplotlib

Matplotlib is a low-level graph plotting library in Python, primarily used for data visualization and created by John D. Hunter. It includes a submodule called Pyplot, which simplifies the plotting process and allows for various plot types such as line graphs, bar charts, and scatter plots. The document also details the anatomy of a Matplotlib plot, including figures, axes, and markers, along with examples of how to create and customize plots.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Matplotlib

What is Matplotlib? Matplotlib is a low level graph plotting library in python that serves as a
visualization utility.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for
Platform compatibility.

Pyplot Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:

import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt

Basic 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 matplotlib.pyplot as plt. Create Data: Prepare your data in the
form of lists or arrays. Plot Data: Use plt.plot() to create the plot. Customize Plot: Add titles, labels, and
other elements using methods like plt.title(), plt.xlabel(), and plt.ylabel(). Display Plot: Use plt.show() to
display the plot. Let’s visualize a basic plot, and understand basic components of matplotlib figure:

In [1]: import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define data points for x and y axes


x = [0, 2, 4, 6, 8]
y = [0, 4, 16, 36, 64]

# Create a figure and an axes


fig, ax = plt.subplots()

# Plot data points with markers and a label


ax.plot(x, y, marker='o', label="Data Points")

# Set the title of the plot


ax.set_title("Basic Components of Matplotlib Figure")
# Set the label for the x-axis
ax.set_xlabel("X-Axis")

# Set the label for the y-axis


ax.set_ylabel("Y-Axis")

# Display the plot


plt.show()

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

In [2]: import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define data points for x and y axes


x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

# Plot the data points


plt.plot(x, y)

# Display the plot


plt.show()
In [3]:
# Example
# Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis points using numpy array


xpoints = np.array([0, 6])

# Define y-axis points using numpy array


ypoints = np.array([0, 250])

# Plot the line connecting the points


plt.plot(xpoints, ypoints)

# Display the plot


plt.show()
Matplotlib Plotting
Plotting x and y points The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the plot
function.

In [4]:
# Example
# Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis points using numpy array


xpoints = np.array([1, 8])

# Define y-axis points using numpy array


ypoints = np.array([3, 10])

# Plot the line connecting the points


plt.plot(xpoints, ypoints)

# Display the plot


plt.show()
Plotting Without Line To plot only the markers, you can use shortcut string notation parameter 'o',
which means 'rings'.

In [5]:
# Example
# Draw two points in the diagram, one at position (1, 3) and one in positio

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis points using numpy array


xpoints = np.array([1, 8])

# Define y-axis points using numpy array


ypoints = np.array([3, 10])

# Plot the points using 'o' marker


plt.plot(xpoints, ypoints, 'o')

# Display the plot


plt.show()
Multiple Points You can plot as many points as you like, just make sure you have the same number of
points in both axis.

In [6]:
# Example
# Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) an

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis points using numpy array


xpoints = np.array([1, 2, 6, 8])

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the line connecting the points


plt.plot(xpoints, ypoints)

# Display the plot


plt.show()
Default X-Points If we do not specify the points on the x-axis, they will get the default values 0, 1, 2, 3
etc., depending on the length of the y-points.

So, if we take the same example as above, and leave out the x-points, the diagram will look like this:

In [7]: # Example
# Plotting without x-points:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10, 5, 7])

# Plot the y-axis points


plt.plot(ypoints)

# Display the plot


plt.show()
Matplotlib Markers
Markers You can use the keyword argument marker to emphasize each point with a specified marker:

In [8]:
# Example
# Mark each point with a circle:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers


plt.plot(ypoints, marker='o')

# Display the plot


plt.show()
In [2]:
#Example
#Mark each point with a star:
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = '*')


plt.show()

Marker Reference You can choose any of these markers:


Marker Description

'o' | Circle |
'*' | Star | '.' | Point | ',' | Pixel | 'x' | X | 'X' | X (filled) |
'+' | Plus | 'P' | Plus (filled) | 's' | Square | 'D' | Diamond | 'd' | Diamond (thin)| 'p' | Pentagon | 'H' | Hexagon |
'h' | Hexagon | 'v' | Triangle Down | '^' | Triangle Up | '<' | Triangle Left |
'>' | Triangle Right|
'1' | Tri Down | '2' | Tri Up | '3' | Tri Left |
'4' | Tri Right |
'|' | Vline | '_' | Hline |

Format Strings fmt You can also use the shortcut string notation parameter to specify the marker.

This parameter is also called fmt, and is written with this syntax:

marker|line|color

In [9]:
# Example
# Mark each point with a circle:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers, red color, and dotted line
plt.plot(ypoints, 'o:r')

# Display the plot


plt.show()

he marker value can be anything from the Marker Reference above.


The line value can be one of the following: Line Reference |Line Syntax | Description | --------------|-------------
--------| | '-' | Solid line | | ':' | Dotted line | | '--' | Dashed line |
| '-.' | Dashed/dotted line | Note: If you leave out the line value in the fmt parameter, no line will be
plotted.

Color Reference |Color Syntax |Description | |--------------|------------| | 'r' | Red |


| 'g' | Green |
| 'b' | Blue |
| 'c' | Cyan |
| 'm' | Magenta |
| 'y' | Yellow | | 'k' | Black |
| 'w' | White |
Marker Size You can use the keyword argument markersize or the shorter version, ms to set the size of
the markers:

In [10]:
# Example
# Set the size of the markers to 20:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers and set marker size to 20
plt.plot(ypoints, marker='o', ms=20)

# Display the plot


plt.show()

Marker Color You can use the keyword argument markeredgecolor or the shorter mec to set the color
of the edge of the markers:
In [11]:
# Example
# Set the EDGE color to red:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers, set marker size to 20, and ed
plt.plot(ypoints, marker='o', ms=20, mec='r')

# Display the plot


plt.show()

You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge
of the markers:

In [12]:
# Example
# Set the FACE color to red:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers, set marker size to 20, and fa
plt.plot(ypoints, marker='o', ms=20, mfc='r')
# Display the plot
plt.show()

Use both the mec and mfc arguments to color the entire marker:

In [13]: # Example
# Set the color of both the edge and the face to red:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers, set marker size to 20, edge c
plt.plot(ypoints, marker='o', ms=20, mec='r', mfc='r')

# Display the plot


plt.show()
You can also use Hexadecimal color values:

In [14]:
# Example
# Mark each point with a beautiful green color:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with circle markers, set marker size to 20, edge c
plt.plot(ypoints, marker='o', ms=20, mec='#4CAF50', mfc='#4CAF50')

# Display the plot


plt.show()
In [10]:
#Example
#Mark each point with the color named "hotpink":

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])


plt.plot(ypoints, marker = 'o', ms = 20, mec = 'hotpink', mfc = 'hotpink')
plt.show()
Matplotlib Line
Linestyle You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted
line:

In [15]:
# Example
# Use a dotted line:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with a dotted line style


plt.plot(ypoints, linestyle='dotted')

# Display the plot


plt.show()

In [16]: # Example
# Use a dashed line:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with a dashed line style


plt.plot(ypoints, linestyle='dashed')
# Display the plot
plt.show()

Shorter Syntax The line style can be written in a shorter syntax:

linestyle can be written as ls.

dotted can be written as :.

dashed can be written as --.

In [17]:
# Example
# Shorter syntax for line style:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with a dotted line style using shorter syntax
plt.plot(ypoints, ls=':') # 'ls' is the shorter syntax for 'linestyle'

# Display the plot


plt.show()
Line Styles You can choose any of these styles:

Style Or
'solid' (default) '-'
'dotted' ':'
'dashed' '--'
'dashdot' '-.'
'None' '' or ' '

Line Color You can use the keyword argument color or the shorter c to set the color of the line:

In [18]:
# Example
# Set the line color to red:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with the line color set to red
plt.plot(ypoints, color='r') # 'color' parameter sets the line color

# Display the plot


plt.show()
In [19]:
# Example
# Set the line color to green:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with the line color set to green using hex code
plt.plot(ypoints, c='#4CAF50') # 'c' is the shorter syntax for 'color'

# Display the plot


plt.show()
In [20]:
# Example
# Plot with the color named "hotpink":

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with the line color set to "hotpink"
plt.plot(ypoints, c='hotpink') # 'c' is the shorter syntax for 'color'

# Display the plot


plt.show()
Line Width You can use the keyword argument linewidth or the shorter lw to change the width of the
line.

The value is a floating number, in points:

In [21]: # Example
# Plot with a 20.5pt wide line:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points using numpy array


ypoints = np.array([3, 8, 1, 10])

# Plot the y-axis points with the line width set to 20.5 points
plt.plot(ypoints, linewidth=20.5) # 'linewidth' parameter sets the width o

# Display the plot


plt.show()
Multiple Lines You can plot as many lines as you like by simply adding more plt.plot() functions:

In [22]:
# Example
# Draw two lines by specifying a plt.plot() function for each line:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define y-axis points for the first line using numpy array
y1 = np.array([3, 8, 1, 10])

# Define y-axis points for the second line using numpy array
y2 = np.array([6, 2, 7, 11])

# Plot the first line


plt.plot(y1)

# Plot the second line


plt.plot(y2)

# Display the plot


plt.show()
You can also plot many lines by adding the points for the x- and y-axis for each line in the same
plt.plot() function.

(In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis
got the the default values (0, 1, 2, 3).)

The x- and y- values come in pairs:

In [23]:
# Example
# Draw two lines by specifying the x- and y-point values for both lines:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points for the first line using numpy arrays
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])

# Define x- and y-axis points for the second line using numpy arrays
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])

# Plot both lines by specifying x- and y-point values for each line
plt.plot(x1, y1, x2, y2)

# Display the plot


plt.show()
Matplotlib Labels and Title
Create Labels for a Plot With Pyplot, you can use the xlabel() and ylabel() functions to set a label for
the x- and y-axis.

In [24]:
# Example
# Add labels to the x- and y-axis:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Plot the x- and y-axis points


plt.plot(x, y)

# Add a label to the x-axis


plt.xlabel("Average Pulse")

# Add a label to the y-axis


plt.ylabel("Calorie Burnage")

# Display the plot


plt.show()
Create a Title for a Plot With Pyplot, you can use the title() function to set a title for the plot.

In [25]:
# Example
# Add a plot title and labels for the x- and y-axis:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Plot the x- and y-axis points


plt.plot(x, y)

# Add a title to the plot


plt.title("Sports Watch Data")

# Add a label to the x-axis


plt.xlabel("Average Pulse")

# Add a label to the y-axis


plt.ylabel("Calorie Burnage")

# Display the plot


plt.show()
Set Font Properties for Title and Labels You can use the fontdict parameter in xlabel(), ylabel(), and
title() to set font properties for the title and labels.

In [26]:
# Example
# Set font properties for the title and labels:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Define font properties for the title


font1 = {'family': 'serif', 'color': 'blue', 'size': 20}

# Define font properties for the labels


font2 = {'family': 'serif', 'color': 'darkred', 'size': 15}

# Add a title to the plot with specified font properties


plt.title("Sports Watch Data", fontdict=font1)

# Add a label to the x-axis with specified font properties


plt.xlabel("Average Pulse", fontdict=font2)

# Add a label to the y-axis with specified font properties


plt.ylabel("Calorie Burnage", fontdict=font2)
# Plot the x- and y-axis points
plt.plot(x, y)

# Display the plot


plt.show()

Position the Title You can use the loc parameter in title() to position the title.

Legal values are: 'left', 'right', and 'center'. Default value is 'center'.

In [27]:
# Example
# Position the title to the left:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Add a title to the plot and position it to the left


plt.title("Sports Watch Data", loc='left') # 'loc' parameter positions the

# Add a label to the x-axis


plt.xlabel("Average Pulse")
# Add a label to the y-axis
plt.ylabel("Calorie Burnage")

# Plot the x- and y-axis points


plt.plot(x, y)

# Display the plot


plt.show()

Matplotlib Adding Grid Lines


Add Grid Lines to a Plot With Pyplot, you can use the grid() function to add grid lines to the plot.

In [28]:
# Example
# Add grid lines to the plot:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Add a title to the plot


plt.title("Sports Watch Data")
# Add a label to the x-axis
plt.xlabel("Average Pulse")

# Add a label to the y-axis


plt.ylabel("Calorie Burnage")

# Plot the x- and y-axis points


plt.plot(x, y)

# Add grid lines to the plot


plt.grid()

# Display the plot


plt.show()

Specify Which Grid Lines to Display You can use the axis parameter in the grid() function to specify
which grid lines to display.

Legal values are: 'x', 'y', and 'both'. Default value is 'both'.

In [29]:
# Example
# Display only grid lines for the x-axis:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Add a title to the plot


plt.title("Sports Watch Data")

# Add a label to the x-axis


plt.xlabel("Average Pulse")

# Add a label to the y-axis


plt.ylabel("Calorie Burnage")

# Plot the x- and y-axis points


plt.plot(x, y)

# Add grid lines only for the x-axis


plt.grid(axis='x')

# Display the plot


plt.show()

In [26]:
#Example
#Display only grid lines for the y-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis = 'y')

plt.show()

Set Line Properties for the Grid You can also set the line properties of the grid, like this: grid(color =
'color', linestyle = 'linestyle', linewidth = number).

In [30]:
# Example
# Set the line properties of the grid:

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Define x-axis points using numpy array


x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

# Define y-axis points using numpy array


y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

# Add a title to the plot


plt.title("Sports Watch Data")

# Add a label to the x-axis


plt.xlabel("Average Pulse")
# Add a label to the y-axis
plt.ylabel("Calorie Burnage")

# Plot the x- and y-axis points


plt.plot(x, y)

# Add grid lines with specified properties: color, linestyle, and linewidth
plt.grid(color='green', linestyle='--', linewidth=0.5)

# Display the plot


plt.show()

Matplotlib Subplot
Display Multiple Plots With the subplot() function you can draw multiple plots in one figure:

In [31]:
# Example
# Draw 2 plots:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the first subplot in a 1x2 grid (1 row, 2 columns), position 1


plt.subplot(1, 2, 1)
plt.plot(x, y)

# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the second subplot in a 1x2 grid (1 row, 2 columns), position 2


plt.subplot(1, 2, 2)
plt.plot(x, y)

# Display the plots


plt.show()

The subplot() Function The subplot() function takes three arguments that describes the layout of the
figure.

The layout is organized in rows and columns, which are represented by the first and second argument.

The third argument represents the index of the current plot.

plt.subplot(1, 2, 1)

#the figure has 1 row, 2 columns, and this plot is the first plot.

plt.subplot(1, 2, 2)

#the figure has 1 row, 2 columns, and this plot is the second plot. So, if we want a figure with 2 rows an
1 column (meaning that the two plots will be displayed on top of each other instead of side-by-side),
we can write the syntax like this:

In [32]: # Example
# Draw 2 plots on top of each other:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the first subplot in a 2x1 grid (2 rows, 1 column), position 1


plt.subplot(2, 1, 1)
plt.plot(x, y)

# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the second subplot in a 2x1 grid (2 rows, 1 column), position 2


plt.subplot(2, 1, 2)
plt.plot(x, y)

# Display the plots


plt.show()

In [33]: # Example
# Draw 6 plots:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points for the first plot


x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the first subplot in a 2x3 grid (2 rows, 3 columns), position 1


plt.subplot(2, 3, 1)
plt.plot(x, y)

# Define x- and y-axis points for the second plot


x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the second subplot in a 2x3 grid, position 2


plt.subplot(2, 3, 2)
plt.plot(x, y)

# Define x- and y-axis points for the third plot


x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the third subplot in a 2x3 grid, position 3


plt.subplot(2, 3, 3)
plt.plot(x, y)

# Define x- and y-axis points for the fourth plot


x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the fourth subplot in a 2x3 grid, position 4


plt.subplot(2, 3, 4)
plt.plot(x, y)

# Define x- and y-axis points for the fifth plot


x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the fifth subplot in a 2x3 grid, position 5


plt.subplot(2, 3, 5)
plt.plot(x, y)

# Define x- and y-axis points for the sixth plot


x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the sixth subplot in a 2x3 grid, position 6


plt.subplot(2, 3, 6)
plt.plot(x, y)

# Display the plots


plt.show()
Title You can add a title to each plot with the title() function:

In [34]:
# Example
# 2 plots, with titles:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the first subplot in a 1x2 grid (1 row, 2 columns), position 1


plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("SALES") # Add a title to the first plot

# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the second subplot in a 1x2 grid, position 2


plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.title("INCOME") # Add a title to the second plot

# Display the plots


plt.show()
Super Title You can add a title to the entire figure with the suptitle() function:

In [35]:
# Example
# Add a title for the entire figure:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

# Create the first subplot in a 1x2 grid (1 row, 2 columns), position 1


plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("SALES") # Add a title to the first plot

# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

# Create the second subplot in a 1x2 grid, position 2


plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.title("INCOME") # Add a title to the second plot

# Add a title for the entire figure


plt.suptitle("MY SHOP")
# Display the plots
plt.show()

Matplotlib Scatter
Creating Scatter Plots With Pyplot, you can use the scatter() function to draw a scatter plot.

The scatter() function plots one dot for each observation. It needs two arrays of the same length, one
for the values of the x-axis, and one for values on the y-axis:

In [36]:
# Example
# A simple scatter plot:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis points using numpy array


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])

# Define y-axis points using numpy array


y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])

# Create a scatter plot with the x- and y-axis points


plt.scatter(x, y)

# Display the plot


plt.show()
The observation in the example above is the result of 13 cars passing by.

The X-axis shows how old the car is.

The Y-axis shows the speed of the car when it passes.

Are there any relationships between the observations?

It seems that the newer the car, the faster it drives, but that could be a coincidence, after all we only
registered 13 cars.

Compare Plots In the example above, there seems to be a relationship between speed and age, but
what if we plot the observations from another day as well? Will the scatter plot tell us something else?

In [37]:
# Example
# Draw two plots on the same figure:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Day one, the age and speed of 13 cars:


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y) # Create a scatter plot for day one

# Day two, the age and speed of 15 cars:


x = np.array([2, 2, 8, 1, 15, 8, 12, 9, 7, 3, 11, 4, 7, 14, 12])
y = np.array([100, 105, 84, 105, 90, 99, 90, 95, 94, 100, 79, 112, 91, 80,
plt.scatter(x, y) # Create a scatter plot for day two

# Display the plots


plt.show()
Note: The two plots are plotted with two different colors, by default blue and orange, you will learn how
to change colors later in this chapter.

By comparing the two plots, I think it is safe to say that they both gives us the same conclusion: the
newer the car, the faster it drives.

Colors You can set your own color for each scatter plot with the color or the c argument:

In [38]: # Example
# Set your own color of the markers:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points for the first scatter plot


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y, color='hotpink') # Create a scatter plot with hotpink ma

# Define x- and y-axis points for the second scatter plot


x = np.array([2, 2, 8, 1, 15, 8, 12, 9, 7, 3, 11, 4, 7, 14, 12])
y = np.array([100, 105, 84, 105, 90, 99, 90, 95, 94, 100, 79, 112, 91, 80,
plt.scatter(x, y, color='#88c999') # Create a scatter plot with custom gre

# Display the plots


plt.show()
Color Each Dot You can even set a specific color for each dot by using an array of colors as value for
the c argument:

Note: You cannot use the color argument for this, only the c argument.

In [39]: # Example
# Set your own color of the markers:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points using numpy arrays


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])

# Define an array of colors for each point


colors = np.array(["red", "green", "blue", "yellow", "pink", "black", "oran

# Create a scatter plot with custom colors for each marker


plt.scatter(x, y, c=colors)

# Display the plot


plt.show()
ColorMap The Matplotlib module has a number of available colormaps.

A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.

This colormap is called 'viridis' and as you can see it ranges from 0, which is a purple color, up to 100,
which is a yellow color.

How to Use the ColorMap You can specify the colormap with the keyword argument cmap with the
value of the colormap, in this case 'viridis' which is one of the built-in colormaps available in Matplotlib.

In addition you have to create an array with values (from 0 to 100), one value for each point in the
scatter plot:

In [40]: # Example
# Create a color array, and specify a colormap in the scatter plot:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points using numpy arrays


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])

# Define an array of color values


colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

# Create a scatter plot with a colormap


plt.scatter(x, y, c=colors, cmap='viridis')

# Display the plot


plt.show()
You can include the colormap in the drawing by including the plt.colorbar() statement:

In [41]:
# Example
# Include the actual colormap:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points using numpy arrays


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])

# Define an array of color values


colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

# Create a scatter plot with a colormap


plt.scatter(x, y, c=colors, cmap='viridis')

# Include the actual colormap


plt.colorbar()

# Display the plot


plt.show()
Name Reverse Accent :Accent_r / Blues :Blues_r / BrBG :BrBG_r / BuGn :BuGn_r / BuPu :BuPu_r /
CMRmap :CMRmap_r / Dark2 :Dark2_r / GnBu :GnBu_r / Greens :Greens_r / Greys :Greys_r / OrRd
:OrRd_r / Oranges :Oranges_r / PRGn :PRGn_r / Paired :Paired_r / Pastel1 :Pastel1_r / Pastel2
:Pastel2_r / PiYG :PiYG_r / PuBu :PuBu_r / PuBuGn :PuBuGn_r / PuOr :PuOr_r / PuRd :PuRd_r / Purples
:Purples_r / RdBu :RdBu_r / RdGy :RdGy_r / RdPu :RdPu_r / RdYlBu :RdYlBu_r / RdYlGn :RdYlGn_r / Reds
:Reds_r / Set1 :Set1_r / Set2 :Set2_r / Set3 :Set3_r / Spectral :Spectral_r / Wistia :Wistia_r / YlGn :YlGn_r
/ YlGnBu :YlGnBu_r / YlOrBr :YlOrBr_r / YlOrRd :YlOrRd_r / afmhot :afmhot_r / autumn :autumn_r /
binary :binary_r / bone :bone_r / brg :brg_r / bwr :bwr_r / cividis :cividis_r / cool :cool_r / coolwarm
:coolwarm_r / copper :copper_r / cubehelix :cubehelix_r /
flag :flag_r / gist_earth :gist_earth_r / gist_gray :gist_gray_r / gist_heat :gist_heat_r / gist_ncar
:gist_ncar_r / gist_rainbow :gist_rainbow_r / gist_stern :gist_stern_r / gist_yarg :gist_yarg_r / gnuplot
:gnuplot_r / gnuplot2 :gnuplot2_r / gray :gray_r / hot :hot_r / hsv :hsv_r / inferno :inferno_r / jet :jet_r /
magma :magma_r / nipy_spectral :nipy_spectral_r / ocean :ocean_r / pink :pink_r / plasma :plasma_r /
prism :prism_r / rainbow :rainbow_r / seismic :seismic_r / spring :spring_r / summer :summer_r / tab10
:tab10_r / tab20 :tab20_r / tab20b :tab20b_r / tab20c :tab20c_r / terrain :terrain_r / twilight :twilight_r /
twilight_shifted :twilight_shifted_r / viridis :viridis_r / winter :winter_r

Size You can change the size of the dots with the s argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

In [42]: #Example
#Set your own size for the markers:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes)

plt.show()
Alpha You can adjust the transparency of the dots with the alpha argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

In [43]: # Example
# Set your own size for the markers:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x- and y-axis points using numpy arrays


x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])

# Define an array of sizes for each marker


sizes = np.array([20, 50, 100, 200, 500, 1000, 60, 90, 10, 300, 600, 800, 7

# Create a scatter plot with custom marker sizes and set the transparency
plt.scatter(x, y, s=sizes, alpha=0.5) # 'alpha' sets the transparency leve

# Display the plot


plt.show()
Combine Color Size and Alpha You can combine a colormap with different sizes of the dots. This is
best visualized if the dots are transparent:

In [44]:
# Example
# Create random arrays with 100 values for x-points, y-points, colors, and

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Create random arrays with 100 values for x-points and y-points
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))

# Create random arrays with 100 values for colors and sizes
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))

# Create a scatter plot with custom colors, sizes, and transparency


plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')

# Include the actual colormap


plt.colorbar()

# Display the plot


plt.show()
Matplotlib Bars
Creating Bars With Pyplot, you can use the bar() function to draw bar graphs:

In [45]:
# Example
# Draw 4 bars:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a bar plot with the x- and y-axis values


plt.bar(x, y)

# Display the plot


plt.show()
The bar() function takes arguments that describes the layout of the bars.

The categories and their values represented by the first and second argument as arrays.

In [46]: # Example
import matplotlib.pyplot as plt # Import the matplotlib library for plotti
import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values


x = ["APPLES", "BANANAS"]
y = [400, 350]

# Create a bar plot with the x- and y-axis values


plt.bar(x, y)

# Display the plot


plt.show()
Horizontal Bars If you want the bars to be displayed horizontally instead of vertically, use the barh()
function:

In [7]:
#Example
#Draw 4 horizontal bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y)
plt.show()
Bar Color The bar() and barh() take the keyword argument color to set the color of the bars:

In [47]:
# Example
# Draw 4 red bars:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="red")

# Display the plot


plt.show()
Color Names You can use any of the 140 supported color names.

In [48]:
# Example
# Draw 4 "hot pink" bars:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="hotpink")

# Display the plot


plt.show()
Color Hex Or you can use Hexadecimal color values:

In [49]:
# Example
# Draw 4 bars with a beautiful green color:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="#4CAF50")

# Display the plot


plt.show()
Bar Width The bar() takes the keyword argument width to set the width of the bars:

In [50]:
# Example
# Draw 4 very thin bars:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a bar plot with the x- and y-axis values and set the bar width to
plt.bar(x, y, width=0.1)

# Display the plot


plt.show()
The default width value is 0.8

Note: For horizontal bars, use height instead of width.

Bar Height The barh() takes the keyword argument height to set the height of the bars:

In [51]: # Example
# Draw 4 very thin bars:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define x-axis labels and y-axis values using numpy arrays


x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

# Create a horizontal bar plot with the x- and y-axis values and set the ba
plt.barh(x, y, height=0.1)

# Display the plot


plt.show()
The default height value is 0.8

Matplotlib Histograms
Histogram A histogram is a graph showing frequency distributions.

It is a graph showing the number of observations within each given interval.

Example: Say you ask for the height of 250 people, you might end up with a histogram like this:

Create Histogram In Matplotlib, we use the hist() function to create histograms.

The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.

For simplicity we use NumPy to randomly generate an array with 250 values, where the values will
concentrate around 170, and the standard deviation is 10

In [52]:
# Example
# A Normal Data Distribution by NumPy:

import numpy as np # Import the numpy library for numerical operations

# Generate a normal distribution with mean 170, standard deviation 10, and
x = np.random.normal(170, 10, 250)

# Print the generated values


print(x)

[173.90517225 176.56302481 166.10380539 169.46281696 155.94147336


170.90772868 172.87249029 181.93773509 167.6875096 177.68686169
166.23539 160.68058286 163.39440259 158.83212643 174.24909013
167.52910959 162.83900541 153.44667988 169.71211155 163.69378831
159.94331034 160.4613887 176.3232374 151.71213499 171.69277612
168.27964905 166.06660588 179.06903963 190.76402842 178.68053139
180.75213322 179.78502821 165.29461432 162.57507706 163.10359339
161.4202265 155.93132447 172.19965658 163.11303101 156.30409266
167.07010307 179.34450594 160.73602327 162.60510236 174.73789059
190.59701648 154.99303658 179.18037007 161.91255407 173.41907072
152.79232288 163.63040927 172.33822096 157.07524134 186.31612479
178.65169605 180.56298729 155.37956407 172.74182084 168.53795836
172.74965454 186.37792154 185.07952369 171.34306387 156.31086273
154.70966937 173.72690297 156.27012071 159.62119078 165.42286603
177.60643301 156.80011682 168.26261025 186.05601476 171.30307371
170.31952336 181.82589494 165.47080371 158.4545405 176.29226294
170.68418047 172.04601968 163.27785594 154.79227412 164.28344403
174.10895747 179.01844158 148.93017971 183.93024325 175.80842634
163.11339855 188.67572235 179.09541378 171.7128505 165.63511704
180.00745634 159.31587122 167.09230381 158.05616228 171.64403401
157.98908624 161.5387273 181.11890988 159.68467785 155.09677997
176.40570662 170.70625981 168.92815821 173.72297298 164.15190919
163.93206833 173.45889866 162.29403921 168.64123514 163.31024539
169.17781657 172.21848065 171.70640827 163.83387939 168.7296311
181.44843472 163.54871165 172.44556056 190.04829182 158.71143663
178.48702043 159.43319379 177.39349171 163.1922007 175.7209545
172.9860008 170.27224094 183.20988982 149.12355175 172.16994543
180.56605706 188.16586798 163.33464765 187.18354412 168.18079444
164.86388939 173.45605388 173.48827897 176.89392026 173.42691431
168.74931044 154.7006584 166.29141933 145.53533948 166.23537714
167.22141591 177.42300681 175.43821704 158.96296204 173.76901043
166.78639496 154.64113269 163.97802852 162.47308093 144.76196953
184.32772328 179.32188476 172.34836038 166.89977219 148.46687865
176.21882246 165.54989788 174.72084883 160.25878079 161.36079256
151.26174904 152.58443976 152.07650282 150.50381271 189.35408193
171.92834351 172.27726511 162.51250687 192.45416071 188.12971112
163.81901944 170.09530293 165.19207832 171.99761848 164.1894104
177.28456592 158.65532273 165.62540809 155.42294105 154.90781163
172.17124925 149.60700281 158.79649168 174.21250798 165.5031961
175.82970499 164.51419795 162.44818376 176.50700146 178.75951312
172.16232838 173.28969845 153.39838854 182.55692684 169.33053562
164.39514041 164.59352131 178.91926849 146.93537663 188.73437607
163.83415551 163.77171799 197.29335613 171.86507926 192.29260038
165.07219307 169.22916113 139.33245877 163.52596047 182.49232577
171.24786559 156.37485637 183.84029013 187.23062395 170.46879692
154.82826338 159.79836338 166.99201532 164.32923388 171.12760257
171.7103934 183.69945751 171.45470623 150.11700582 147.81256998
166.18844315 166.61487641 161.86369495 165.94160507 152.53439097
169.97607755 183.34196822 156.17368592 157.03981677 164.36238092
164.58867805 172.59193382 169.88022493 172.86015108 182.16356891]

The hist() function will read the array and produce a histogram:

In [53]:
# Example
# A simple histogram:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Generate a normal distribution with mean 170, standard deviation 10, and
x = np.random.normal(170, 10, 250)

# Create a histogram of the generated values


plt.hist(x)

# Display the plot


plt.show()
Matplotlib Pie Charts
Creating Pie Charts With Pyplot, you can use the pie() function to draw pie charts:

In [54]:
# Example
# A simple pie chart:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Create a pie chart with the defined values


plt.pie(y)

# Display the plot


plt.show()
As you can see the pie chart draws one piece (called a wedge) for each value in the array (in this case
[35, 25, 25, 15]).

By default the plotting of the first wedge starts from the x-axis and moves counterclockwise:

Note: The size of each wedge is determined by comparing the value with all the other values, by using
this formula:

The value divided by the sum of all values: x/sum(x)

Labels Add labels to the pie chart with the labels parameter.

The labels parameter must be an array with one label for each wedge:

In [55]: # Example
# A simple pie chart:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Create a pie chart with the defined values and labels


plt.pie(y, labels=mylabels)

# Display the plot


plt.show()
Start Angle As mentioned the default start angle is at the x-axis, but you can change the start angle by
specifying a startangle parameter.

The startangle parameter is defined with an angle in degrees, default angle is 0:

In [56]: # Example
# Start the first wedge at 90 degrees:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Create a pie chart with the defined values and labels, and start the firs
plt.pie(y, labels=mylabels, startangle=90)

# Display the plot


plt.show()
Explode Maybe you want one of the wedges to stand out? The explode parameter allows you to do
that.

The explode parameter, if specified, and not None, must be an array with one value for each wedge.

Each value represents how far from the center each wedge is displayed:

In [57]:
# Example
# Pull the "Apples" wedge 0.2 from the center of the pie:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Define the explode values to pull the "Apples" wedge 0.2 from the center
myexplode = [0.2, 0, 0, 0]

# Create a pie chart with the defined values, labels, and explode values
plt.pie(y, labels=mylabels, explode=myexplode)

# Display the plot


plt.show()
Shadow Add a shadow to the pie chart by setting the shadows parameter to True:

In [58]:
# Example
# Add a shadow:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Define the explode values to pull the "Apples" wedge 0.2 from the center
myexplode = [0.2, 0, 0, 0]

# Create a pie chart with the defined values, labels, explode values, and a
plt.pie(y, labels=mylabels, explode=myexplode, shadow=True)

# Display the plot


plt.show()
Colors You can set the color of each wedge with the colors parameter.

The colors parameter, if specified, must be an array with one value for each wedge:

In [59]: # Example
# Specify a new color for each wedge:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Define the colors for each wedge of the pie chart


mycolors = ["black", "hotpink", "b", "#4CAF50"]

# Create a pie chart with the defined values, labels, and colors
plt.pie(y, labels=mylabels, colors=mycolors)

# Display the plot


plt.show()
You can use Hexadecimal color values, any of the 140 supported color names, or one of these
shortcuts:

'r' - Red / 'g' - Green / 'b' - Blue / 'c' - Cyan / 'm' - Magenta / 'y' - Yellow / 'k' - Black / 'w' - White

Legend To add a list of explanation for each wedge, use the legend() function:

In [60]: # Example
# Add a legend:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Create a pie chart with the defined values and labels


plt.pie(y, labels=mylabels)

# Add a legend to the plot


plt.legend()

# Display the plot


plt.show()
Legend With Header To add a header to the legend, add the title parameter to the legend function.

In [61]:
# Example
# Add a legend with a header:

import matplotlib.pyplot as plt # Import the matplotlib library for plotti


import numpy as np # Import the numpy library for numerical operations

# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])

# Define the labels for each slice of the pie chart


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

# Create a pie chart with the defined values and labels


plt.pie(y, labels=mylabels)

# Add a legend with a header to the plot


plt.legend(title="Four Fruits:")

# Display the plot


plt.show()
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.

In [26]:
# Example of Three-dimensional Plotting using Matplotlib
# We will first start with plotting the 3D axis using the Matplotlib librar
# For plotting the 3D axis we just have to change the projection parameter

import numpy as np # Import the numpy library for numerical operations


import matplotlib.pyplot as plt # Import the matplotlib library for plotti

# Create a new figure


fig = plt.figure()

# Add a 3D axis to the figure


ax = plt.axes(projection='3d')

# Display the plot


plt.show()
3-Dimensional Line Graph Using Matplotlib For plotting the 3-Dimensional line graph we will use the
mplot3d function from the mpl_toolkits library. For plotting lines in 3D we will have to initialize three
variable points for the line equation. In our case, we will define three variables as x, y, and z.

In [62]:
# Importing mplot3d toolkits, numpy, and matplotlib
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Create a new figure


fig = plt.figure()

# Syntax for 3-D projection


ax = plt.axes(projection='3d')

# Defining all 3 axes


z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)

# Plotting
ax.plot3D(x, y, z, 'green')
ax.set_title('3D line plot geeks for geeks')

# Display the plot


plt.show()
3-Dimensional Scattered Graph Using Matplotlib To plot the same graph using scatter points we will
use the scatter() function from matplotlib. It will plot the same line equation using distinct points.

In [63]:
# Importing mplot3d toolkits, numpy, and matplotlib
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Create a new figure


fig = plt.figure()

# Syntax for 3-D projection


ax = plt.axes(projection='3d')

# Defining axes
z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)
c = x + y

# Plotting a 3D scatter plot


ax.scatter(x, y, z, c=c)

# Set the title of the plot


ax.set_title('3D Scatter plot geeks for geeks')

# Display the plot


plt.show()
Surface Graphs using Matplotlib library Surface graphs and Wireframes graph work on gridded data.
They take the grid value and plot it on a three-dimensional surface. We will use the plot_surface()
function to plot the surface plot.

In [64]:
# Importing libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Defining surface and axes


x = np.outer(np.linspace(-2, 2, 10), np.ones(10))
y = x.copy().T
z = np.cos(x ** 2 + y ** 3)

# Create a new figure


fig = plt.figure()

# Syntax for 3-D plotting


ax = plt.axes(projection='3d')

# Plotting the surface


ax.plot_surface(x, y, z, cmap='viridis', edgecolor='green')

# Set the title of the plot


ax.set_title('Surface plot geeks for geeks')

# Display the plot


plt.show()
Wireframes graph using Matplotlib library For plotting the wireframes graph we will use the
plot_wireframe() function from the matplotlib library.

In [65]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Function for z axis


def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

# x and y axis
x = np.linspace(-1, 5, 10)
y = np.linspace(-1, 5, 10)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

# Create a new figure


fig = plt.figure()

# Add a 3D axis to the figure


ax = plt.axes(projection='3d')

# Plotting the wireframe


ax.plot_wireframe(X, Y, Z, color='green')

# Set the title of the plot


ax.set_title('Wireframe geeks for geeks')
# Display the plot
plt.show()

Contour Graphs using Matplotlib library The contour graph takes all the input data in two-dimensional
regular grids, and the Z data is evaluated at every point. We use the ax.contour3D function to plot a
contour graph. Contour plots are an excellent way to visualize optimization plots.

In [66]: import numpy as np


import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Define the function for z axis


def function(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

# Define the x and y axis values


x = np.linspace(-10, 10, 40)
y = np.linspace(-10, 10, 40)

# Create a meshgrid for x and y


X, Y = np.meshgrid(x, y)
Z = function(X, Y)

# Create a new figure with specified size


fig = plt.figure(figsize=(10, 8))

# Add a 3D axis to the figure


ax = plt.axes(projection='3d')

# Plot the surface with a colormap and transparency


ax.plot_surface(X, Y, Z, cmap='cool', alpha=0.8)
# Set the title of the plot
ax.set_title('3D Contour Plot of function(x, y) = sin(sqrt(x^2 + y^2))', fo

# Set the labels for the axes


ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.set_zlabel('z', fontsize=12)

# Display the plot


plt.show()

Plotting Surface Triangulations In Python The above graph is sometimes overly restricted and
inconvenient. So by this method, we use a set of random draws. The function ax.plot_trisurf is used to
draw this graph. It is not that clear but more flexible.

In [67]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.tri import Triangulation
# Define the function for z axis
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

# Define the x and y axis values


x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

# Create a triangulation object


tri = Triangulation(X.ravel(), Y.ravel())

# Create a new figure with specified size


fig = plt.figure(figsize=(10, 8))

# Add a 3D axis to the figure


ax = fig.add_subplot(111, projection='3d')

# Plot the surface triangulation with a colormap and transparency


ax.plot_trisurf(tri, Z.ravel(), cmap='cool', edgecolor='none', alpha=0.8)

# Set the title of the plot


ax.set_title('Surface Triangulation Plot of f(x, y) = sin(sqrt(x^2 + y^2))'

# Set the labels for the axes


ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.set_zlabel('z', fontsize=12)

# Display the plot


plt.show()
Plotting Möbius strip In Python Möbius strip also called the twisted cylinder, is a one-sided surface
without boundaries. To create the Möbius strip think about its parameterization, it’s a two-dimensional
strip, and we need two intrinsic dimensions. Its angle range from 0 to 2 pie around the loop and its
width ranges from -1 to 1.

In [68]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Define the parameters of the Möbius strip


R = 2

# Define the Möbius strip surface


u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(-1, 1, 100)
u, v = np.meshgrid(u, v)
x = (R + v*np.cos(u/2)) * np.cos(u)
y = (R + v*np.cos(u/2)) * np.sin(u)
z = v * np.sin(u/2)
# Create the plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the Möbius strip surface


ax.plot_surface(x, y, z, alpha=0.5)

# Set plot properties


ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Möbius Strip')

# Set the limits of the plot


ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])
ax.set_zlim([-3, 3])

# Show the plot


plt.show()

You might also like