0% found this document useful (0 votes)
5 views29 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)
5 views29 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 15, 2025

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


Outline

1 Specialized Visualization Tools

2 Advanced Visualization Tools

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


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 15, 2025 3 / 29


Example 1: Filled Contour Plot (‘contourf‘) - Code

1 import matplotlib . pyplot as plt


2 import numpy as np
3
4 x = np . linspace ( - np . pi , np . pi , 100)
5 y = np . linspace ( - np . pi , np . pi , 100)
6 X , Y = np . meshgrid (x , y )
7 Z = np . sin ( X ) + np . cos ( Y )
8
9 fig , ax = plt . subplots ()
10 contourf = ax . contourf (X , Y , Z ,
11 levels =15 ,
12 cmap = ’ viridis ’)
13 fig . colorbar ( contourf , ax = ax ,
14 label = ’Z value ’)
15 ax . set_title ( ’ Filled Contour ’)
16 # Replace plt . show () with this line to save the figure :
17 # plt . savefig ( ’ fig_contourf . png ’, dpi =150 , bbox_inches = ’ tight ’)
18 plt . show ()
19

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


Example 1: Filled Contour Plot (‘contourf‘) - Explanation

fig_contourf.png

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


Example 1: Exercises

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


Z = X 2 − Y 2 . How does the shape of the contours change? Describe
the new pattern.
2 Change Colormap: Re-create the original plot but use the ‘’magma’‘
colormap instead of ‘’viridis’‘. Add a second contour plot on top that
only shows the line for the level Z = 0 in a bright color (e.g., ’white’).

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


Example 2: Line Contour Plot (‘clabel‘) - Code

1 import matplotlib . pyplot as plt


2 import numpy as np
3 X , Y = np . meshgrid ( np . linspace ( - np . pi , np . pi , 100) ,
4 np . linspace ( - np . pi , np . pi , 100) )
5 Z = np . sin ( X ) + np . cos ( Y )
6
7 fig , ax = plt . subplots ()
8 contour = ax . contour (X , Y , Z ,
9 levels =10 ,
10 colors = ’ black ’)
11 ax . clabel ( contour , inline = True ,
12 fontsize =8 , fmt = ’ %1.2 f ’)
13 ax . set_title ( ’ Line Contour Plot ’)
14 # Replace plt . show () with this line to save the figure :
15 # plt . savefig ( ’ fig_clabel . png ’, dpi =150 , bbox_inches = ’ tight ’)
16 plt . show ()
17

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


Example 2: Line Contour Plot (‘clabel‘) - Explanation

fig_clabel.png

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


Example 2: Exercises

1 Customize Labels: In the example, change the format string ‘fmt‘ to


show integers instead of decimals. Also, try setting ‘inline=False‘ and
observe the difference in label placement.
2 Specific Levels: Instead of specifying the number of levels, plot only
the contours for Z = −1, 0, 1. Label only the Z = 0 contour.

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


Example 3: Combined Contour Plots - Code

1 X , Y = np . meshgrid ( np . linspace ( -5 ,5 ,100) ,


2 np . linspace ( -5 ,5 ,100) )
3 Z = X **2 - Y **2 % Saddle shape
4 fig , ax = plt . subplots ()
5
6 contourf = ax . contourf (X , Y , Z ,
7 levels =20 , cmap = ’ RdBu ’)
8
9 contour = ax . contour (X , Y , Z ,
10 levels =20 ,
11 colors = ’ black ’ ,
12 linewidths =0.5)
13
14 fig . colorbar ( contourf , ax = ax )
15 # Replace plt . show () with this line to save the figure :
16 # plt . savefig ( ’ f i g _ c o m b i n e d _ c o n t o u r . png ’, dpi =150 , bbox_inches = ’
tight ’)
17 plt . show ()
18

Pratheek Rai N Matplotlib Visualization October 15, 2025 10 / 29


Example 3: Combined Contour Plots - Explanation

fig_combined_contour.png

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


Example 3: Exercises

1 Thicken Lines: Modify the example to make the overlaid contour


lines dashed and thicker. (Hint: look for a ‘linestyles‘ argument).
2 Different Levels: Create a plot where the ‘contourf‘ has 10 levels,
but the overlaid ‘contour‘ lines only show every second level (i.e., 5
lines).

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


