How to use matplotlib animation within kivy

2019-09-12 15:37发布

问题:

I want to show a live diagram of acceleration sensor data. Kivy is the framework and matplotlib should be used for the plot. I can easily integrate a static plot in my app screens, however I wasn't successful in using the matplotlib animation method. How can I do this? Based on an example I found (not made for kivy) the following is my code so far.

class FigGraphLive(BoxLayout):

def __init__(self, **kwargs):
    super(FigResultPropGraphLive, self).__init__(**kwargs)

    fig = Figure(figsize=(3, 1), facecolor='none', dpi=90)
    ax = fig.add_subplot(111)
    ax.set_axis_bgcolor('none')
    ax.spines['bottom'].set_color('white')
    ax.spines['top'].set_color('white')
    ax.spines['left'].set_color('white')
    ax.spines['right'].set_color('white')
    xa = ax.xaxis                  
    ya = ax.yaxis
    xa.set_tick_params(labelcolor='white')
    xa.set_tick_params(color='white')
    ya.set_tick_params(labelcolor='white')
    ya.set_tick_params(color='white')

    self.valx = np.zeros(0)
    self.valy = np.zeros(0)
    self.valz = np.zeros(0)
    self.time = np.zeros(0)
    plxax = ax.plot(self.time, self.valx, color='blue', label='X-Axis')
    plyax = ax.plot(self.time, self.valy, color='red', label='Y-Axis')
    plzax = ax.plot(self.time, self.valz, color='green', label='Z-Axis')

    leg = ax.legend()
    leg.get_frame().set_alpha(0.4)

    self.plxmin = 0.0
    self.plxmax = 10.0
    self.plx = 0.0

    simulation = mplanimation.FuncAnimation(fig, self.updateGraph, blit=False, frames=200, interval=50, repeat=False)

    figcanvas = FigureCanvas(fig)
    figcanvas.draw()

    self.create_plot(figcanvas)

def updateGraph(self):
    self.valx = np.append(self.valx, np.random.rand() * 4)
    self.valy = np.append(self.valx, np.random.rand() * 4)
    self.valz = np.append(self.valx, np.random.rand() * 0.5)

    self.plx += 0.05

    if self.plx >= self.plxmax - 1.00:
        plxax.axes.set_xlim(self.plx - self.plxmax + 1.0, x + 1.0)
        plyax.axes.set_xlim(self.plx - self.plxmax + 1.0, x + 1.0)
        plzax.axes.set_xlim(self.plx - self.plxmax + 1.0, x + 1.0)

    return plxax, plyax, plzax

def create_plot(self, figcanvas):
    self.add_widget(figcanvas)

回答1:

You can use matplotlib integration example from kivy garden: https://github.com/kivy-garden/garden.matplotlib


Another option is https://github.com/kivy-garden/garden.graph , with an animated presentation embedded into init.py file.