0% found this document useful (0 votes)
23 views25 pages

Lect 6

This document discusses presenting and visualizing data from calculations. It introduces the matplotlib library for creating visual plots from numerical data in Python. It demonstrates how to plot simple functions like sine and cosine by preparing arrays of x and y values from NumPy, and then using matplotlib functions like plot, xlabel, ylabel to generate and label a plot. It also shows how to visualize 2D functions by creating grids of x and y values and generating color gradient or contour plots.

Uploaded by

Devansh
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)
23 views25 pages

Lect 6

This document discusses presenting and visualizing data from calculations. It introduces the matplotlib library for creating visual plots from numerical data in Python. It demonstrates how to plot simple functions like sine and cosine by preparing arrays of x and y values from NumPy, and then using matplotlib functions like plot, xlabel, ylabel to generate and label a plot. It also shows how to visualize 2D functions by creating grids of x and y values and generating color gradient or contour plots.

Uploaded by

Devansh
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
You are on page 1/ 25

Presentation and Visualisation

Intro to Programming

Kapil Hari Paranjape

IISER Mohali

5th October 2023

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 1 / 25
Displaying the results
Once we have carried out the calculation, we have to output the results.
One way to do this via “formatted” printing.
We can produce a nice table of the data.
0.00e+00 | 0.000e+00
1.00e-02 | 1.000e-02
2.00e-02 | 2.000e-02
3.00e-02 | 3.000e-02
4.00e-02 | 3.999e-02
5.00e-02 | 4.998e-02
6.00e-02 | 5.996e-02
7.00e-02 | 6.994e-02
8.00e-02 | 7.991e-02
9.00e-02 | 8.988e-02
...
Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 2 / 25
This was produced by the following program.
import math as m
import numpy as np
for k in np.arange(0.0, m.pi, 0.01):
print("{:8.2e} |{:10.3e}".format(k, m.sin(k)))
Here we have used arange from the numpy library in the form:
np.arange( start , stop , step )
to produce a 1-dimensional array of floating point numbers.
We have also used format to ensure that the floating point numbers are
printed in a uniform way.
Here the e in the format string indicates “scientific notation”.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 3 / 25
Seeing the data

While tables are nice it is often nicer to see data presented visually in a
2-dimensional format.
Since the human eye has a 2-dimensional retina, all images are originally
2-dimensional!
The signals from the retina are processed by the brain.
The brain combines these signals into a “movie” which is what we “observe”.
The actual neurological process may be more complex than this!

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 4 / 25
This process is called “visualisation” of the data.
What we must remember is that this is done primarily for humans to
perceive and process.
Thus, we must bring out the features of the data in a way that a person
seeing it can easily recognise them.

Seeing is believing!

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 5 / 25
matplotlib Library

As we have seen earlier the math library provides convenient


implementations of standard mathematical functions.
Similarly, the numpy library provides convenient ways of dealing with
multi-dimensional arrays of numerical data.
The matplotlib library provides many ways to visualise the results of our
computations.
It combines well with numpy which provides ways of creating tables of data
to be plotted.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 6 / 25
Preparing the data
We need to provide a pair (xi ), (yi ) of sequences of the same length
consisting of the values (points) to be plotted.
stepsize = 0.05
x = np.arange(-m.pi, m.pi, stepsize)
produces a sequence (xi ) of values from −π to π in steps of size 0.05.
To produce the corresponding (yi ), we need to apply our chosen function to
each (xi ).
The numpy library provides a vectorize method which converts a function
fun into another function that applies fun to each element of a
multi-dimensional array.
y = np.vectorize(m.cos)(x)
creates the sequence (cos(xi )) of corresponding values of the Cosine
function.
Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 7 / 25
Invoking plot

We now plot the values using the pyplot submodule of matplotlib.


import matplotlib.pyplot as plt
plt.plot(x,y)
To give the eye reference, we also show the axes through the origin in black.
plt.axhline(y=0, color="black") # horizontal-axis
plt.axvline(x=0, c="black") # vertical-axis
We also put labels on the axis to explain what is being plotted.
plt.xlabel("Radians")
plt.ylabel("Cosines")

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 8 / 25
Finally, we ask to see the figure that has been created.
plt.show()
This gives us:

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 9 / 25
Optical Illusions

We notice that the data is discrete, but the plot appears to be continuous.
One reason is that our brain “creates” continuity (and even
differentiability!).
Our visual system looks for “edges” where continuity fails and interpolates
the rest!
It seems that a large percentage of what we “see” is not data from the
retina but created in the brain based on past experience!

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 10 / 25
Further, pyplot assists this process by joining successive points by lines to
fill in the gaps.
We can see this clearly by reducing the step size by putting stepsize=0.5.
This gives:

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 11 / 25
We can ask pyplot to only show the “dots”.
plt.plot(x,y,'.')
This gives:

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 12 / 25
We can combine the “segmented” plot with the “dotty” plot:
plt.plot(x,y)
plt.plot(x,y,'.')
This shows us clearly how the points are being joined by lines.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 13 / 25
If we decrease the step size in this picture using stepsize=0.05, we see:

The way the figure is being constructed becomes clearer.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 14 / 25
In fact, if step size is small enough (say stepsize=0.001) we can ask
pyplot to just plot the dots.

Note that this needs more computation than using lines, but does not
actually give us more visual sense!

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 15 / 25
Anatomy of a figure

The fundamental object for pyplot is of type figure.


Various pyplot methods place things on the figure.
▶ plot places a plot with lines; giving a marker parameter places
markers instead of lines.
▶ axhline places a horizontal line; axvline places a vertical line
▶ xlabel labels the x-axis; ylabel labels the y-axis
▶ title places a title on top
▶ grid makes it look like “graph paper”.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 16 / 25
Perhaps a picture will explain this better.

This figure is from the matplotlib documentation where more details can
be found.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 17 / 25
Plotting f (x, y)

We can also plot functions of 2 variables such as


f (x, y) = cos(x2 ) sin(x + y).
One approach is to plot “level curves” of the type f (x, y) = c for various
values of c.
This is dome by the contour method of pyplot.
Another approach is to make an “image” with a color gradient to indicate
changing values.
This is done by the imshow method of pyplot.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 18 / 25
Preparing the (x, y) grid

We give ranges for x and y as follows.


x = np.arange(xmin,xmax,step)
y = np.arange(ymin,ymax,step)
We now produce the grid as follows.
X, Y = np.meshgrid(x,y)
If x has length a and y has length b, then X and Y have shape (a, b).
The (i, j)-th entry of X is xi .
The (i, j)-th entry of Y is yj .
In other words, we have a collection of points p = pi,j in the plane, and X
gives the x-coordinate of p while Y gives the y-coordinate of p.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 19 / 25
Applying functions

As before, we can use vectorize from numpy to apply functions.


def fun(x,y):
return x**2 - y**3
Z = np.vectorize(fun)(X,Y)
However, we have seen that X*Y for arrays of the same shape does
element-wise multiplication. (Not matrix multiplication!).
This is useful to define simple functions.
The assignment Z = X**2 - Y**3 is the same as the code above!

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 20 / 25
We can also use np.sin, np.cos etc. which are vectorized versions of
m.sin, m.cos etc.
Thus, we can apply the mathematical function f (x, y) = cos(x2 ) sin(x + y)
as follows.
Z = np.cos(X**2)*np.sin(X-Y)

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 21 / 25
Contour plot
We can now create the contour plot (of level curves) as follows.
plt.contour(X,Y,Z)
plt.show() now gives

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 22 / 25
Color gradient plot
We can create the color gradient plot as a “grayscale”.
limits = [xmin,xmax,ymin,ymax]
plt.imshow(Z, extent=limits, cmap='gray', origin='lower')
We specify extent to get correct labels on the axes.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 23 / 25
The combined plot gives us a clearer picture of how to learn from such plots.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 24 / 25
Conclusion

This lecture only gives a small glimpse into what matplotlib can do!
Like the numpy library, the matplotlib library has a lot of features and
capabilities.
However, this should be enough to get you started on making plots of your
calculations.
To learn more go to the Matplotlib website and explore the tutorials,
examples and other documentation.

Kapil Hari Paranjape (IISER Mohali) Presentation and Visualisation 5th October 2023 25 / 25

You might also like