Animación Matplotlib dentro de su propia interfaz gráfica de usuario PyQt4
Estoy escribiendo software en Python. Necesito incrustar una animación de tiempo Matplotlib en una GUI propia. Aquí hay algunos detalles más sobre ellos:
1. La GUILa GUI también está escrita en Python, usando la biblioteca PyQt4. Mi GUI no es muy diferente de las GUI comunes que puedes encontrar en la red. Yo solo subclaseQtGui.QMainWindow y agregue algunos botones, un diseño, ...
2. La animaciónLa animación de Matplotlib se basa enanimation.TimedAnimation clase. Aquí está el código para la animación:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.animation as animation
class CustomGraph(animation.TimedAnimation):
def __init__(self):
self.n = np.linspace(0, 1000, 1001)
self.y = 1.5 + np.sin(self.n/20)
#self.y = np.zeros(self.n.size)
# The window
self.fig = plt.figure()
ax1 = self.fig.add_subplot(1, 2, 1)
self.mngr = plt.get_current_fig_manager()
self.mngr.window.setGeometry(50,100,2000, 800)
# ax1 settings
ax1.set_xlabel('time')
ax1.set_ylabel('raw data')
self.line1 = Line2D([], [], color='blue')
ax1.add_line(self.line1)
ax1.set_xlim(0, 1000)
ax1.set_ylim(0, 4)
animation.TimedAnimation.__init__(self, self.fig, interval=20, blit=True)
def _draw_frame(self, framedata):
i = framedata
print(i)
self.line1.set_data(self.n[ 0 : i ], self.y[ 0 : i ])
self._drawn_artists = [self.line1]
def new_frame_seq(self):
return iter(range(self.n.size))
def _init_draw(self):
lines = [self.line1]
for l in lines:
l.set_data([], [])
def showMyAnimation(self):
plt.show()
''' End Class '''
if __name__== '__main__':
print("Define myGraph")
myGraph = CustomGraph()
myGraph.showMyAnimation()
Este código produce una animación simple:
La animación en sí funciona bien. Ejecute el código, la animación aparece en una pequeña ventana y comienza a ejecutarse. Pero, ¿cómo incrusto la animación en mi propia GUI hecha por mí?
3. Incrustar la animación en una GUI propiaHe investigado un poco para descubrirlo. Aquí hay algunas cosas que probé. He agregado el siguiente código al archivo python. Tenga en cuenta que este código agregado es en realidad una definición de clase adicional:
from PyQt4 import QtGui
from PyQt4 import QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
class CustomFigCanvas(FigureCanvas):
def __init__(self):
self.myGraph = CustomGraph()
FigureCanvas.__init__(self, self.myGraph.fig)
Lo que intento hacer aquí es incrustar elCustomGraph () objeto, que es esencialmente mi animación, en unFigura Lienzo.
Escribí mi GUI en otro archivo de Python (pero aún en la misma carpeta). Normalmente puedo agregar widgets a mi GUI. Creo que un objeto de la claseCustomFigCanvas (..) es un widget a través de la herencia. Entonces, esto es lo que intento en mi GUI:
..
myFigCanvas = CustomFigCanvas()
self.myLayout.addWidget(myFigCanvas)
..
Funciona hasta cierto punto. De hecho, me aparece una figura en mi GUI. Pero la figura está vacía. La animación no se ejecuta:
Y hay incluso otro fenómeno extraño que está sucediendo. Mi GUI muestra esta figura vacía, pero obtengo simultáneamente una ventana emergente Matplotlib normal con mi figura de animación. Además, esta animación no se está ejecutando.
Claramente hay algo que me estoy perdiendo aquí. Por favor, ayúdame a resolver este problema. Agradezco mucho toda la ayuda.