IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PyQt Python Discussion :

Intégrer un graph Matplotlib dans un QWidget [QtGui]


Sujet :

PyQt Python

  1. #1
    Membre régulier
    Homme Profil pro
    Analyste programmeur
    Inscrit en
    Septembre 2015
    Messages
    148
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : Algérie

    Informations professionnelles :
    Activité : Analyste programmeur
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2015
    Messages : 148
    Points : 92
    Points
    92
    Par défaut Intégrer un graph Matplotlib dans un QWidget
    Bonjour,

    Je suis un petit projet pour afficher des données sur graphe avec matplotlib, jusqu'à la tout marche à merveille.
    Mon projet est dessiné avec Qt Designer PyQt5.
    A l'exécution du programme le graphe est affiché dans une fenêtre de matplotlib.

    Mon souhait est d'afficher le graphe dans un QWidget que j'ai déjà ajouté dans ma fenêtre principale, j'ai beau cherché mais en vain.

    Ci-dessous un bout du code pour la création du graph

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
            self.figure = Figure()
            self.canvas = FigureCanvasQTAgg(self.figure)
            self.figure.clf()
            self.canvas.figure = plt.figure(figsize=(8, 5))
     
            ax1 = self.canvas.figure.add_subplot(111)
            ax2 = self.canvas.figure.add_subplot(111)
            ax3 = self.canvas.figure.add_subplot(111)
     
            ax1.set_title ("Phases")
            ax1.set_xlabel ('Date')
            ax1.set_ylabel ("Valeur ")
     
            ax1.plot_date (date, phase1, '-', label="Phase1", color='r', linewidth=1, marker='^')
            ax2.plot_date (date, phase2, '-', label="Phase2", color='g', linewidth=1, marker='o')
            ax3.plot_date (date, phase3, '-', label="Phase3", color='b', linewidth=1, marker='x')
     
            self.canvas.figure.autofmt_xdate (rotation=45)
            self.canvas.figure.tight_layout()
     
            ax1.grid (True)
            ax1.legend (loc='best', framealpha=0.5)
     
            # plt.savefig ("courbe.png")
            plt.show()
    Merci.

  2. #2
    Expert éminent
    Avatar de tyrtamos
    Homme Profil pro
    Retraité
    Inscrit en
    Décembre 2007
    Messages
    4 462
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2007
    Messages : 4 462
    Points : 9 249
    Points
    9 249
    Billets dans le blog
    6
    Par défaut
    Bonjour,

    Je ne l'ai jamais fait, mais comme je suis curieux, j'ai cherché sur le web avec les mots "pyqt qwidget matplotlib embeded", j'ai trouvé:
    https://stackoverflow.com/questions/...qt-for-dummies

    Après avoir modernisé PyQt4 => PyQt5 et changé QDialog => QWidget, ça a l'air de marcher:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    import sys
    from PyQt5 import QtWidgets, QtGui, QtCore
     
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
    from matplotlib.figure import Figure
     
    import random
     
    class Window(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
     
            # a figure instance to plot on
            self.figure = Figure()
     
            # this is the Canvas Widget that displays the `figure`
            # it takes the `figure` instance as a parameter to __init__
            self.canvas = FigureCanvas(self.figure)
     
            # this is the Navigation widget
            # it takes the Canvas widget and a parent
            self.toolbar = NavigationToolbar(self.canvas, self)
     
            # Just some button connected to `plot` method
            self.button = QtWidgets.QPushButton('Plot')
            self.button.clicked.connect(self.plot)
     
            # set the layout
            layout = QtWidgets.QVBoxLayout()
            layout.addWidget(self.toolbar)
            layout.addWidget(self.canvas)
            layout.addWidget(self.button)
            self.setLayout(layout)
     
        def plot(self):
            ''' plot some random stuff '''
            # random data
            data = [random.random() for i in range(10)]
     
            # create an axis
            ax = self.figure.add_subplot(111)
     
            # discards the old graph
            ax.clear()
     
            # plot data
            ax.plot(data, '*-')
     
            # refresh canvas
            self.canvas.draw()
     
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
     
        main = Window()
        main.show()
     
        sys.exit(app.exec_())
    [edit]: il faut aussi changer dans les importations de matplotlib: backend_qt4agg => backend_qt5agg pour adapter à PyQt5. Le code ci-dessus est corrigé.
    Un expert est une personne qui a fait toutes les erreurs qui peuvent être faites, dans un domaine étroit... (Niels Bohr)
    Mes recettes python: http://www.jpvweb.com

  3. #3
    Membre régulier
    Homme Profil pro
    Analyste programmeur
    Inscrit en
    Septembre 2015
    Messages
    148
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : Algérie

    Informations professionnelles :
    Activité : Analyste programmeur
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2015
    Messages : 148
    Points : 92
    Points
    92
    Par défaut
    Merci Tyrtamos pour votre réponse, mais je voudrais inséré le graphe dans un QWidget qui fait partie la fenêtre principale de mon application.

  4. #4
    Expert éminent
    Avatar de tyrtamos
    Homme Profil pro
    Retraité
    Inscrit en
    Décembre 2007
    Messages
    4 462
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2007
    Messages : 4 462
    Points : 9 249
    Points
    9 249
    Billets dans le blog
    6
    Par défaut
    Bonjour,

    Ça ne change pas grand-chose. On laisse la classe précédente "Window" comme elle est, et on va simuler une fenêtre plus grande "Principal" qui va intégrer "Window" à l'intérieur. Et le graphique de matplotlib ne sera dessiné que dans ce QWidget interne à la grande fenêtre:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
     
     
    """
    https://stackoverflow.com/questions/12459811/how-to-embed-matplotlib-in-pyqt-for-dummies
    """
     
    import sys
    from PyQt5 import QtWidgets, QtGui, QtCore
     
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
    from matplotlib.figure import Figure
     
    import random
     
    class Window(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
     
            # a figure instance to plot on
            self.figure = Figure()
     
            # this is the Canvas Widget that displays the `figure`
            # it takes the `figure` instance as a parameter to __init__
            self.canvas = FigureCanvas(self.figure)
     
            # this is the Navigation widget
            # it takes the Canvas widget and a parent
            self.toolbar = NavigationToolbar(self.canvas, self)
     
            # Just some button connected to `plot` method
            self.button = QtWidgets.QPushButton('Plot')
            self.button.clicked.connect(self.plot)
     
            # set the layout
            layout = QtWidgets.QVBoxLayout()
            layout.addWidget(self.toolbar)
            layout.addWidget(self.canvas)
            layout.addWidget(self.button)
            self.setLayout(layout)
     
        def plot(self):
            ''' plot some random stuff '''
            # random data
            data = [random.random() for i in range(10)]
     
            # create an axis
            ax = self.figure.add_subplot(111)
     
            # discards the old graph
            ax.clear()
     
            # plot data
            ax.plot(data, '*-')
     
            # refresh canvas
            self.canvas.draw()
     
    class Principal(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
     
            self.resize(900, 900)
     
            self.window = Window(self)
            self.window.setGeometry(50, 50, 700, 700)
     
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
     
        main = Principal()
        main.show()
     
        sys.exit(app.exec_())
    Pour adapter, il suffira de définir dans la fenêtre "Principal" le QWidget "Window()" en remplacement de QtWidgets.QWidget().

    Il faudra bien sûr revoir aussi les instructions de dimensionnement (resize, setGeometry), que je n'ai ajoutées que pour mieux distinguer les 2 fenêtres l'une par rapport à l'autre.
    Un expert est une personne qui a fait toutes les erreurs qui peuvent être faites, dans un domaine étroit... (Niels Bohr)
    Mes recettes python: http://www.jpvweb.com

  5. #5
    Membre régulier
    Homme Profil pro
    Analyste programmeur
    Inscrit en
    Septembre 2015
    Messages
    148
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : Algérie

    Informations professionnelles :
    Activité : Analyste programmeur
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2015
    Messages : 148
    Points : 92
    Points
    92
    Par défaut
    Merci Tyrtamos pour votre réponse mais, je vois que je n'ai pas bien expliqué, je voudrais affiché mon graphe comme indiqué dans l'image
    ci-dessous :
    Nom : fenetre-principale-graph.jpg
Affichages : 2762
Taille : 83,8 Ko
    Merci

  6. #6
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 300
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 300
    Points : 6 780
    Points
    6 780
    Par défaut
    Salut,

    C'est exactement ce que Tyrtamos te montre. Lorsque tu crées ton interface avec le designer, tu places un simple widget à cet endroit et tu lui places un QLayout vide.

    Ensuite tu crées ton widget dans un autre fichier comme montré plus haut et tu le positionnes dans ce QLayout.

  7. #7
    Membre régulier
    Homme Profil pro
    Analyste programmeur
    Inscrit en
    Septembre 2015
    Messages
    148
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : Algérie

    Informations professionnelles :
    Activité : Analyste programmeur
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2015
    Messages : 148
    Points : 92
    Points
    92
    Par défaut
    Merci ça a marché.
    S'est l'occasion il faut en profiter
    Comment vider le premier graphe ? Car quand je choisi un autre client j'ai deux graphes dans le même QWidget comme ci-dessous :

    Nom : fenetre-principale-graph-2.jpg
Affichages : 2713
Taille : 81,7 Ko

    J'ai essayer :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    self.canvas.figure.clear()
    ou bien sans modification
    Merci

  8. #8
    Membre régulier
    Homme Profil pro
    Analyste programmeur
    Inscrit en
    Septembre 2015
    Messages
    148
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : Algérie

    Informations professionnelles :
    Activité : Analyste programmeur
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2015
    Messages : 148
    Points : 92
    Points
    92
    Par défaut
    Bonjour,

    Je viens de trouver la solution en ajoutant la fonction suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
     def vidergraph(self):
            while 1:
                child = self.ui.gridLayoutMpl.takeAt (0)
                if not child:
                    break
                    child.widget ().deleteLater ()
    Merci encore.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Intégrer un graphe JFreeChart dans une JSP avec Struts 2
    Par eiketchi-san dans le forum Servlets/JSP
    Réponses: 1
    Dernier message: 24/08/2012, 13h35
  2. Intégrer l'Open Graph protocol dans mon site
    Par aalex57 dans le forum Facebook
    Réponses: 4
    Dernier message: 10/06/2011, 16h16
  3. Intégrer un graphe dans un GUI
    Par bahru dans le forum Interfaces Graphiques
    Réponses: 7
    Dernier message: 09/06/2010, 08h32
  4. Réponses: 1
    Dernier message: 24/05/2007, 16h12
  5. intégrer un fichier image dans une base de donnée?
    Par Lody dans le forum Requêtes
    Réponses: 9
    Dernier message: 16/03/2006, 19h08

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo