0% found this document useful (0 votes)
2 views15 pages

Advanced Matplotlib Visualization Techniques

Uploaded by

sujanpavan57
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Advanced Matplotlib Visualization Techniques

Uploaded by

sujanpavan57
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Specialized & Advanced Visualization with Matplotlib

Synthesized from Healy and McKinney

Pratheek Rai N

October 13, 2025

Pratheek Rai N Matplotlib Visualization October 13, 2025 1 / 15


Outline

1 Specialized Visualization Tools

2 Advanced Visualization Tools

Pratheek Rai N Matplotlib Visualization October 13, 2025 2 / 15


Topic 1.1: Contour Plots
Introduction Mathematical Foundation

A contour plot is a 2D representation of a 3D surface, similar to a


topographical map. It uses lines (contours) to connect points of equal
value.
Mathematical Foundation
A contour plot visualizes a function of two variables, z = f (x, y ). Each
contour line represents a level set of the function, which is the set of all
points (x, y ) where f (x, y ) is a constant, c.

f (x, y ) = c

Matplotlib interpolates between points on a data grid to find these paths


of constant value.

Pratheek Rai N Matplotlib Visualization October 13, 2025 3 / 15


Example 1: Filled Contour Plot (‘contourf‘)

1 import matplotlib . pyplot as plt


2 import numpy as np Explanation
3 [Link](x,y): Creates a 2D
4 x = np . linspace ( - np . pi , np . pi ,
100)
coordinate grid from 1D arrays.
5 y = np . linspace ( - np . pi , np . pi , [Link](...): Draws and
100)
6 X , Y = np . meshgrid (x , y ) fills the contours. levels=15 slices
7 Z = np . sin ( X ) + np . cos ( Y ) the Z-axis into 15 colored regions.
8
9 fig , ax = plt . subplots () [Link](...): Adds the
0 contourf = ax . contourf (X , Y , Z , essential color scale legend.
1 levels =15 ,
2 cmap = ’ viridis ’)
3 fig . colorbar ( contourf , ax = ax ,
4 label = ’Z value ’)
5 ax . set_title ( ’ Filled Contour ’)
6 plt . show ()
7

Pratheek Rai N Matplotlib Visualization October 13, 2025 4 / 15


Example 2: Line Contour Plot with Labels (‘clabel‘)

1 import matplotlib . pyplot as plt


2 import numpy as np Explanation
3 X , Y = np . meshgrid ( np . linspace ( - [Link](...): Draws only the
np . pi , np . pi , 100) ,
4 np . linspace ( -
lines for each level, without the
np . pi , np . pi , 100) ) color fill.
5 Z = np . sin ( X ) + np . cos ( Y )
6
[Link](contour, ...): Adds
7 fig , ax = plt . subplots () value labels to the contour lines.
8 # Create a line - only plot
9 contour = ax . contour (X , Y , Z , inline=True: A key feature that
0 levels =10 , carves out a small piece of the line
1 colors = ’ black ’) so the label fits inside, improving
2 # Add labels directly on lines
3 ax . clabel ( contour , inline = True , readability.
4 fontsize =8 , fmt = ’ %1.2 f ’
)
5 ax . set_title ( ’ Line Contour Plot ’)
6 plt . show ()
7

Pratheek Rai N Matplotlib Visualization October 13, 2025 5 / 15


Example 3: Combined Contour Plots

1 X , Y = np . meshgrid ( np . linspace
( -5 ,5 ,100) , Explanation
2 np . linspace Layering: Multiple plotting
( -5 ,5 ,100) )
3 Z = X **2 - Y **2 # Saddle shape
functions are called on the same
4 fig , ax = plt . subplots () ‘Axes‘ to layer them.
5
6 # 1. Filled contour plot cmap=’RdBu’: A diverging
7 contourf = ax . contourf (X , Y , Z , colormap, ideal for data with a
8 levels =20 , cmap = ’ meaningful center point (like zero).
RdBu ’)
It uses different colors for positive
9
0 # 2. Overlay line contour and negative values.
1 contour = ax . contour (X , Y , Z ,
2 levels =20 ,
3 colors = ’ black ’ ,
4 linewidths =0.5)
5
6 fig . colorbar ( contourf , ax = ax )
7 plt . show ()
8