Example 4: Highlighting a Region - Code

1 X , Y = np . meshgrid ( np . linspace ( -5 ,5 ,100) ,


2 np . linspace ( -5 ,5 ,100) )
3 Z = np . sin ( np . sqrt ( X **2 + Y **2) )
4 fig , ax = plt . subplots ()
5
6 ax . contourf (X , Y , Z , levels =20 ,
7 cmap = ’ gray_r ’ , alpha =0.8)
8
9 h i g h l i g h t _ l e v e ls = [0.8 , 0.9 , 1.0]
10 ax . contourf (X , Y , Z ,
11 levels = highlight_levels ,
12 cmap = ’ autumn ’)
13 ax . set_title ( " Highlighting Peaks " )
14 # Replace plt . show () with this line to save the figure :
15 # plt . savefig ( ’ fig_highlight . png ’, dpi =150 , bbox_inches = ’ tight ’)
16 plt . show ()
17

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


Example 4: Highlighting a Region - Explanation

fig_highlight.png

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


Example 4: Exercises

1 Highlight Valleys: Using the same function, modify the code to


highlight the ”valleys” (regions where Z < −0.8) using a cool
colormap like ‘’winter’‘.
2 Combine with Scatter: Generate 50 random (x, y ) points within the
plot’s range. Calculate their Z values using the wave function and
overlay them as a scatter plot. Color the scatter points based on their
Z value.

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


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 15, 2025 16 / 29


Example 1: Basic Grid (‘[Link]‘) - Code

1 fig , axs = plt . subplots (2 , 2 ,


2 figsize =(8 , 6) ,
3 c o n s t r a i n e d _ l a y o u t = True )
4
5 axs [0 , 0]. plot ( np . random . randn (50) . cumsum () )
6 axs [0 , 0]. set_title ( ’ Top - Left ’)
7
8 axs [0 , 1]. hist ( np . random . randn (500) )
9 axs [0 , 1]. set_title ( ’ Top - Right ’)
10
11 axs [1 , 0]. scatter ( np . random . rand (50) , np . random . rand (50) )
12 axs [1 , 0]. set_title ( ’ Bottom - Left ’)
13
14 axs [1 , 1]. bar ([ ’A ’ , ’B ’ , ’C ’] , [10 ,20 ,15])
15 axs [1 , 1]. set_title ( ’ Bottom - Right ’)
16 # Replace plt . show () with this line to save the figure :
17 # plt . savefig ( ’ f i g _ s u b pl o t s _ g r i d . png ’, dpi =150 , bbox_inches = ’ tight
’)
18 plt . show ()
19

Pratheek Rai N Matplotlib Visualization October 15, 2025 17 / 29


Example 1: Basic Grid (‘[Link]‘) - Explanation

fig_subplots_grid.png

Pratheek Rai N Matplotlib Visualization October 15, 2025 18 / 29


Example 1: Exercises

1 1x3 Grid: Use ‘[Link]()‘ to create a 1x3 grid (one row, three
columns). Plot a sine wave, a cosine wave, and a tangent wave in the
three subplots.
2 Flatten the Axes Array: For a 2x2 grid, the ‘axs‘ object is a 2D
array. You can use ‘[Link]()‘ to get a 1D array, which can be
easier to loop over. Recreate the 2x2 plot but use a ‘for‘ loop over
‘[Link]()‘ to set the titles.

Pratheek Rai N Matplotlib Visualization October 15, 2025 19 / 29


Example 2: Sharing Axes - Code

1 x = np . linspace (0 , 10 , 100)
2 y1 = x **2
3 y2 = np . exp ( x /2)
4
5 fig , ( ax1 , ax2 ) = plt . subplots (
6 2 , 1 , figsize =(6 , 6) ,
7 sharex = True )
8
9 ax1 . plot (x , y1 , color = ’ navy ’)
10 ax1 . set_ylabel ( ’ Squared ’)
11
12 ax2 . plot (x , y2 , color = ’ maroon ’)
13 ax2 . set_ylabel ( ’ Exponential ’)
14 ax2 . set_xlabel ( ’ Input ( x ) ’)
15 # Replace plt . show () with this line to save the figure :
16 # plt . savefig ( ’ f ig _s ha r ed _a xe s . png ’, dpi =150 , bbox_inches = ’ tight ’)
17 plt . show ()
18

Pratheek Rai N Matplotlib Visualization October 15, 2025 20 / 29


Example 2: Sharing Axes - Explanation

fig_shared_axes.png

Figure: Output of two plots with a shared x-axis.


Pratheek Rai N Matplotlib Visualization October 15, 2025 21 / 29
Example 2: Exercises

1 Share Both Axes: Create a 2x2 grid and use ‘sharex=True‘ and
‘sharey=True‘. Plot four different functions. What happens to the
tick labels on the inner plots?
2 Share Column-wise: Create a 2x2 grid. Use ‘sharey=’col’‘ to make
plots in the same column share a y-axis. Use ‘sharex=’row’‘ to make
plots in the same row share an x-axis.

Pratheek Rai N Matplotlib Visualization October 15, 2025 22 / 29


Example 3: ‘GridSpec‘ Layouts - Code

1 import matplotlib . gridspec as gs


2 fig = plt . figure ( figsize =(10 , 6) ,
3 c o n s t ra i n e d _ l a y o u t = True )
4 spec = gs . GridSpec (2 , 2 , figure = fig )
5
6 ax1 = fig . add_subplot ( spec [: , 0])
7 ax1 . set_title ( ’ Main Plot ’)
8
9 ax2 = fig . add_subplot ( spec [0 , 1])
10 ax2 . set_title ( ’Top - Right ’)
11
12 ax3 = fig . add_subplot ( spec [1 , 1])
13 ax3 . set_title ( ’ Bottom - Right ’)
14 # Replace plt . show () with this line to save the figure :
15 # plt . savefig ( ’ fig_gridspec . png ’, dpi =150 , bbox_inches = ’ tight ’)
16 plt . show ()
17

Pratheek Rai N Matplotlib Visualization October 15, 2025 23 / 29


Example 3: ‘GridSpec‘ Layouts - Explanation

fig_gridspec.png

Pratheek Rai N Matplotlib Visualization October 15, 2025 24 / 29


Example 3: Exercises

1 T-shape Layout: Use ‘GridSpec‘ to create a ”T” shaped layout: one


plot that spans the entire top row of a 2x2 grid, and two plots in the
bottom row.
2 Complex Span: Use ‘GridSpec‘ on a 3x3 grid. Make one plot span
the first two rows and first two columns. Then, add smaller plots in
the remaining spaces.

Pratheek Rai N Matplotlib Visualization October 15, 2025 25 / 29


Example 4: Inset Plots - Code

1 x = np . linspace (0 , 10 , 500)
2 y = np . sin ( x ) + np . sin (3* x ) /3
3 fig , ax_main = plt . subplots ( figsize =(8 , 5) )
4 ax_main . plot (x , y )
5 ax_main . set_title ( ’ Main Plot ’)
6
7 ax_inset = ax_main . inset_axes (
8 [0.6 , 0.6 , 0.35 , 0.35])
9
10 ax_inset . plot (x , y , color = ’ red ’)
11 ax_inset . set_xlim (1.5 , 3.5)
12 ax_inset . set_ylim (0.5 , 1.4)
13
14 ax_main . i n d i c a t e _ i n s e t _ z o o m (
15 ax_inset , edgecolor = " black " )
16 # Replace plt . show () with this line to save the figure :
17 # plt . savefig ( ’ fig_inset . png ’, dpi =150 , bbox_inches = ’ tight ’)
18 plt . show ()
19

Pratheek Rai N Matplotlib Visualization October 15, 2025 26 / 29


Example 4: Inset Plots - Explanation

fig_inset.png

Pratheek Rai N Matplotlib Visualization October 15, 2025 27 / 29


Example 4: Exercises

1 Change Inset Position: Move the inset plot to the bottom-left


corner of the main plot.
2 Manual Indication: Instead of using
‘indicatei nsetz oom‘, manuallydrawarectangleonthemainplottoshowthezoom
use‘[Link]‘).

Pratheek Rai N Matplotlib Visualization October 15, 2025 28 / 29


Thank You / Q&A

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

You might also like