python:matplotlib

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
python:matplotlib [2023/02/17 10:30] – [Labels des axes] change size of tick labels phswpython:matplotlib [2024/10/06 15:47] (Version actuelle) – [Matplotlib] add link phsw
Ligne 2: Ligne 2:
  
   * [[https://hal.inria.fr/hal-03427242/document|Scientific Visualization: Python + Matplotlib]]   * [[https://hal.inria.fr/hal-03427242/document|Scientific Visualization: Python + Matplotlib]]
 +  * [[https://duetosymmetry.com/code/latex-mpl-fig-tips/|Fonts/sizes in matplotlib figures for LaTeX publications]]
 +  * https://datavizcatalogue.com/FR/
 +
  
  
Ligne 80: Ligne 83:
 </code> </code>
  
-Paramètres facultatifs de ''[[https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html|ax.legend()]]'': +Paramètres facultatifs de ''[[https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html|ax.legend()]]''
-  * ''handletextpad'': espacement entre le symbole et le texte +  * ''handletextpad'' : espacement entre le symbole et le texte 
-  * ''borderpad'': padding de la boîte de légende +  * ''borderpad'' : padding de la boîte de légende 
-  * ''borderaxespad'': décalage par rapport aux bordures du graphique +  * ''borderaxespad'' : décalage par rapport aux bordures du graphique 
-  * ''handlelength'': longueur du symbole +  * ''handlelength'' : longueur du symbole 
-  * ''ncol'': sur combien de colonnes répartir les éléments de la légende +  * ''labelspacing'' : espace entre deux éléments de la légende (par défaut 0,5) 
-  * ''prop={'size': 6}'' ou ''fontsize'': change la taille du texte de la légende (accepte un entier ou les valeurs ''xx-small'', ''x-small'', ''small'', ''medium'', ''large'', ''x-large'', ''xx-large'' +  * ''ncol'' : sur combien de colonnes répartir les éléments de la légende 
-  * ''title="Un titre"'': donne un titre à la légende ([[https://matplotlib.org/stable/gallery/text_labels_and_annotations/legend_demo.html#sphx-glr-gallery-text-labels-and-annotations-legend-demo-py|source]])+  * ''prop={'size': 6}'' ou ''fontsize'' : change la taille du texte de la légende (accepte un entier ou les valeurs ''xx-small'', ''x-small'', ''small'', ''medium'', ''large'', ''x-large'', ''xx-large'' 
 +  * ''title="Un titre"'' : donne un titre à la légende ([[https://matplotlib.org/stable/gallery/text_labels_and_annotations/legend_demo.html#sphx-glr-gallery-text-labels-and-annotations-legend-demo-py|source]])
  
 La taille de la police de la légende peut être définie par défaut: La taille de la police de la légende peut être définie par défaut:
Ligne 286: Ligne 290:
 # or: # or:
 plt.xticks([])  # also hide grid lines plt.xticks([])  # also hide grid lines
 +</code>
 +
 +Changer l'emplacement des graduations et leurs valeurs (depuis une version récente de Matplotlib) :
 +<code python>
 +plt.yticks(ticks, labels)
 +# ou
 +ax.set_yticks(ticks, labels)
 </code> </code>
  
Ligne 300: Ligne 311:
 plt.xticks(x, labels, rotation='vertical') plt.xticks(x, labels, rotation='vertical')
 plt.xticks(x, labels, rotation=90) plt.xticks(x, labels, rotation=90)
 +
 +# or just:
 +plt.xticks(rotation="vertical")
  
 # or: # or:
 for tick in ax.get_xticklabels(): for tick in ax.get_xticklabels():
     tick.set_rotation(45)     tick.set_rotation(45)
 +    
 +# or (with Matplotlib >= 3.5):
 +ax.set_xticks(ax.get_xticks(), ax.get_xticklabels(), rotation=45, ha='right')
  
 # Pad margins so that markers don't get clipped by the axes # Pad margins so that markers don't get clipped by the axes
Ligne 319: Ligne 336:
  
 <code python> <code python>
 +# De façon générale :
 plt.rc('xtick', labelsize=8)  # 8 est petit plt.rc('xtick', labelsize=8)  # 8 est petit
-</code> 
  
-[[https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot/39566040|Source]] +# Uniquement pour un axe :
-<code python>+
 for label in ax.get_xticklabels(): for label in ax.get_xticklabels():
     label.set_fontsize(8)     label.set_fontsize(8)
Ligne 440: Ligne 456:
 for i in range(len(bars)): for i in range(len(bars)):
     bars[i].set_hatch(hatches[i])     bars[i].set_hatch(hatches[i])
 +    # pour avoir un export correct dans les PDFs, utiliser plutôt :
 +    bars[i].set(hatch="//", alpha=1)
 </code> </code>
  
Ligne 487: Ligne 505:
  
 plt.show() plt.show()
 +</code>
 +
 +Placer l'origine en bas à gauche :
 +<code python>
 +ax.imshow(matrix, origin="lower")
 +</code>
 +
 +Changer les couleurs utilisées (voir la liste [[https://matplotlib.org/stable/tutorials/colors/colormaps.html#__do_not_save__|ici]]) :
 +<code python>
 +ax.imshow(matrix, cmap="Grey")
 </code> </code>
  
Ligne 496: Ligne 524:
  
  
-Pivoter les labels de l'axe des abscisses (voir la [[https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/demo_text_rotation_mode.html|ref]]:+Pivoter les labels de l'axe des abscisses (voir la [[https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/demo_text_rotation_mode.html|ref]]:
 <code python> <code python>
 plt.setp(ax2.get_xticklabels(), rotation=90, ha="right", va="center", rotation_mode="anchor") plt.setp(ax2.get_xticklabels(), rotation=90, ha="right", va="center", rotation_mode="anchor")
 </code> </code>
  
-Ajouter un titre englobant les deux graphes:+Ajouter un titre englobant les deux graphes :
 <code python> <code python>
 fig.suptitle(title) fig.suptitle(title)
 +</code>
 +
 +Il est possible de préciser à quelle hauteur placer le titre ([[https://stackoverflow.com/questions/55767312/how-to-position-suptitle|source]]) :
 +<code python>
 +fig.suptitle(title, y=0.95)
 +</code>
 +
 +
 +Dessiner un rectangle ([[https://stackoverflow.com/questions/67946418/how-to-add-rectangle-patches-in-python-heatmap|source]]) :
 +<code python>
 +import matplotlib.patches as patches
 +
 +ax.add_patch(
 +     patches.Rectangle(
 +         (5, 6),
 +         1.0,
 +         35.0,
 +         edgecolor='red',
 +         fill=False,
 +         lw=2
 +     ) )
 +</code>
 +
 +
 +Pour ne pas forcer que les cases soient carrées ([[https://stackoverflow.com/questions/32256586/how-to-control-the-cell-size-of-a-pyplot-pcolor-heatmap|source]]) :
 +<code python>
 +ax.set_aspect("auto")
 +</code>
 +
 +Pour agrandir la heatmap, il peut être aussi utile de ne pas utiliser ''tight_layout''.
 +
 +Ajouter du texte dans chaque case de la heatmap ([[https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html|source]]) :
 +<code python>
 +for i in range(len(vegetables)):
 +    for j in range(len(farmers)):
 +        text = ax.text(j, i, harvest[i, j], ha="center", va="center", color="w")
 </code> </code>
  
Ligne 517: Ligne 581:
 </code> </code>
  
 +
 +
 +=== Boxplots ===
 +
 +Pour que Matplotlib calcule directement les statistiques : ''ax.boxplot()'' ([[https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.boxplot.html#__do_not_save__|documentation]])
 +
 +Pour fournir nous-mêmes les statistiques à Matplotlib : ''ax.bxp()'' ([[https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bxp.html#__do_not_save__|documentation]])
 +
 +
 +== Changer la couleur de fond ==
 +
 +[[https://matplotlib.org/stable/gallery/statistics/boxplot_color.html#sphx-glr-gallery-statistics-boxplot-color-py|Source]]
 +
 +<code python>
 +boxplot = ax1.boxplot(all_data, patch_artist=True)
 +for b in boxplot['boxes']:
 +    b.set_facecolor(color)
 +</code>
 +
 +== Légende correspondante ==
 +
 +[[https://stackoverflow.com/questions/47528955/adding-a-legend-to-a-matplotlib-boxplot-with-multiple-plots-on-same-axes|Source]]
 +
 +<code python>
 +boxplot = ax.boxplot(all_data, patch_artist=True)
 +ax.legend([boxplot["boxes"][0]], ["Label"])
 +</code>
  
  
Ligne 569: Ligne 660:
 from matplotlib.patches import Patch from matplotlib.patches import Patch
  
-Patch(hatch="+", label="Label", alpha=0)+Patch(hatch="+", label="Label", alpha=1, fill=False# alpha=0 ne fonctionne pas pour l'export en PDF.
 </code> </code>
  
Ligne 656: Ligne 747:
 </code> </code>
  
 +
 +
 +=== Définir le centre de la colorbar ===
 +
 +Pour les palettes des couleurs divergentes ([[https://matplotlib.org/stable/tutorials/colors/colormapnorms.html|source]]) :
 +<code python>
 +from matplotlib.colors import TwoSlopeNorm
 +
 +divnorm = TwoSlopeNorm(vmin=0, vcenter=1)
 +im = ax.imshow(matrix, cmap="seismic", norm=divnorm)
 +</code>
  
  
Ligne 857: Ligne 959:
 </code> </code>
  
-Pour n'affiche qu'une légende, sous tous les graphes :+Pour n'afficher qu'une légende, sous tous les graphes :
 <code python> <code python>
 handles_left, labels_left = axs[0,0].get_legend_handles_labels() handles_left, labels_left = axs[0,0].get_legend_handles_labels()
Ligne 867: Ligne 969:
 <code python> <code python>
 fig.delaxes(axs[i, j]) fig.delaxes(axs[i, j])
 +</code>
 +
 +Pour définir le titre de chaque sous-graphe :
 +<code python>
 +axes[j_msg_size,i_comm_size].set_title("Titre", fontdict={"fontsize": 9})
 </code> </code>
  
  • python/matplotlib.1676626253.txt.gz
  • Dernière modification : 2023/02/17 10:30
  • de phsw