1.6 Plotting, Printing and Input Data
21
sized intervals in [0, 1] and that the coordinates are then given by t i =
1−0
1000 i =
i
1000 ,
i = 0, 1, . . . , 1000.
The object returned from linspace is an array, i.e., a certain collection of (in
this case) numbers. Through the assignment, this array gets the name t. If we like,
we may think of the array t as a collection of “boxes” in computer memory (each
containing a number) that collectively go by the name t (later, we will demonstrate
how these boxes are numbered consecutively from zero and upwards, so that each
“box” may be identified and used individually).
Vectorization When we start computing with t in
y = v0*t - 0.5*g*t**2
the right hand side is computed for every number in t (i.e., every t i for i =
0, 1, . . . , 1000), yielding a similar collection of 1001 numbers in the result y, which
(automatically) also becomes an array!
This technique of computing all numbers “in one chunk” is referred to as
vectorization. When it can be used, it is very handy, since both the amount of
code and computation time is reduced compared to writing a corresponding loop 16
(Chap. 3) for doing the same thing.
Plotting The plotting commands are new, but simple:
plt.plot(t, y)
# plots all y coordinates vs. all t coordinates
plt.xlabel(’t (s)’)
# places the text t (s) on x-axis
plt.ylabel(’y (m)’)
# places the text y (m) on y-axis
plt.show()
# displays the figure
At this stage, you are encouraged to do Exercise 1.4. It builds on the example
above, but is much simpler both with respect to the mathematics and the amount of
numbers involved.
1.6 Plotting, Printing and Input Data
1.6.1 Plotting with Matplotlib
Often, computations and analyses produce data that are best illustrated graphically.
Thus, programming languages usually have many good tools available for producing
and working with plots, and Python is no exception. 17
In this book, we shall stick to the excellent plotting library Matplotlib, which has
become the standard plotting package in Python. Below, we demonstrate just a few
of the possibilities that come with Matplotlib, much more information is found on
the Matplotlib website. 18
16 It should be mentioned, though, that the computations are still done with loops “behind the
scenes” (coded in C or Fortran). They generally run much quicker than the Python loops we write
ourselves.
17 In Sect. 9.2.4 we give a brief example of how plots may be turned into videos.
18 https://matplotlib.org/index.html.
Précédent

- 43/350

Suivant