Matplotlib
Matplotlib
What is Matplotlib? Matplotlib is a low level graph plotting library in python that serves as a
visualization utility.
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:
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
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
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):
In [5]:
# Example
# Draw two points in the diagram, one at position (1, 3) and one in positio
In [6]:
# Example
# Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) an
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:
In [8]:
# Example
# Mark each point with a circle:
'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:
# Plot the y-axis points with circle markers, red color, and dotted line
plt.plot(ypoints, 'o:r')
In [10]:
# Example
# Set the size of the markers to 20:
# Plot the y-axis points with circle markers and set marker size to 20
plt.plot(ypoints, marker='o', ms=20)
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:
# Plot the y-axis points with circle markers, set marker size to 20, and ed
plt.plot(ypoints, marker='o', ms=20, mec='r')
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:
# 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:
# 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')
In [14]:
# Example
# Mark each point with a beautiful green color:
# 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')
In [15]:
# Example
# Use a dotted line:
In [16]: # Example
# Use a dashed line:
In [17]:
# Example
# Shorter syntax for line style:
# Plot the y-axis points with a dotted line style using shorter syntax
plt.plot(ypoints, ls=':') # 'ls' is the shorter syntax for 'linestyle'
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:
# Plot the y-axis points with the line color set to red
plt.plot(ypoints, color='r') # 'color' parameter sets the line color
# 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'
# Plot the y-axis points with the line color set to "hotpink"
plt.plot(ypoints, c='hotpink') # 'c' is the shorter syntax for 'color'
In [21]: # Example
# Plot with a 20.5pt wide line:
# 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
In [22]:
# Example
# Draw two lines by specifying a plt.plot() function for each line:
# 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])
(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).)
In [23]:
# Example
# Draw two lines by specifying the x- and y-point values for both lines:
# 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)
In [24]:
# Example
# Add labels to the x- and y-axis:
In [25]:
# Example
# Add a plot title and labels for the x- and y-axis:
In [26]:
# Example
# Set font properties for the title and labels:
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:
In [28]:
# Example
# Add grid lines to the plot:
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:
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.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:
# Add grid lines with specified properties: color, linestyle, and linewidth
plt.grid(color='green', linestyle='--', linewidth=0.5)
Matplotlib Subplot
Display Multiple Plots With the subplot() function you can draw multiple plots in one figure:
In [31]:
# Example
# Draw 2 plots:
# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
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.
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:
# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
In [33]: # Example
# Draw 6 plots:
In [34]:
# Example
# 2 plots, with titles:
# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
In [35]:
# Example
# Add a title for the entire figure:
# Plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
# Plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
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:
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:
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:
Note: You cannot use the color argument for this, only the c argument.
In [39]: # Example
# Set your own color of the markers:
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:
In [41]:
# Example
# Include the actual colormap:
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:
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:
# 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
In [44]:
# Example
# Create random arrays with 100 values for x-points, y-points, colors, and
# 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))
In [45]:
# Example
# Draw 4 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
In [7]:
#Example
#Draw 4 horizontal bars:
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:
# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="red")
In [48]:
# Example
# Draw 4 "hot pink" bars:
# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="hotpink")
In [49]:
# Example
# Draw 4 bars with a beautiful green color:
# Create a bar plot with the x- and y-axis values and set the bar color to
plt.bar(x, y, color="#4CAF50")
In [50]:
# Example
# Draw 4 very thin bars:
# Create a bar plot with the x- and y-axis values and set the bar width to
plt.bar(x, y, width=0.1)
Bar Height The barh() takes the keyword argument height to set the height of the bars:
In [51]: # Example
# Draw 4 very thin bars:
# Create a horizontal bar plot with the x- and y-axis values and set the ba
plt.barh(x, y, height=0.1)
Matplotlib Histograms
Histogram A histogram is a graph showing frequency distributions.
Example: Say you ask for the height of 250 people, you might end up with a histogram like this:
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:
# Generate a normal distribution with mean 170, standard deviation 10, and
x = np.random.normal(170, 10, 250)
The hist() function will read the array and produce a histogram:
In [53]:
# Example
# A simple histogram:
# Generate a normal distribution with mean 170, standard deviation 10, and
x = np.random.normal(170, 10, 250)
In [54]:
# Example
# A simple pie chart:
# Define the values for the pie chart using a numpy array
y = np.array([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:
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:
# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])
In [56]: # Example
# Start the first wedge at 90 degrees:
# 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 and labels, and start the firs
plt.pie(y, labels=mylabels, startangle=90)
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:
# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])
# 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)
In [58]:
# Example
# Add a shadow:
# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])
# 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)
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:
# 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, labels, and colors
plt.pie(y, labels=mylabels, colors=mycolors)
'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:
# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])
In [61]:
# Example
# Add a legend with a header:
# Define the values for the pie chart using a numpy array
y = np.array([35, 25, 25, 15])
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
In [62]:
# Importing mplot3d toolkits, numpy, and matplotlib
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
# Plotting
ax.plot3D(x, y, z, 'green')
ax.set_title('3D line plot geeks for geeks')
In [63]:
# Importing mplot3d toolkits, numpy, and matplotlib
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
# Defining axes
z = np.linspace(0, 1, 100)
x = z * np.sin(25 * z)
y = z * np.cos(25 * z)
c = x + y
In [64]:
# Importing libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
In [65]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
# 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)
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.
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))
In [68]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D