def main():
    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_xlabel("X axis")
    ax.set_ylabel("Y axis")
    ax.grid()

    canvas_elem = g.Canvas(size=(640,
                                 480))  # get the canvas we'll be drawing on
    slider_elem = g.Slider(range=(0, 10000), size=(60, 10), orientation='h')
    # define the form layout
    layout = [[
        g.Text('Animated Matplotlib',
               size=(40, 1),
               justification='center',
               font='Helvetica 20')
    ], [canvas_elem], [slider_elem],
              [
                  g.ReadFormButton('Exit',
                                   size=(10, 2),
                                   pad=((280, 0), 3),
                                   font='Helvetica 14')
              ]]

    # create the form and show it without the plot
    form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI')
    form.Layout(layout)
    form.ReadNonBlocking()

    graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
    canvas = canvas_elem.TKCanvas

    dpts = [randint(0, 10) for x in range(10000)]
    for i in range(len(dpts)):
        button, values = form.ReadNonBlocking()
        if button is 'Exit' or values is None:
            exit(69)

        slider_elem.Update(i)
        ax.cla()
        ax.grid()
        DATA_POINTS_PER_SCREEN = 40
        ax.plot(range(DATA_POINTS_PER_SCREEN),
                dpts[i:i + DATA_POINTS_PER_SCREEN],
                color='purple')
        graph.draw()
        figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
        figure_w, figure_h = int(figure_w), int(figure_h)
        photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

        canvas.create_image(640 / 2, 480 / 2, image=photo)

        figure_canvas_agg = FigureCanvasAgg(fig)
        figure_canvas_agg.draw()

        # Unfortunately, there's no accessor for the pointer to the native renderer
        tkagg.blit(photo,
                   figure_canvas_agg.get_renderer()._renderer,
                   colormode=2)
Ejemplo n.º 2
0
            def draw_figure(canvas, figure, loc=(0, 0)):
                """ Draw a matplotlib figure onto a Tk canvas
            
                loc: location of top-left corner of figure on canvas in pixels.
            
                Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
                """
                figure_canvas_agg = FigureCanvasAgg(figure)
                figure_canvas_agg.draw()
                figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
                figure_w, figure_h = int(figure_w), int(figure_h)
                photo = PhotoImage(master=canvas,
                                   width=figure_w,
                                   height=figure_h)

                # Position: convert from top-left anchor to center anchor
                canvas.create_image(loc[0] + figure_w / 2,
                                    loc[1] + figure_h / 2,
                                    image=photo)

                # Unfortunately, there's no accessor for the pointer to the native renderer
                tkagg.blit(photo,
                           figure_canvas_agg.get_renderer()._renderer,
                           colormode=2)

                # Return a handle which contains a reference to the photo object
                # which must be kept live or else the picture disappears
                return photo
    def plot_figure(self, fig):
        if self._empty:
            self._empty = False
            self._canvas.delete(self._text_id)

        f_w = fig.get_window_extent().width
        f_h = fig.get_window_extent().height
        f_w, f_h = int(f_w), int(f_h)

        # draw out figure
        fca = FigureCanvasAgg(fig)
        fca.draw()

        f_w, f_h = fca.get_renderer().get_canvas_width_height()
        f_w, f_h = int(f_w), int(f_h)

        self._graph_h += f_h
        self._graph_w = max(self._graph_w, f_w)
        self._canvas.config(width=self._graph_w, height=self._graph_h)
        self._canvas.grid(row=0, column=0)

        photo = tk.PhotoImage(master=self._canvas, width=f_w, height=f_h)
        self._canvas.create_image(f_w/2, self._graph_h-f_h/2, image=photo)
        tkagg.blit(photo, fca.get_renderer()._renderer, colormode=2)
        self._root.update()

        self._figs.append(fig)
        self._fcas[fig] = fca
        self._photos[fig] = photo
