Matplotlib adding to existing plots

Date: March 5th 2016
Last updated: March 5th 2016

In this example, each click on the play button renders additional attributes to a figure. I didn't arrive at this intentionally. I was actually trying to replace each figure when the play button was clicked. I imagine that this code will come in handy at some point in the future.

Keeps the same graph 'window'.
Plots new bins overtop of existing plot.

import matplotlib
import matplotlib.pyplot as plt
from import FigureCanvas
import kivy
from import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
import matplotlib.mlab as mlab
from random import gauss
import random
import numpy as np

class DrawPlot(BoxLayout):
    def __init__(self, **kwargs):
        super(DrawPlot, self).__init__(**kwargs)

    def get_data(self):
        x = [gauss(100, 15) for i in range(100)]
        return x

    def draw_plot_frame(self):
        self.fig, = plt.subplots()[0, 200])
        canvas =  FigureCanvas(figure=self.fig)
        self.add_widget(canvas, 1) #<===== builds initial plot window

    def plot(self):
        x = self.get_data()
        colorlist = ['blue','red','green','yellow']
        facecolor = colorlist[random.randint(0,3)]
        n, bins, patches =, 50, normed=1, facecolor=facecolor, alpha=0.3)
        pdf = mlab.normpdf(bins, 100, 15), pdf, 'r-', linewidth=2)
        canvas = self.fig.canvas
        canvas.draw() #<===== this adds stuff from plot() to the existing plot window

class SampleApp(App):
    def build(self):
        return DrawPlot()

if __name__ == '__main__':


#:kivy 1.9.1
    orientation: 'vertical'

        orientation: 'vertical'
        size_hint: 1, None
        height: main_title.height

            id: main_title
            text: "Plotting using Matplotlib in Kivy"
            font_size: '35sp'
            size_hint: 1, None
            height: self.height

            size_hint_x: 0.8
            source: root.draw_plot_frame() #<==== creates initial plot window

        orientation: 'horizontal'
        size_hint: 1, None
        height: playbutton.height
            id: playbutton
            text: 'play'
            size_hint: 1, None
            height: self.height
            on_press: root.plot() #<==== add stuff to existing plot

            text: 'reset'
            size_hint: 1, None
            text: 'quit'
            size_hint: 1, None


The following screenshot is produced when running the main program.
Opening window screenshot

After clicking on the play button several times I got the following image. Note that the colours are chosen at random (blue, red, green, yellow) to fill in the histogram bins. Reset and quit buttons do nothing.

Adding stuff to a plot window kivy screenshot

results matching ""

    No results matching ""