Envoyez-vous 16 conseils pratiques pour le dessin matplotlib (code joint)

Source: Cochon volant de Snow Mountain

Cet article est à propos de 2800 mots , Il est recommandé de lire 10 minutes

Cet article partagera avec vous 16 conseils pratiques pour le traçage matplotlib.

Label: Analyse des données

1. Ajouter titre-titre

import numpy as npimport matplotlib.pyplot as plt # Afficher le chinois plt.rcParams = plt.rcParams = False% matplotlib inlinex = np.arange (0,10) plt.title ('This is an example title') plt.plot (x , x * x) plt.show ()

Production:

2. Ajouter du texte-texte

Définissez simplement les coordonnées et le texte

import numpy as npimport matplotlib.pyplot as plt # Afficher chinois plt.rcParams = plt.rcParams = False% matplotlib inlinex = np.arange (-10,11,1) y = x * xplt.plot (x, y) plt. title ('Ceci est un exemple de titre') # Ajouter du texte plt.text (-2.5,30, 'function y = x * x') plt.show ()

Production:

3. Ajouter une annotation-annoter

  • xy: Point de coordination pour les remarques
  • xytext: Les coordonnées du texte de la remarque (la valeur par défaut est la position de xy)
  • flèche: Dessinez une flèche entre xy et xytext
import numpy as npimport matplotlib.pyplot as plt # Display Chinese plt.rcParams = plt.rcParams = False% matplotlib inlinex = np.arange (-10,11,1) y = x * xplt.title ('Ceci est un exemple de titre ') plt.plot (x, y) # Ajouter une annotation plt.annotate (' Ceci est un exemple d'annotation ', xy = (0,1), xytext = (- 2,22), arrowprops = (' headwidth ': 10 , 'facecolor': 'r'}) plt.show ()

Production:

4. Définissez le nom de l'axe-xlabel / ylabel

import numpy as npimport matplotlib.pyplot as plt # Display Chinese plt.rcParams = plt.rcParams = False% matplotlib inlinex = np.arange (1,20) plt.xlabel ('example x axis') plt.ylabel ('example y Axe ') plt.plot (x, x * x) plt.show ()

Production:

5. Ajouter une légende-légende

import numpy as npimport matplotlib.pyplot as plt # Afficher chinois plt.rcParams = plt.rcParams = False% matplotlib inlineplt.plot (x, x) plt.plot (x, x * 2) plt.plot (x, x * 3 ) plt.plot (x, x * 4) # Passer directement dans legendplt.legend () plt.show ()

Production:

6. Ajustez la couleur-couleur

Passer les paramètres de couleur, prendre en charge les méthodes suivantes

import numpy as np import matplotlib.pyplot as plt% matplotlib inlinex = np.arange (1,5) #Plusieurs façons de colorer plt.plot (x, color = 'g') plt.plot (x + 1, color = ' 0.5 ') plt.plot (x + 2, color =' # FF00FF ') plt.plot (x + 3, color = (0.1,0.2,0.3)) plt.show ()

Production:

7. Changer de marqueur de style de ligne

import numpy as np import matplotlib.pyplot as plt% matplotlib inlinex = np.arange (1,5) plt.plot (x, marker = 'o') plt.plot (x + 1, marker = ' > ') plt.plot (x + 2, marker =' s ') plt.show ()

Production:

8. Afficher la formule mathématique-mathtext

Le format est le suivant: \ omega $, le symbole dans la formule sera analysé au milieu

import numpy as np import matplotlib.pyplot as plt% matplotlib inlineplt.title ('chenqionghe') plt.xlim () plt.ylim () plt.text (2,4, r '$ \ alpha \ beta \ pi \ lambda \ omega $ ', taille = 25) plt.text (4,4, r' $ \ sin (0) = \ cos (\ frac {\ pi) {2}) $ ', taille = 25) plt.text (2, 2, r '$ \ lim_ {x \ rightarrow y} \ frac {1} {x ^ 3} $', taille = 25) plt.text (4,2, r '$ \ sqrt {x} = \ sqrt { y) $ ', taille = 25) plt.show ()