Ejemplo n.º 4
0
def update_graph():
    slide = int(values['slider'])

    ax.cla()

    ax.hist(x, bins, alpha=0.5, label='x', color='pink')
    ax.hist(y, bins, alpha=0.5, label='y', color='deepskyblue')
    ax.legend(loc='upper right')

    ax.axvline(x=slide / 10, ymin=0, ymax=20)
    graph.draw()

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.image = photo
    canvas.create_image(640 * 1.3 / 2, 480 * 1.3 / 2, image=photo)
    figure_canvas_agg = FigureCanvasAgg(fig)
    figure_canvas_agg.draw()

    _backend_tk.blit(photo,
                     figure_canvas_agg.get_renderer()._renderer, (0, 1, 2, 3))

    #Do it all again for the ROC curve
    ax2.cla()

    ax2.plot(fpr, tpr, linewidth=3, color='deeppink')
    ax2.plot(fpr[slide], tpr[slide], '*', color='deepskyblue', markersize=20)
    ax2.set_xlabel("FPR")
    ax2.set_ylabel("TPR")
    graph2.draw()

    figure_x, figure_y, figure_w, figure_h = fig2.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas2, width=figure_w, height=figure_h)
    canvas2.image = photo
    canvas2.create_image(640 * 1.3 / 2, 480 * 1.3 / 2, image=photo)
    figure_canvas_agg2 = FigureCanvasAgg(fig2)
    figure_canvas_agg2.draw()

    _backend_tk.blit(photo,
                     figure_canvas_agg2.get_renderer()._renderer, (0, 1, 2, 3))
    ##and update the output values
    window['-OUTPUT_TPR-'].update(f'{tpr[slide]:.3f}')
    window['-OUTPUT_FPR-'].update(f'{fpr[slide]:.3f}')
    window['-OUTPUT_AUC-'].update(f'{auc:.3f}')
Ejemplo n.º 5
0
    def matplotCanvas(self):
        f = Figure(figsize=(5, 5), dpi=100)
        a = f.add_subplot(111)
        a.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5])

        canvas = FigureCanvasAgg(f, self)
        canvas.show()

        canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)
def draw_figure(canvas, figure, loc = (0,0)):

    figure_canvas_agg = FigureCanvasAgg(figure) 
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    return photo
def draw(fig, canvas):
    # Magic code that draws the figure onto the Canvas Element's canvas
    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.create_image(640 / 2, 480 / 2, image=photo)
    figure_canvas_agg = FigureCanvasAgg(fig)
    figure_canvas_agg.draw()
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    return photo
Ejemplo n.º 8
0
    def __checkCanvas(self):
        'leave dead True, not checking for window, just for canvas'
        #from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
        if self.win is not None: return
        if self.canvas is not None: return

        from matplotlib.backends.backend_tkagg import FigureCanvasAgg

        self.canvas = FigureCanvasAgg(self.f)
        if hasattr(self.a,'mouse_init'):
            self.a.mouse_init()
        return
Ejemplo n.º 9
0
def draw_figure(canvas, figure, loc=(0, 0)):
    # Convert plot figure into a photo object
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.image = photo
    canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    plt.close('all')
    return photo
def draw_figure(canvas, figure, loc=(0, 0)):
    """ Draw a matplotlib figure onto a Tk canvas
    loc: location of top-left corner of figure on canvas in pixels.
    Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
    """
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    return photo
Ejemplo n.º 11
0
def create_figure(size=None,
                  shape=None,
                  pyplot=True,
                  dpi=100,
                  **kwargs) -> Figure:
    figsize = get_figsize(size, shape)

    if pyplot:
        figure = plt.figure(figsize=figsize)
    else:
        figure = Figure(figsize=figsize, dpi=dpi)
        FigureCanvasAgg(figure)

    return figure
Ejemplo n.º 12
0
def draw_figure(canvas, figure, loc=(0, 0)):
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = PhotoImage(master=canvas, width=figure_w, height=figure_h)

    canvas.create_image(loc[0] + figure_w / 2,
                        loc[1] + figure_h / 2,
                        image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)

    #return handle containing reference to photo - must be kept live else picture disappears
    return photo
Ejemplo n.º 13
0
 def _plot_pic(self, figure, gait_canvas):
     """
     在pysimplegui上绘制plot。调用这个函数必须接受返回值,不接受的话无法绘图,我也不知道为啥,辣鸡tkinter
     :param gait_canvas:
     :param figure:
     :return:
     """
     figure_canvas_agg = FigureCanvasAgg(figure)
     figure_canvas_agg.draw()
     figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
     figure_w, figure_h = int(figure_w), int(figure_h)
     photo = tk.PhotoImage(master=gait_canvas, width=figure_w, height=figure_h)
     gait_canvas.create_image(figure_w / 2, figure_h / 2, image=photo)
     tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
     return photo
Ejemplo n.º 14
0
 def __init__(self, title="Plotting Window", visible=True):
     plt.Figure.__init__(self)
     self.add_subplot(111)
     self.visible = visible
     self._destroyed = False
     if self.visible:  # If visible, use Tk's frontend
         # Use the correct method to create a window, then set the tk_started flag to True
         self.canvas = FigureCanvasTkAgg(
             self,
             Toplevel() if self.__class__._tk_started else Tk())
         self.__class__._tk_started = True
         self.title(title)
         self.make_window()
         self.show()
     else:
         self.canvas = FigureCanvasAgg(self)
Ejemplo n.º 15
0
def figure_to_image(figure):
    """
    Draws the previously created "figure" in the supplied Image Element
    :param element: an Image Element
    :param figure: a Matplotlib figure
    :return: The figure canvas
    """

    plt.close('all')  # erases previously drawn plots
    canv = FigureCanvasAgg(figure)
    buf = io.BytesIO()
    canv.print_figure(buf, format='png')
    if buf is None:
        return None
    buf.seek(0)
    return buf.read()
 def update_graph():
     graph.draw()
     figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
     figure_w, figure_h = int(figure_w), int(figure_h)
     photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
     canvas.image = photo
     canvas.pack(fill="both", expand=True)
     canvas.create_image(fig.get_figwidth() * 100 / 2,
                         fig.get_figheight() * 100 / 2,
                         image=photo)
     #canvas.update(size=(size(window_g)[0],size(window_g)[1]))
     figure_canvas_agg = FigureCanvasAgg(fig)
     figure_canvas_agg.draw()
     _backend_tk.blit(photo,
                      figure_canvas_agg.get_renderer()._renderer,
                      (0, 1, 2, 3))
