HomeTurtlegraficsGPanelRobotics WebTigerPython
 Python - Online
Deutsch   English   

16. NumPy and MatPlotLib

 

 

YOU LEARN HERE...

 

how to import Python libraries numpy and matplotlib into WebTigerPython.

 

 

WHAT IS NUMPY AND MATPLOTLIB?

 

numpy is a Python extension module used for scientific calculations. Since this module is written in C, numerical calculations are performed much faster with numpy than with standard Python. In addition, nympy enriches Python with powerful data structures for efficient calculations with large arrays and matrices.
matplotlib is used for the visualisation and graphical representation of data.

 

 

EXAMPLES

 
 

Example 1: Graphically visualising a data series
You import the numpy and matplotlib modules. It is usual to give these imports short aliases np and pltwhich are then used in the programme code. The list
values is converted to the numpy array using np.array() and the values of the array v are calculated. The array is displayed in the coordinate system using the plot() function from the mathplotlib module.

Program:  

#Gp16a.py
import numpy as np
import matplotlib.pyplot as plt

values = [20.1, 20.8, 21.9, 22.5, 22.7,21.8, 21.3, 20.9, 20.1]
a = np.array(values)
v = a * 9/5 + 34.789
print(v)
plt.plot(v)
plt.show()
► Copy to clipboard


Example 2
: Function graphs
The numpy module supports many mathematical functions (https://numpy.org/doc/stable/reference/routines.math.html).
You can visualise these very easily with matplotlib. The appropriate coordinate system is added automatically.

The function arange(start, stop, step)from the numpy module returns a half-open interval [start, stop) with a step distance between two consecutive values.
(start is included, stop is not). In contrast to the Python function range(start, stop, step) , which returns a list of integer values, arange(start, stop, step) can also return decimal numbers.
np.arange(0, 10.01, 0.01) returns an array with the numbers 0, 0.1, 0.2, 0.3 ......10.
plt.plot(x, f1, color= "red") plots the function values f1(x) with the red colour in the coordinate system for all values of the array.

Program:  

#Gp16b.py
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10.01, 0.01)
f1 = np.sin(x)
f2 = np.cos(x)
f3 = 0.01 * x**2 + 0.15 * x - 1
plt.plot(x, f1, color="red")
plt.plot(x, f2, color="blue")
plt.plot(x, f3, color="green")
plt.show()
► Copy to clipboard


Example 3: Bar chart
In the next example, the number of fruits is displayed in a coloured Bar chart . Use set_titel() and set_ylabel() to add the title and the label to the y-axis.

Program:  

#Gp16c.py
import matplotlib.pyplot as plt

fig, fx = plt.subplots()
fruits = ['apple','bananas','blueberry', 'orange']
counts = [80, 40, 30, 55]
bar_colors = ['tab:red','tab:olive','tab:blue','tab:orange']
fx.bar(fruits, counts, color=bar_colors)
fx.set_ylabel('number of fruits ')
fx.set_title('Fruits')
plt.show()
► Copy to clipboard

Example 4: Horizontal bar chart
Here you use a bar chart to display the results of a cube simulation. You define a function countFrequency(), that generates 300 random dice numbers and calculates the frequencies with which the individual numbers occur. Use a Bar chartto display these frequencies in the coordinate system.
Run the programme several times and increase the number of dice n.

Program:  

#Gp16d.py
import matplotlib.pyplot as plt
import numpy as np
from random import randint

def countFrequency():
    global a
    n = 300
    for i in range(n):
        r = randint(1, 6)
        if r == 1:
            a[0] += 1
        elif r == 2:
            a[1] += 1
        elif r == 3:
            a[2] += 1 
        elif r == 4:
            a[3] += 1
        elif r == 5:
            a[4] += 1
        elif r == 6:
            a[5] += 1     

fig, fx = plt.subplots()
diceNumbers = ('1', '2', '3', '4', '5', '6')
a = [0, 0, 0, 0, 0, 0]
y_pos = np.arange(len(diceNumbers))
countFrequency()
frequency = [a[0], a[1], a[2], a[3], a[4], a[5]]
fx.barh(y_pos, frequency, align='center')
fx.set_yticks(y_pos, labels=diceNumbers)
fx.set_xlabel('Frequency')
fx.set_title('Dice simulation (n = 300)')
plt.show()
► Copy to clipboard

 

 

REMEMBER YOU...

 

With import numpy and import matplotlib you extend WebTigerPython with powerful additional modules that you can use for scientific calculation and graphical representation of numerical material.

 

 

TO SOLVE BY YOURSELF

 

1)


Set the values of the list values

values = [35, 40, 25, 46, 72, 65, 80, 60, 36]

a) with a line graph
b) with a bar chart.

   
 

2)


Plot the function
f = x3 - 9x
n the range -4 < x < 4 r.

 

 


 

3)


The function known from physics
y = ae-kt sin(ωt + pi/2)
represents a damped harmonic oscillation.
a: initial amplitude
k: damping constant
omega: angular frequency of the undamped system

You can calculate the function values from the modulus np using the functions exp() , sin(), pi:

f = a * np.exp(-k * x) * np.sin(omega * x + np.pi/2)

Plot the function for the values
a = 5
k = 0.04
omega = 0.6

in the range 0 < x < 100 .