Production:

9. Afficher grille-grille

import numpy as np import matplotlib.pyplot as plt% matplotlib inlinex = 'a', 'b', 'c', 'y = plt.grid () # Vous pouvez également définir la couleur, la largeur de ligne et le style de ligne # plt.grid (color = 'g', linewidth = '1', linestyle = '-.') plt.plot (x, y) plt.show ()

Production:

10. Ajustez l'axe scale-locator_params

  • Ajustez l'axe x et l'axe y en même temps: plt.locator_params (nbins = 20);
  • Ajustez uniquement l'axe des x: plt.locator_params («x», nbins = 20);
  • Ajustez uniquement l'axe y: plt.locator_params («y», nbins = 20).
import numpy as np import matplotlib.pyplot as plt% matplotlib inlinex = np.arange (0,30,1) plt.plot (x, x) # Les axes x et y affichent respectivement 20 plt.locator_params (nbins = 20) plt .spectacle()

Production:

11. Ajustez l'axe range-axis / xlim / ylim

  • axe: , X de 0 à 5, y de 0 à 10
  • xlim: Les paramètres correspondants sont xmin et xmax, qui peuvent ajuster respectivement les valeurs maximum et minimum
  • ylim: Identique à l'utilisation xlim
import numpy as np import matplotlib.pyplot as plt% matplotlib inlinex = np.arange (0,30,1) plt.plot (x, x * x) #Afficher l'axe des coordonnées, plt.axis (), les 4 nombres représentent respectivement x Les coordonnées minimales de l'axe et de l'axe y, les coordonnées maximales # ajustez x à 10 à 25plt.xlim (xmin = 10, xmax = 25) plt.plot (x, x * x) plt.show ()

Production:

12. Ajustez la date adaptive-autofmt_xdate

Parfois, les dates affichées se chevauchent, ce qui est très peu convivial. Appeler plt.gcf (). Autofmt_xdate () ajustera automatiquement l'angle

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt% matplotlib inlinex = pd.date_range ('2020/01/01', périodes = 30) y = np.arange (0,30,1) plt.plot (x, y) plt.gcf (). autofmt_xdate () plt.show ()

Production:

13. Ajouter dual axis-twinx

import numpy as npimport matplotlib.pyplot as plt% matplotlib inlinex = np.arange (1,20) y1 = x * xy2 = np.log (x) plt.plot (x, y1) # Ajouter un axe de coordonnées, par défaut 0 à 1plt.twinx () plt.plot (x, y2, 'r') plt.show ()

Production:

14. Remplissez area-fill / fill_beween

remplir la zone de fonction de remplissage

import numpy as np import matplotlib.pyplot as plt # Display Chinese plt.rcParams = plt.rcParams = False% matplotlib inlinex = np.linspace (0,5 * np.pi, 1000) y1 = np.sin (x) y2 = np .sin (2 * x) plt.plot (x, y1) plt.plot (x, y2) # Fill plt.fill (x, y1, 'g') plt.fill (x, y2, 'r') plt .title ('Ceci est un exemple de titre') plt.show ()

Production:

fill_beween zone d'intersection de la fonction de remplissage

import numpy as npimport matplotlib.pyplot as plt # Afficher le chinois plt.rcParams = plt.rcParams = False% matplotlib inlineplt.title ('Ceci est un exemple de titre') x = np.linspace (0,5 * np.pi, 1000 ) y1 = np.sin (x) y2 = np.sin (2 * x) plt.plot (x, y1) plt.plot (x, y2) # Fill plt.fill_between (x, y1, y2, où = y1 > y2, interpoler = Vrai) plt.show ()

Production:

15. Dessinez un shape-matplotlib.patche rempli

