Matplotlib

De knowledge
Aller à la navigation Aller à la recherche

Dessin simple

On se propose d'afficher la fonction f(x)=sin(x)

import numpy as np
from matplotlib import pyplot as plt

x=np.arange(0,6.283,0.01) 
y=np.sin(x)

plt.plot(x,y)
plt.show()

Ligne 1 On utilise numpy je ne m'étends pas sur le sujet, il est approfondi dans une page dédié.

Ligne 2 on importe la partie pyplot de matplotlib sous le nom plt. C'est un usage standard dans l'utilisation de matplotlib.

Ligne 4 on construit un tableau numpy de valeurs entre 0 et 2*π espacé de 0.01.

Ligne 5 on construit un autre tableau avec la valeur du sinus de chacun des points de x.

Ligne 7 on demande le graphique de y en fonction de x

Matplotlib-simple-sin.png

Je vous laisse jouer avec le zoom (la loupe) et le déplacement (la croix).

En gros on a eu besoin de 3 lignes de code!

Si on veut aussi avoir le cosinus

import numpy as np
from matplotlib import pyplot as plt

x=np.arange(0,6.283,0.01) 
sin=np.sin(x)
cos=np.cos(x)

plt.plot(x,sin)
plt.plot(x,cos)
plt.show()

On a compris le code précédent on comprends celui-ci!

Matplotlib-simple-sincos.png

Pour terminer un exemple avec des unités adaptées, des couleurs et des styles de courbes et une grille.

import numpy as np
from matplotlib import pyplot as plt

x=np.arange(0,6.283,0.01) 
sin=np.sin(x)
cos=np.cos(x)

plt.plot(x,sin,label='sin',color='black', linestyle=':', linewidth=1)
plt.plot(x,cos,label='cos', color='green',linestyle='-.', linewidth=1)
plt.legend(loc='upper left')
plt.yticks(ticks=[-1,0,1])
plt.xticks(ticks=[0,1.570,3.14,4.7124,6.28],labels=['0','pi/2','pi','3pi/2','2pi'])
plt.grid()
plt.show()

Matplotlib-simple-details.png

Particularité WSL

Avec Windows 10 et ses versions supérieures WSL est une option intéressante. En revanche la conf est spéciale.

J'ai bien galéré car xterm s'affichait bien mais python3 ./display.py ... rien en faire!

Il faut installer :

sudo apt-get update
sudo apt-get install python3
sudo apt-get install pip
sudo apt-get install libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xfixes0 libxcb-xinerama0 libxcb-xkb1 libxkbcommon-x11-0 libxkbcommon0
sudo apt-get install Qt5
sudo apt-get install libxcb-cursor0
sudo apt-get install python3.10-tk # Or adapt version
pip install numpy
python3 -m pip install   --upgrade   --pre   --index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple   --extra-index-url https://pypi.org/simple   matplotlib
EXPORT DISPLAY=":0.0"

Matplotlib-sample-wsl.png