Pratheek Rai N Matplotlib Visualization October 13, 2025 6 / 15


Example 4: Highlighting a Specific Region

1 X , Y = np . meshgrid ( np . linspace
( -5 ,5 ,100) , Explanation
2 np . linspace Visual Hierarchy: We create a
( -5 ,5 ,100) )
3 Z = np . sin ( np . sqrt ( X **2 + Y **2) )
muted background, then plot a
4 fig , ax = plt . subplots () second ‘contourf‘ for a specific list
5 of ‘levels‘ with a vibrant colormap.
6 # 1. Muted background This technique powerfully directs
7 ax . contourf (X , Y , Z , levels =20 ,
8 cmap = ’ gray_r ’ , alpha
the viewer’s attention.
=0.8)
9
0 # 2. Highlight peak regions
1 h i g h l i g h t _ l e v el s = [0.8 , 0.9 ,
1.0]
2 ax . contourf (X , Y , Z ,
3 levels = highlight_levels ,
4 cmap = ’ autumn ’)
5 ax . set_title ( " Highlighting Peaks "
)
6 plt . show ()
7

Pratheek Rai N Matplotlib Visualization October 13, 2025 7 / 15


Contour Plot Exercises

1 Modify the Function: Change the function in Example 1 to


Z = X 2 − Y 2 . How does the shape of the contours change?
2 Change Colormap and Levels: Re-create the plot from Example 2
but use the ‘’magma’‘ colormap and only 5 levels.
3 Specific Levels: Instead of specifying the number of levels, plot only
the contours for Z = −1, 0, 1 for the function Z = sin(X ) + cos(Y ).
4 Combine with a Scatter Plot: Generate 50 random (x, y ) points.
Calculate their Z values (using the wave function from Example 4)
and overlay them as a scatter plot.

Pratheek Rai N Matplotlib Visualization October 13, 2025 8 / 15


Topic 2.1: Multi-Panel Plots
Introduction

Often, you need to compare different views of your data side-by-side.


Matplotlib provides powerful tools for creating complex layouts.

‘[Link]()‘ ‘GridSpec‘
The easiest way to create a regular Offers more flexibility for creating
grid of plots (e.g., 2x2, 1x3). It’s complex, non-uniform layouts where
fast and convenient. plots can span multiple rows or
columns.

Pratheek Rai N Matplotlib Visualization October 13, 2025 9 / 15


Example 1: Basic Grid with ‘[Link]‘

1 # Create a 2 x2 grid .
2 fig , axs = plt . subplots (2 , 2 , Explanation
3 figsize =(8 , 6) , fig, axs = ...: Returns the
4 c o n s t r a i n e d _ l a y o u t = True )
5
figure and a NumPy array (‘axs‘) of
6 # Access each axes object subplots.
7 axs [0 , 0]. plot (
8 np . random . randn (50) . cumsum () ) Indexing: Access subplots via array
9 axs [0 , 0]. set_title ( ’Top - Left ’) indexing, e.g., axs[0, 0].
0
1 axs [0 , 1]. hist ( constrained layout=True:
2 np . random . randn (500) ) Automatically adjusts spacing.
3 axs [0 , 1]. set_title ( ’ Top - Right ’)
4
5 axs [1 , 0]. scatter (
6 np . random . rand (50) ,
7 np . random . rand (50) )
8 axs [1 , 0]. set_title ( ’ Bottom - Left ’
)
9
0 axs [1 , 1]. bar ([ ’A ’ , ’B ’ , ’C ’] ,
1 [10 ,20 ,15])
2 axs [1 , 1]. set_title ( ’ Bottom - Right
’) Pratheek Rai N Matplotlib Visualization October 13, 2025 10 / 15
Example 2: Sharing Axes for Comparison

1 x = np . linspace (0 , 10 , 100)
2 y1 = x **2 Explanation
3 y2 = np . exp ( x /2) sharex=True: This argument links
4
5 # sharex = True links the x - axes
the x-axes. Zooming one plot will
6 fig , ( ax1 , ax2 ) = plt . subplots ( update the other.
7 2 , 1 , figsize =(6 , 6) ,
8 sharex = True ) Clarity: Matplotlib automatically
9 hides redundant tick labels on the
0 ax1 . plot (x , y1 , color = ’ navy ’) upper plot, reinforcing the shared
1 ax1 . set_ylabel ( ’ Squared ’)
scale and making the figure cleaner.
2
3 ax2 . plot (x , y2 , color = ’ maroon ’)
4 ax2 . set_ylabel ( ’ Exponential ’)
5 ax2 . set_xlabel ( ’ Input ( x ) ’)
6 plt . show ()
7

Pratheek Rai N Matplotlib Visualization October 13, 2025 11 / 15


Example 3: Complex Layouts with ‘GridSpec‘

1 import matplotlib . gridspec as gs


2 fig = plt . figure ( figsize =(10 , 6) , Explanation
3 constrained_layout = GridSpec(...): Creates a layout
True )
4 spec = gs . GridSpec (2 , 2 , figure =
manager object.
fig ) [Link] subplot(spec[...]):
5
6 # Spans both rows of first column Adds a subplot by passing a slice
7 ax1 = fig . add_subplot ( spec [: , 0]) of the ‘GridSpec‘ object.
8 ax1 . set_title ( ’ Main Plot ’)
9 spec[:, 0]: This slice selects all
0 # Top - right plot rows (‘:‘) in the first column (‘0‘),
1 ax2 = fig . add_subplot ( spec [0 , 1]) creating a tall axes.
2 ax2 . set_title ( ’Top - Right ’)
3
4 # Bottom - right plot
5 ax3 = fig . add_subplot ( spec [1 , 1])
6 ax3 . set_title ( ’ Bottom - Right ’)
7 plt . show ()
8

Pratheek Rai N Matplotlib Visualization October 13, 2025 12 / 15


Example 4: Inset Plots

1 x = np . linspace (0 , 10 , 500)
2 y = np . sin ( x ) + np . sin (3* x ) /3 Explanation
3 fig , ax_main = plt . subplots ( [Link] axes([...]): Creates
4 figsize =(8 , 5) )
5 ax_main . plot (x , y )
a new ‘Axes‘ object inside another.
6 ax_main . set_title ( ’ Main Plot ’) Position is relative to the parent.
7
8 // Inset : [L , B , W , H ] [Link] inset zoom(...):
9 ax_inset = ax_main . inset_axes ( A helper function that draws a
0 [0.6 , 0.6 , 0.35 , 0.35]) rectangle and connector lines to
1
show where the inset view comes
2 ax_inset . plot (x , y , color = ’ red ’)
3 ax_inset . set_xlim (1.5 , 3.5) from.
4 ax_inset . set_ylim (0.5 , 1.4)
5
6 ax_main . i n d i c a t e _ i n s e t _ z o o m (
7 ax_inset , edgecolor = " black " )
8 plt . show ()
9

Pratheek Rai N Matplotlib Visualization October 13, 2025 13 / 15


Multi-Panel Plot Exercises

1 2x2 Grid: Use ‘[Link]()‘ to create a 2x2 grid plotting: a) y = x,



b) y = x 2 , c) y = x 3 , and d) y = x.
2 Shared Axes: Re-create the 2x2 grid from Exercise 1, but use the
‘sharex=True‘ and ‘sharey=True‘ arguments. What happens to the
tick labels?
3 GridSpec T-shape: Use ‘GridSpec‘ to create a ”T” shaped layout:
one plot that spans the entire top row, and two plots in the bottom
row.
4 Marginal Histograms: Create a scatter plot in a main panel using
‘GridSpec‘. Add a histogram of the x-variable above it and a
histogram of the y-variable to its right.

Pratheek Rai N Matplotlib Visualization October 13, 2025 14 / 15


Thank You / Q&A

Pratheek Rai N Matplotlib Visualization October 13, 2025 15 / 15

You might also like