import numpy comme npimport matplotlib.pyplot comme pltimport matplotlib.patches comme mptaches% matplotlib inlinexy1 = np.array () xy2 = np.array () xy3 = np.array () xy4 = np.array () fig, ax = plt. subplots () # circle, spécifiez les coordonnées et le rayon circle = mptaches.Circle (xy1,0.15) ax.add_patch (circle) #rectangle rect = mptaches.Rectangle (xy2,0.2,0.1, color = 'r') ax.add_patch (rect) # polygon polygon = mptaches.RegularPolygon (xy3,6,0.1, color = 'g') ax.add_patch (polygon) # ellipse = mptaches.Ellipse (xy4,0.4,0.2, color = 'c') ax .add_patch (ellipse) ax.axis ('égal') plt.show ()

Production:

16. Commutez style-plt.style.use

Matplotlib prend en charge une variété de styles, vous pouvez changer de style via plt.style.use, par exemple: plt.style.use ('ggplot') input plt.style. Disponible pour afficher tous les styles:

import matplotlib.pyplot comme pltplt.style. disponible

Production:

Exemple de code, style ggplot:

import numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as mptaches% matplotlib inlineplt.style.use ('ggplot') # Créer 4 nouvelles sous-parcelles fig, axes = plt.subplots (2,2) ax1, ax2, ax3, ax4 = axes.ravel () # Le premier graphique x, y = np.random.normal (size = (2,100)) ax1.plot (x, y, 'o') # Le deuxième graphique x = np.arange ( 0,10) y = np.arange (0,10) colors = plt.rcParamslength = np.linspace (0,10, len (couleurs)) pour s de longueur: ax2.plot (x, y + s, '- ') # Le troisième graphique x = np.arange (5) y1, y2, y3 = np.random.randint (1,25, size = (3,5)) width = 0.25ax3.bar (x, y1, width) ax3.bar (x + width, y2, width) ax3.bar (x + 2 * width, y3, width) # La quatrième image pour i, color in enumerate (colors): xy = np.random.normal (taille = 2) ax4.add_patch (plt.Circle (xy, rayon = 0,3, couleur = couleur)) ax4.axis ('égal') plt.show ()

Production:

Adresse d'origine: https://www.cnblogs.com/chenqionghe/

Editeur: Wang Jing

Relecture: Lin Yilin

-Terminer-

Suivez la plate-forme publique officielle WeChat de l'Institut Tsinghua-Qingdao pour la science des données " Tarte aux données AI "Et le numéro de soeur" Tarte aux données JEU "Obtenez plus d'avantages de cours et un contenu de qualité.

Google Translate est écrasé! Le premier moteur de traduction au monde DeepL est de retour, la "folie du diable" est terminée
Précédent
USTC × MSRA | Dr Zhou Ming conférence Record: Natural Language Processing Better Life
Prochain
A « chair de poule » étape importante: les scientifiques chinois les ondes cérébrales de décodage AI, le taux de précision de 97%
De nouvelles données de recherche de la Couronne où trouver? Les chercheurs doivent-voir (lien ci-joint)
« Hey Siri » équipe de développement scientifique et technologique derrière le noir!
L'apprentissage GRAPHIC: tout le monde peut comprendre l'algorithme principe
portes logiques de protéines avec les cellules dans l'ordinateur, les jeunes chercheurs chinois Gordon sciences
Le premier moteur de traduction au monde a évolué et la «folie du diable» a pris soin du dialecte
La diffusion des « informations » plutôt que « virus »! Les programmeurs avec 500 traduction multilingue « se laver les mains »
Tsinghua lancement plate-forme de sécurité de l'équipe AI AI, algorithme haut de déception face forte, puis corriger les bugs
Limite de décision de différents modèles d'apprentissage automatique (avec code)
Petits robots aider à prendre à emporter! Parc scientifique de Zhongguancun Dongsheng ces « outil de prévention des épidémies » pour contribuer à rétablir la production de retourner au travail
tuyau de chauffage est pas chaud, les fuites d'eau ...... communautés « équipe Parkour de » l'entretien de 60 jours de plus d'un millier de fois
Conseil de Direction « Propriétés Direction » comment évaluer? les lignes directrices de la Commission viennent