Ejemplo n.º 17
0
def main():
    # define the form layout
    layout = [[sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')],
              [sg.Canvas(size=(640, 480), key='canvas')],
              [sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]

    # create the form and show it without the plot
    window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize()

    canvas_elem = window.FindElement('canvas')
    canvas = canvas_elem.TKCanvas

    while True:
        event, values = window.Read(timeout=10)
        if event in ('Exit', None):
            exit(69)

        def PyplotScatterWithLegend():
            import matplotlib.pyplot as plt
            from numpy.random import rand

            fig, ax = plt.subplots()
            for color in ['red', 'green', 'blue']:
                n = 750
                x, y = rand(2, n)
                scale = 200.0 * rand(n)
                ax.scatter(x, y, c=color, s=scale, label=color,
                           alpha=0.3, edgecolors='none')

            ax.legend()
            ax.grid(True)
            return fig

        fig = PyplotScatterWithLegend()

        figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
        figure_w, figure_h = int(figure_w), int(figure_h)
        photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

        canvas.create_image(640/2, 480/2, image=photo)

        figure_canvas_agg = FigureCanvasAgg(fig)
        figure_canvas_agg.draw()

        # Unfortunately, there's no accessor for the pointer to the native renderer
        tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
Ejemplo n.º 18
0
def draw_figure(figure):
    """
    Draws the previously created "figure" in the supplied Image Element

    :param figure: a Matplotlib figure
    :return: BytesIO object
    """

    plt.close('all')  # erases previously drawn plots
    canv = FigureCanvasAgg(figure)
    buf = io.BytesIO()
    canv.print_figure(buf, format='png')
    if buf is not None:
        buf.seek(0)
        # element.update(data=buf.read())
        return buf
    else:
        return None
Ejemplo n.º 19
0
def drawFigure(canvas, figure, loc=(0, 0)):
    '''
    PARAMETERS:
        canvas: tkinter.Canvas object
        figure: matplotlib figure object
        loc: 2-tuple (default: (0, 0))

    RETURN: tkagg image object
    '''
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.create_image(loc[0] + figure_w / 2,
                        loc[1] + figure_h / 2,
                        image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    return photo
Ejemplo n.º 20
0
def main():
    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_xlabel("X axis")
    ax.set_ylabel("Y axis")
    ax.grid()

    layout = [[g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')],
              [g.Canvas(size=(640, 480), key='canvas')],
              [g.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]

    # create the form and show it without the plot  
    form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI')
    form.Layout(layout)
    form.ReadNonBlocking()

    canvas_elem = form.FindElement('canvas')

    graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
    canvas = canvas_elem.TKCanvas

    dpts = [randint(0, 10) for x in range(10000)]
    for i in range(len(dpts)):
        button, values = form.ReadNonBlocking()
        if button is 'Exit' or values is None:
            exit(69)

        ax.cla()
        ax.grid()

        ax.plot(range(20), dpts[i:i + 20], color='purple')
        graph.draw()
        figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
        figure_w, figure_h = int(figure_w), int(figure_h)
        photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

        canvas.create_image(640 / 2, 480 / 2, image=photo)

        figure_canvas_agg = FigureCanvasAgg(fig)
        figure_canvas_agg.draw()

        tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
 def draw_figure(self, canvas, loc=(650, 140)):
     #Draw a matplotlib figure onto a Tk canvas
     #loc: location of top-left corner of figure on canvas in pixels.
     #Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
     self.figure_canvas_agg = FigureCanvasAgg(self.figure)
     self.figure_canvas_agg.draw()
     self.figure_x, self.figure_y, self.figure_w, self.figure_h = (
         self.figure.bbox.bounds)
     self.figure_w, self.figure_h = int(self.figure_w), int(self.figure_h)
     self.photo = PhotoImage(master=canvas,
                             width=self.figure_w,
                             height=self.figure_h)
     # Position: convert from top-left anchor to center anchor
     canvas.delete(self.graph)
     self.graph = canvas.create_image(loc[0] + self.figure_w / 2,
                                      loc[1] + self.figure_h / 2,
                                      image=self.photo)
     # Unfortunatly, there's no accessor for the pointer to the native renderer
     tkagg.blit(self.photo,
                self.figure_canvas_agg.get_renderer()._renderer,
                colormode=2)
Ejemplo n.º 22
0
                   layout)
window.Finalize(
)  # needed to access the canvas element prior to reading the window

canvas_elem = window['canvas']

graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
canvas = canvas_elem.TKCanvas

dpts = [randint(0, 10) for x in range(10000)]
# Our event loop
for i in range(len(dpts)):
    event, values = window.read(timeout=20)
    if event == 'Exit' or event is None:
        exit(69)

    ax.cla()
    ax.grid()

    ax.plot(range(20), dpts[i:i + 20], color='purple')
    graph.draw()
    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

    canvas.create_image(640 / 2, 480 / 2, image=photo)

    figure_canvas_agg = FigureCanvasAgg(fig)
    figure_canvas_agg.draw()

    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
Ejemplo n.º 23
0
def confusion_matrix(cm, labels, normalize=False):
    """
    Create confusion matrix image plot

    Parameters:
        cm                              : Confusion matrix
        labels                          : Axis labels (strings)

    Returns:
        data                            : Confusion matrix image buffer
    """
    if normalize:
        cm = cm.astype('float') * 10.0 / cm.sum(axis=1)[:, np.newaxis]
        cm = np.nan_to_num(cm, copy=True)
        cm = cm.astype('int')

    np.set_printoptions(precision=2)

    fig = matfig.Figure(figsize=(5, 5), dpi=96, facecolor='w', edgecolor='k')
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.imshow(cm, cmap='jet')

    strlabels = map(str, labels)
    classes = [
        re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x)
        for x in strlabels
    ]
    classes = ['\n'.join(wrap(cl, 40)) for cl in classes]

    tick_marks = np.arange(len(classes))

    FONTSIZE = 12
    ax.set_xlabel('Predicted', fontsize=FONTSIZE)
    ax.set_xticks(tick_marks)
    rotation = 90 if len(max(classes, key=len)) > 2 else 0
    ax.set_xticklabels(classes,
                       fontsize=FONTSIZE,
                       rotation=rotation,
                       ha='center')
    ax.xaxis.set_label_position('bottom')
    ax.xaxis.tick_bottom()

    ax.set_ylabel('Actual', fontsize=FONTSIZE)
    ax.set_yticks(tick_marks)
    ax.set_yticklabels(classes, fontsize=FONTSIZE, va='center')
    ax.yaxis.set_label_position('left')
    ax.yaxis.tick_left()

    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        ax.text(j,
                i,
                format(cm[i, j], 'd') if cm[i, j] != 0 else '.',
                horizontalalignment='center',
                fontsize=FONTSIZE,
                verticalalignment='center',
                color='white')
    fig.set_tight_layout(True)

    canvas.draw()
    data = np.fromstring(canvas.tostring_rgb(), dtype=np.uint8, sep='')
    data = data.reshape(canvas.get_width_height()[::-1] + (3, ))
    return data