Animation graph with plotly and PyQt5

I’m trying to produce an animated graph with plotly and display it in pyqt5 windows.

code :

import sys
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView
import plotly.io as pio

# Génération des données (exemple simplifié)
x_range = np.arange(1, 1251)  # x allant de 1 Ă  1250
t_range = np.arange(0, 3600)  # t allant de 0 Ă  3599 secondes

# Fonction fictive pour générer des vitesses
def generate_speed(x, t):
    # Exemple : une vitesse qui varie sinusoĂŻdalement
    return 50 + 50 * np.sin(2 * np.pi * x / 1250 + 2 * np.pi * t / 3600)

# Créer les données dans un DataFrame
data = {'x': [], 't': [], 'vitesse': []}
for t in t_range:
    for x in x_range:
        data['x'].append(x)
        data['t'].append(t)
        data['vitesse'].append(generate_speed(x, t))

df = pd.DataFrame(data)

# Création des frames pour l'animation
frames = []
for t in t_range:
    frame_data = df[df['t'] == t]
    frames.append(go.Frame(data=[go.Scatter(x=frame_data['x'], y=frame_data['vitesse'],
                                            mode='lines', name=f't={t}s')],
                           name=str(t)))

# Données initiales pour le graphe
initial_data = df[df['t'] == 0]

# Création de la figure
fig = go.Figure(
    data=[go.Scatter(x=initial_data['x'], y=initial_data['vitesse'],
                     mode='lines', name='Initial')],
    layout=go.Layout(
        title="Vitesse en fonction de x avec le temps",
        xaxis=dict(title='x'),
        yaxis=dict(title='Vitesse'),
        updatemenus=[{
            'buttons': [
                {
                    'args': [None, {'frame': {'duration': 10, 'redraw': True}, 'fromcurrent': True}],
                    'label': 'Play',
                    'method': 'animate'
                },
                {
                    'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',
                                      'transition': {'duration': 0}}],
                    'label': 'Pause',
                    'method': 'animate'
                }
            ],
            'direction': 'left',
            'pad': {'r': 10, 't': 87},
            'showactive': False,
            'type': 'buttons',
            'x': 0.1,
            'xanchor': 'right',
            'y': 0,
            'yanchor': 'top'
        }]
    ),
    frames=frames
)

# Convertir la figure en HTML
html = pio.to_html(fig, full_html=False)
print(" Affichage terminé")
# Créer l'application PyQt5
class PlotlyViewer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Plotly Viewer")
        self.setGeometry(100, 100, 800, 600)
        self.initUI()

    def initUI(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        web_view = QWebEngineView()
        web_view.setHtml(html)
        layout.addWidget(web_view)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    viewer = PlotlyViewer()
    viewer.show()
    sys.exit(app.exec_())

when running the code, I have nothing displayed in my Pyqt5 window.

But if i want to display a simple message like “Hello, World!” , it’s worked.

Thank you for your help.

Hey @Didie welcome to the forums.

Unfortunately we don’t get a lot of questions regarding pyqt :frowning: