Adventures in
Python: Plotting Sine and Cosine, The
numpy Module
This program will require that you have both numpy and
matplotlib. If you are working with
Pythonista for the iOS, the two modules are included. Other versions of Python require that you
download matplotlib and numpy separately.
Please refer to this post:
http://edspi31415.blogspot.com/2017/09/adventures-in-python-installing-and.html
Pointers:
1. The module numpy works with functions with lists as
arguments. There is a math function
associated with numpy. See the section
on numpy functions below.
2. It is helpful to
set up all the graphing parameters before showing the graph with pylplot.show().
3. Color strings are six digit hexadecimal integers with the
format ‘#RRGGBB’ (R = red, G = green, B = blue)
4. To turn the plot
grid on, use pyplot.legend(). To turn on the legend on use pyplot.legend(). Labels are defined in pyplot.plot.
Program:
# this will require
matplotlib
# download if needed
# radians mode is
the default
import matplotlib
from matplotlib
import pyplot
# will need numpy to
generate lists
import numpy
# we will need math
module for pi
import math
# generate lists
x =
numpy.linspace(-2*math.pi, 2*math.pi, 50)
# sin and cos are
included in numpy
y1 = numpy.sin(x)
y2 = numpy.cos(x)
y3 =
numpy.sin(x)+numpy.cos(x)
# alt for y3:
numpy.add(y1,y2)
# the plot begins
pyplot.plot(x,y1,color
= '#228b22', label = 'sin x')
pyplot.plot(x,y2,color
= '#ffa500', label = 'cos x')
pyplot.plot(x,y3,color
= '#919811', label = 'sin x + cos x')
# turn grid on
pyplot.grid(True)
# labels
pyplot.title('Trig
Plots 007')
pyplot.xlabel('x')
pyplot.ylabel('y')
# turn legend box on
pyplot.legend()
# show the plot
pyplot.show()
Output:
Some Numpy Functions
numpy.add(list 1, list 2)
Adds two lists, element by element.
numpy.subtract(list 1, list 2) Subtracts list 2 from list 1, element by
element.
numpy.mutiply(list 1, list 2) Multiplies two lists, element by element.
numpy.divide(list 1, list 2) Divides list 1 by list 2, element by
element.
numpy.power(list 1, list 2) Calculates list 1**list 2.
numpy.maximum(list 1, list 2) Takes the maximum of each respective pair.
numpy.minimum(list 1, list 2) Takes the minimum of each respective pair.
numpy.round(list, number of decimal places) Round each element.
Other element by element operations: (one list arguments –
Radians is the default angle measure)
numpy.square
|
numpy.sqrt
|
numpy.cbrt (cube root)
|
numpy.absolute
|
numpy.sin
|
numpy.cos
|
numpy.tan
|
numpy.radians (convert to radians)
|
numpy.asin
|
numpy.acos
|
numpy.atan
|
numpy.degrees (covert to degrees)
|
numpy.exp
|
numpy.log (ln)
|
numpy.real
|
numpy.imag
|
numpy.angle
|
numpy.log10 (log)
|
numpy.sinc
|
numpy.i0 (Bessel first kind, order 0)
|
Until next time,
Eddie
This blog is property of Edward Shore, 2017.