Figure et axes

Un graphique consiste en objets

  • Figure l’espace total du graphique

  • Axes la partie qui présente les données

Figure

La fonction subplots() retourne un tuple consistant de

  • Figure le conteneur global

  • Axes pour présenter les données

fig, ax = plt.subplots()
../_images/figure_3_0.png

La classe Figure a environ 150 méthodes.

f = [x for x in dir(fig) if not x.startswith('_')]
print(len(f))
f[:20]
143
['add_artist',
 'add_axes',
 'add_axobserver',
 'add_callback',
 'add_gridspec',
 'add_subplot',
 'align_labels',
 'align_xlabels',
 'align_ylabels',
 'artists',
 'autofmt_xdate',
 'axes',
 'bbox',
 'bbox_inches',
 'callbacks',
 'canvas',
 'clear',
 'clf',
 'clipbox',
 'colorbar']

Taille

La taille de la figure par défaut est 6 x 4 pouces.

fig.get_figwidth(), fig.get_figheight()
(6.0, 4.0)

Nous pouvons modifier la taille avec le mot-clé figsize.

plt.subplots(figsize=(8, 2));
../_images/figure_9_0.png

Couleur

La couleur du graphique est choisie avec facecolor.

plt.subplots(facecolor='lightgray', figsize=(8, 2));
../_images/figure_11_0.png

La couleur du contour et son épaisseur peuvent être choisies.

plt.subplots(figsize=(8, 2), facecolor='pink', 
             edgecolor='red', linewidth=3, frameon=True);
../_images/figure_13_0.png
y = [2, 4, 3, 5, 1]
plt.subplots(figsize=(8, 3), facecolor='pink', 
             edgecolor='red', linewidth=3, frameon=True)
plt.plot(y, 'or-');
../_images/figure_14_0.png

Ligne

Des lignes horizontales et verticales peuvent être ajoutées.

plt.plot(y);
plt.axhline(2, c='r')
plt.axhline(4, 0.1, 0.9, c='r');
../_images/figure_16_0.png
plt.axvline(2, c='r')
plt.axvline(3, 0.1, 0.8, c='r')
plt.plot(y, 'o-');
../_images/figure_17_0.png

Une ligne d’orientation générale est indiquée avec axline et deux points de référence.

plt.plot(y, 'o-');
plt.axline((1, 2), (2, 1.5), c='r')
plt.axline((1, 2), (2, 2.5), c='r');
../_images/figure_19_0.png

Lignes multiples

plt.plot(y, 'o-')
plt.hlines((4, 4.3, 4.6), 0.5, 4, color='r');
../_images/figure_21_0.png
plt.plot(y, 'o-')
plt.vlines((1, 1.2, 1.4), 2, 5, color='r');
../_images/figure_22_0.png

Bandes

La méthode axhspan et axvspan permet de placer des bandes horizontales ou verticales.

plt.axhspan(2, 3, alpha=0.3, color='lime')
plt.plot(y, 'o-');
../_images/figure_24_0.png
plt.axvspan(2, 3, alpha=0.5, color='pink')
plt.plot(y, 'o-');
../_images/figure_25_0.png

Boîte de contour

La boite de contour est optionnelle.

plt.subplots(figsize=(8, 2))
plt.plot(y, 'o-');
plt.box(False)
plt.grid(True)
../_images/figure_27_0.png

Marques de graduation

plt.plot(y, 'o-')
plt.minorticks_on()
../_images/figure_29_0.png
plt.plot(y);
plt.box(True)
plt.tick_params(length=10, width=2, direction='inout', 
                color='red', pad=10, labelcolor='g')
../_images/figure_30_0.png
plt.plot(y);
plt.tick_params(length=0, labelleft=False, labelbottom=False)
../_images/figure_31_0.png

Valeurs par défaut

Toutes les valeurs par défaut sont définis dans rc (runtime configuration).

plt.rc('figure', figsize=(7, 2))
plt.rc('lines', linewidth=2, color='r', linestyle=':')
plt.plot(y);
../_images/figure_34_0.png
plt.bar(range(5), y);
../_images/figure_35_0.png

Axes

Les axes ont plus que 300 attributs et methodes.

a = [x for x in dir(ax) if not x.startswith('_')]
print(len(a))
a[:20]
323
['acorr',
 'add_artist',
 'add_callback',
 'add_child_axes',
 'add_collection',
 'add_container',
 'add_image',
 'add_line',
 'add_patch',
 'add_table',
 'angle_spectrum',
 'annotate',
 'apply_aspect',
 'arrow',
 'artists',
 'autoscale',
 'autoscale_view',
 'axes',
 'axhline',
 'axhspan']

Sous-graphes

La fonction subplot(n, m) crée \(n \times m\) sous-graphes.

plt.subplots();
../_images/figure_39_0.png
plt.subplots(2, 1);
../_images/figure_40_0.png
plt.subplots(1, 2);
../_images/figure_41_0.png

Spécifier un sous-graphe

La fonction subplot(n, m, i) sélectionne le i-ième sous-graphique d’une matrice de \(n \times m\) sous-graphes.

Si le nombre des graphes est inférieur à 10 on peut les désigner directement avec subplot(nmi)

x = [0, 1, 2, 3, 4]
y = [1, 3, 2, 5, 2]
plt.subplot(121)
plt.plot(y, 'ro-')
plt.subplot(122)
plt.bar(x, y);
../_images/figure_44_0.png

Ici les graphes sont superposés.

t = np.arange(0.0, 5.0, 0.1)

plt.subplot(211)
plt.plot(t, np.exp(-t) * np.cos(2*np.pi*t), 'bo-')

plt.subplot(212)
plt.plot(t, np.cos(2*np.pi*t), 'r--');
../_images/figure_46_0.png

Sous-graphes en 2x2

Nous pouvons aussi sous-diviser en \(2 \times 2\) sous-graphes.

plt.subplot(221)
plt.bar(x, y)
plt.subplot(222)
plt.plot(y, 'ro-');
plt.subplot(223)
plt.plot(x, y)
plt.subplot(224)
plt.plot(x, y, 'og');
../_images/figure_48_0.png

Arrangement particulier

Il est possible de varier le nombre de sous-graphes dans chaque ligne.

plt.subplot(2,1,1)
plt.xticks([]), plt.yticks([])

plt.subplot(2,3,4)
plt.xticks([]), plt.yticks([])

plt.subplot(2,3,5)
plt.xticks([]), plt.yticks([])

plt.subplot(2,3,6)
plt.xticks([]), plt.yticks([]);
../_images/figure_50_0.png

Enregistrer une figure

La fonction savefig() permet de sauvegarder une figure. L’extension du fichier détermine le format.

y = [2, 4, 3, 5, 1]
plt.plot(y, 'o-');
plt.savefig('img/demo.png')
plt.savefig('img/demo.jpg')
plt.savefig('img/demo.pdf')
../_images/figure_52_0.png

Les trois fichiers se trouvent dans le dossier local. Le PDF est le plus petit, le JPG le plus grand.

ll img/demo*
-rw-r--r--  1 raphael  staff  17497 Jan 17 20:38 img/demo.jpg
-rw-r--r--  1 raphael  staff   5973 Jan 17 20:38 img/demo.pdf
-rw-r--r--  1 raphael  staff  13472 Jan 17 20:38 img/demo.png

L’image peut être affiché dans un notebook avec la commande ![](img/demo.jpg)