示例#1
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 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)
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
示例#5
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
示例#6
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
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
示例#8
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
示例#9
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
示例#10
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)
 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))
示例#12
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()
示例#13
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}')
示例#14
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)
示例#15
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
示例#16
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)
示例#17
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
示例#18
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
 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)
    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
示例#21
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
示例#22
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)
示例#23
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)
示例#24
0
class PlotWindow(plt.Figure):
    """ Tk window containing a matplotlib plot. In addition to the functions described below, also supports all
    functions contained in matplotlib's Axes_ and Figure_ objects.

    .. _Axes: http://matplotlib.sourceforge.net/api/axes_api.html
    .. _Figure: http://matplotlib.sourceforge.net/api/figure_api.html

    Args:
        title (str): The title to be used for the initial window.
        visible (bool): Whether to actually display a Tk window (set to `False` to create and save plots without
            displaying a window).
        standalone (bool, optional): If `True`, plot windows will be kept open by keeping the Tk event loop alive.
    """
    _tk_started = False  # If this is True, uses Toplevel to create the window, otherwise creates a main window

    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)

    def make_window(self):
        """ Pack the plot and matplotlib toolbar into the containing Tk window.

        This method is called during initialization and it is unlikely you will need to call it elsewhere.
        """
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        self.toolbar = NavigationToolbar2Tk(self.canvas, self.canvas._master)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

    def destroy(self):
        """ Destroy the Tk window.

        Note that after calling this method (or manually closing the Tk window), this :py:class:`PlotWindow` cannot be
        used.
        """
        try:  # Try and destroy the window
            self.canvas._master.destroy()
        except:
            pass  # It was probably already destroyed
        self._destroyed = True

    def clear(self):
        """ Clear the plot, keeping the Tk window active. """
        self.clf()
        self.add_subplot(111)
        if self.visible:
            self.show()

    def show(self):
        """ Update the canvas image (automatically called for most functions). """
        try:
            self.canvas.draw()
        except Exception:
            self.canvas.show()

    def __getattr__(self, name):
        show = True
        if name.startswith('_'):
            name = name[1:]
            show = False
        if hasattr(self.axes[0], name):
            attr = getattr(self.axes[0], name)
            if hasattr(attr, '__call__'):
                if show:

                    def tmp(*args, **kwargs):
                        out = attr(*args, **kwargs)
                        if self.visible:
                            self.show()
                        return out

                    return tmp
                else:
                    return attr
            else:
                return attr
        else:
            raise AttributeError("PlotWindow object has no attribute %s" %
                                 name)

    def title(self, title):
        """ Change the title of the Tk window """
        self.canvas._master.title(title)

    def legend(self, *args):
        """ Create a legend for the figure (requires plots to have been made with labels) """
        handles, labels = self.axes[0].get_legend_handles_labels()
        self.axes[0].legend(handles, labels)
        if self.visible:
            self.show()

    def save(self, fname, **kwargs):
        """ Save this plot as an image.  File type determined by extension of filename passed in.

        See documentation for savefig_.

        .. _savefig: http://matplotlib.sourceforge.net/api/figure_api.html

        Args:
            fname: The file to create, which may be a path or a file-like object.
        """
        self.savefig(fname, **kwargs)

    def stay(self):
        """ Start the Tkinter window's main loop (e.g., to keep the plot open at the end of the execution of a script)
        """
        self.canvas._master.mainloop()

    def plot(self, *args, **kwargs):
        """ Plot lines and/or markers to the Axes. See pyplot_ for more information.

        .. _pyplot: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
        """
        self.__getattr__('plot')(*args, **kwargs)
示例#25
0
    event, values = window.Read(timeout=20)
    if event == 'Leer':
        ax.cla()
        ax.grid()

        data, tdata = spec.read()
        ax.plot(frequency, data, 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)
    elif event in ['Laser', 'Led']:
        if not source_active[event.lower()]:
            spec.start_source(event.lower())
            source_active[event.lower()] = True
        else:
            spec.stop_source(event.lower())
            source_active[event.lower()] = False
    elif event == 'Guardar':
        filename = values['filename']
        if os.path.isfile(filename):
示例#26
0
class PlotWrap(object):
    __debug = False
    __keyArgDict =  {
        'title' : None,
        'winTitle' : None,
        'xlabel' : None,
        'xticks' : None,
        'ylabel' : None,
        'yticks' : None,
        'ylog' : False, 
        'xlog' : False, 
        'ybound' : (None,None),
        'xbound' : (None,None),
        'legend' : None,
        'style' : None,
        'aging' : None,
        'alphaMin' : 0.02,
        'agingCull' : True,
        'bball' : None,
        'accum' : False,
        'showByDefault' : True,
        'makeWinByDefault': True,
        'axes' :  None,
        'axesRect' :  None,
        'axprops' :  {},
        'figsize' : (5,4),
        'dpi' : 100,
        'window' :  None,
        'as3D' : False,
        }
    def __init__(self,
                 **keyArgs
                 ):
        
        # defaults
        for parm, val in self.__keyArgDict.iteritems():
            self.__setattr__(parm, val)
        #
        # parse keyword args
        for keyArg in self.getKeyArgList():
            if keyArgs.has_key(keyArg):
                self.__setattr__(keyArg, keyArgs.pop(keyArg))
        if len(keyArgs) > 0:
            raise RuntimeError, 'unparsed keyword args : '+str(keyArgs)
        #
        window = self.window
        del self.window
        #
        self.x_accum = self.accum
        del self.accum
        #
        axes = self.axes
        del self.axes
        
        self.x_prev = None
        self.x_store = [[],[]]

        self.win = None
        self.a   = None
        self.canvas = None
        
        self.ownCanvas = True
        if window is None:
            self.ownCanvas = True
            'checking self.showByDefault here causes trouble because it is hard to attach a figure to a window later for a general backend ***'
            if self.showByDefault or self.makeWinByDefault:
                # 'go ahead and make a window, using PlotWinP to increase backend flexibility'
                # self.win    = ...PlotWinP(as3D=self.as3D, figsize=self.figsize, dpi=self.dpi)
                # self.a      = self.win.getAxes(0)
                # self.f      = self.win.getFigure()
                # self.canvas = self.win.getCanvas()
                # self.a.set_autoscale_on(True)
                self.__checkWin()
                self.f = self.win.f
            else:
                from matplotlib.figure import Figure
                self.f = Figure(figsize=self.figsize, dpi=self.dpi)
            if self.as3D:
                import mpl_toolkits.mplot3d.axes3d as p3
                self.a = p3.Axes3D(self.f)
            else:
                if self.axesRect is None:
                    self.a = self.f.add_subplot(1, 1, 1, **self.axprops)
                else:
                    self.a = self.f.add_axes(self.axesRect, **self.axprops)
                
            if axes is not None:
                raise RuntimeError, 'do not specify axes when have not passed a window'
        else:
            self.ownCanvas = False
            self.win = window
            self.canvas = self.win.getCanvas()
            self.f = self.win.getFigure()
            if axes is None:
                if self.__debug: print 'using axprops: '+str(self.axprops)
                self.a = self.win.getNextAxes(rect=self.axesRect, attachPW=self, **self.axprops)
            elif isinstance(axes, int):
                self.a = self.win.getAxes(axes, **self.axprops)
            else:
                self.a = axes
        #
        self.clear() # sets labels and so forth

        # self.style = style # can be None
        # self.bball = bball # can be None
        #
        #self.aging = aging
        #self.agingCull = agingCull
        #self.alphaMin = alphaMin
        self.agingNumAge = -1
        if self.aging is not None:
            from math import log
            self.agingNumAge = max(int(log(self.alphaMin)/log(self.aging)),1)
        self.plotProps = {}
        # self.lineListList = [] # not needed, can, and should, use a.lines
        
        self.asImIJ = False
        # self.transform = None
        self.axIm = None
        self.__colorbar = None

        return
    def add_axes(self, arect, kwAddAxes={}, **kwarg):
        aNew = self.f.add_axes(arect, **kwAddAxes)
        # self.a.set_position((0.05, 0.05, 0.45, 0.9))
        new = self.__class__(window=self.win, axes=aNew, **kwarg)
        return new
    @classmethod
    def popKeyArgs(cls, kwargs):
        retval = {}
        for key in cls.getKeyArgList():
            if kwargs.has_key(key):
                retval[key] = kwargs.pop(key)
        return retval
    @classmethod
    def getKeyArgList(cls):
        return cls.__keyArgDict.keys()
    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

    def __checkWin(self):
        if self.win is not None: return
        winTitle = self.winTitle
        if winTitle is None : winTitle = self.title
        if winTitle is None : winTitle = 'plotWin'
        if hasattr(self,'f'):
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, figure=self.f, axesList=[self.a])
        else:
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, axesList=[self.a])
        #self.win = PlotWinP(title=winTitle, figure=self.f, axes=self.a)
        self.canvas = self.win.getCanvas()
        return
    def removeLines(self):
        lines = self.a.get_lines()
        for line in lines:
            line.remove()
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def show(self):
        self.__checkWin()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if hasattr(self.a,'mouse_init'):
            self.a.mouse_init()
        if hasattr(self.f, 'show'):
            self.f.show()
        elif hasattr(self.canvas, 'show'):
            self.canvas.show()
        else:
            raise RuntimeError, 'do not know how to do show'
        return
    def clear(self):
        self.asImIJ = False
        self.axIm = None
        # self.transform = None
        self.x_prev = None
        self.__colorbar = None
        self.x_store = [[],[]]
        if self.showByDefault:
            self.__checkWin()
        if self.a is not None:
            if hasattr(self.a,'mouse_init'):
                'doing a.clear() seems like it causes trouble with plotting collections?' 
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
            else:
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
        if self.xticks is not None:
            self.a.set_xticks(self.xticks)
        if self.title is not None:
            self.a.set_title(self.title)
        if self.xlabel is not None:
            self.a.set_xlabel(self.xlabel)  # r'X axis label $\mu\mbox{lentz}$'
            if self.win is not None:
                'make some room for the label'
                self.win.haveXLabels()
        if self.yticks is not None:
            self.a.set_yticks(self.yticks)
        if self.xlog: self.a.set_xscale('log')
        if self.ylog: self.a.set_yscale('log')
        #self.a.set_ybound(self.ybound)
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if self.ylabel is not None:
            self.a.set_ylabel(self.ylabel)
            if self.win is not None:
                'make some room for the label'
                self.win.haveYLabels()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if self.a is not None:
            self.a.set_autoscale_on(True)
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def setLegend(self, val=True):
        # if self.legend is None:
        #     self.legend = True
        # if val is not None:
        #     self.legend = val
        self.legend = val
        return
    def save(self, **keyArgs):
        '''make hardcopy of the current figure;
        specify filename or prefix keyword argument
        '''
        import numpy as num
        
        filename = None
        prefix = None
        if keyArgs.has_key('filename'):
            filename = keyArgs.pop('filename')
        if keyArgs.has_key('prefix'):
            prefix = keyArgs.pop('prefix')
            filename = prefix+'.pdf' # .eps
        
        if prefix is not None:
            'export data'
            if len(self.x_store[0]) > 0:
                dataFilename = prefix+'.data'
                from hexrd import arrayUtil
                try:
                    arrayUtil.writeArray(dataFilename, num.array(self.x_store))
                except:
                    import sys
                    print 'problem writing to '+dataFilename+' : '+str(self.x_store)
                    sys.exit(1)
        
        if not self.ownCanvas:
            if self.__debug:
                print 'skipping print_figure because this plot does not own its canvas'
        else:
            self.__checkCanvas()
            if filename is None:
                raise RuntimeError, 'need filename or prefix entry in keyArgs'
            #self.canvas.print_figure(filename, **keyArgs)
            self.f.savefig(filename, **keyArgs)
        
        return
    def destroy(self):
        'does not clean up self.a, just kills the window if this plot owns the window'
        if self.ownCanvas and self.win is not None:
            self.win.destroy()
        return
    def drawBBox(self, bbox, **kwargs):
        import numpy as num
        bbox_x = bbox[0]
        bbox_y = bbox[1]
        xBBox = num.array([ bbox_x[0], bbox_x[1], bbox_x[1], bbox_x[0], bbox_x[0] ])
        yBBox = num.array([ bbox_y[0], bbox_y[0], bbox_y[1], bbox_y[1], bbox_y[0] ])
        'go through call, instead of callXY, in case of asImIJ'
        self.__call__(xBBox, yBBox, **kwargs)
        return
    def __call__(self, *args, **keyArgs):
        import numpy as num
        noShow = False
        retVal = None
        # if keyArgs.has_key('transform'):
        #     'pop transform so that can keep it for other (overlaid) plots'
        #     self.transform = keyArgs.pop('transform')
        if keyArgs.has_key('noShow'):
            noShow = keyArgs.pop('noShow')
        if len(args) == 2:
            alphas = None
            if self.asImIJ:
                x = args[1]
                y = args[0]
            else:
                x = args[0]
                y = args[1]
            if keyArgs.has_key('alphas'):
                alphas = keyArgs.pop('alphas')
                assert len(args) == 2, 'len(args) != 2'
                assert len(alphas) == len(y), 'len(alphas) != len(y)'
                self.x_prev = None
                for iX in range(len(x)):
                    self.callXY([x[iX]],[y[iX]],alpha=alphas[iX],**keyArgs)
            else:
                self.callXY(x, y, **keyArgs)
        elif len(args) == 3:
            X = args[0]; Y = args[1]; data = args[2];
            cont = self.callContour(X, Y, data, **keyArgs)
            retVal = cont
        elif len(args) == 1 and isinstance(args[0],str):
            'interpret string as name of a file to plot in axes'
            filename = args[0]
            im = self.callImage(filename, **keyArgs)
            retVal = im
        elif len(args) == 1 and isinstance(args[0],num.ndarray):
            im = self.callIm(args[0], **keyArgs)
            retVal = im
        else:
            raise RuntimeError, 'do not know what to do with args'
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if not noShow:
            if self.showByDefault:
                self.show()
        return retVal
    def callImage(self, filename, 
                  **keyArgs):
        import Image
        im = Image.open(filename)
        s = im.tostring() # convert PIL image -> string
        import numpy as num
        rgb = num.fromstring(s, dtype=num.uint8).astype(num.float)/255.0 # convert string -> array of floats
        rgb = num.resize(rgb, (im.size[1], im.size[0], 3)) # resize to RGB array
        retval = self.callIm(rgb, **keyArgs)
        return retval
    def callIm(self, im, 
               interpolation='nearest', aspect='equal', 
               ijAsXY=False,
               clear=True, **keyArgs):
        if clear: 
            self.clear()
        self.a.axis('off')
        self.a.set_autoscale_on(True)
        if ijAsXY:
            self.asImIJ = False
            'imshow does not yet really support transform'
            if len(im.shape) == 3:
                imT = im.transpose(1,0,2)
            else:
                imT = im.T
            axIm = self.a.imshow(imT, 
                                 interpolation=interpolation, aspect=aspect, origin='lower', 
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(x), round(y), str(im[round(x),round(y)]))
        else:
            self.asImIJ = True
            'imshow does not yet really support transform'
            axIm = self.a.imshow(im, 
                                 interpolation=interpolation, aspect=aspect, 
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(y), round(x), str(im[round(y),round(x)]))
        'turn off autoscale so that axis limits do not get reset on replots'
        self.axIm = axIm
        self.mappable = axIm
        self.a.set_autoscale_on(False)
        return axIm
    def callContour(self, X, Y, data, 
                    interpolation=None, aspect=None,
                    **keyArgs):
        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        #cont = self.a.contourf(X, Y, data, 200, **keyArgs)
        'imshow does not yet really support transform'
        self.a.set_autoscale_on(True)
        cont = self.a.imshow(data, origin='lower',
                             extent=(X[0,0],X[0,-1],Y[0,0],Y[-1,0]), 
                             interpolation=interpolation,
                             aspect=aspect,
                             # transform=self.transform,
                             **keyArgs)
        self.a.set_autoscale_on(False)
        self.mappable = cont
        return cont
    def discontXY(self):
        self.x_prev = None
        return
    def callXY(self, x, y, style=None, **keyArgs):
        assert len(x) == len(y), \
               'x and y must be same length'

        xUse = x
        yUse = y
        if len(x) == 1:
            if self.x_prev is not None:
                xUse = []; xUse.append(self.x_prev[0]); xUse.append(x)
                yUse = []; yUse.append(self.x_prev[1]); yUse.append(y)

        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        if self.bball is not None:
            'first, get rid of last bball'
            lenCur = len(self.a.lines)
            if lenCur>0:
                self.a.lines = self.a.lines[0:lenCur-1]
        if self.aging is not None:
            #for lineList in self.lineListList[:-1]:
            #    for line in lineList:
            lenCur = len(self.a.lines)
            for line in self.a.lines[max(0,lenCur-self.agingNumAge):lenCur]:
                alphaCur = line.get_alpha()
                line.set_alpha(alphaCur*self.aging)
            if self.agingCull:
                if lenCur > self.agingNumAge:
                    self.a.lines = self.a.lines[lenCur-self.agingNumAge:lenCur]
        if style is not None:
            'passing transform of None can cause trouble'
            lines = self.a.plot(xUse, yUse, style,
                                # transform=self.transform,
                                **pp)
        elif self.style is not None:
            #self.lineListList.append(self.a.plot(x,y,self.style,**pp))
            lines = self.a.plot(xUse, yUse, self.style,
                                # transform=self.transform,
                                **pp)
        else:
            #self.lineListList.append(self.a.plot(x,y,**pp))
            lines = self.a.plot(xUse, yUse, 
                                # transform=self.transform,
                                **pp)
        if self.bball is not None:
            'add bball at end'
            self.a.plot([x[-1]],[y[-1]], self.bball)
            # transform=self.transform
        if len(x) == 1:
            if self.x_accum:
                self.x_prev = [x, y]
            self.x_store[0] = self.x_store[0] + list(x)
            self.x_store[1] = self.x_store[1] + list(y) 
        else:
            self.x_prev = None
            if len(x) == len(self.x_store[0]):
                'assume called with the same x values'
                self.x_store.append(list(y))
            else:
                self.x_store[0] = list(x)
                self.x_store[1] = list(y) 
        return
    def setVMM(self, vMM):
        if type(vMM) == int:
            iCol = vMM
            vMM = self.a.collections[iCol].get_clim()
        for col in self.a.collections:
            col.set_clim(vmin=vMM[0],vmax=vMM[1])
        return
    def colorbar(self, rect=(0.80,0.1,0.05,0.8), adjustPos=True, thing=None, **kwargs):
        '''
        if set rect to None, then colorbar steals self.a
        '''
        self.__checkWin()
        w = self.win
        f = self.f
        if len(self.a.collections) > 0:
            self.setVMM(0)
        if thing is None:
            if len(self.a.collections) > 0:
                thing = self.a.collections[0]
            elif hasattr(self, 'mappable'):
                thing = self.mappable
            else:
                raise RuntimeError, 'do not know what to colobar, pass in a thing'
        if rect is None:
            self.__colorbar = f.colorbar(thing, ax=self.a)
        else:
            cax = w.getNextAxes(rect=rect)
            self.__colorbar = f.colorbar(thing, cax=cax)
            if adjustPos:
                'adjust existing position to make room for colorbar'
                bbox = self.a.get_position().get_points()
                arect = (bbox[0,0], # left
                         bbox[0,1], # bottom
                         rect[0]-bbox[0,0]-0.02, # width
                         bbox[1,1]-bbox[0,1], # height
                         ) 
                self.a.set_position(arect) 
        self.show()
        return
示例#27
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
class AlchemyYahoo(object):
    def __init__(self, stock):
        self.apikey = "8490c1022cc805b491e2cf81b243c07e1606282c"
        self.stock = stock
        self.todaydate = datetime.datetime.now()
        self.todaydatetimestamp = int(time.time())
        self.startdate = str(
            (self.todaydate - datetime.timedelta(days=10)).date())
        self.startdatetimestamp = int(
            datetime.datetime.strptime(self.startdate,
                                       '%Y-%m-%d').strftime("%s"))
        self.result = []
        self.articlecount = []
        self.stockdates = []
        self.positive = "positive"
        self.negative = "negative"
        self.articlerow = 6
        self.articlecol = 1
        self.cellx = 250
        self.celly = 100
        self.articledata = None
        self.companyname = None
        self.articledatathread = ArticleDataThread(self.AlchemyURL)
        self.articledatathread.start()
        self.price = None
        self.change = None
        self.volume = None
        self.articlekeywords = []
        self.givestockinfothread = GiveStockInfoThread(self.givestockinfo)
        self.givestockinfothread.start()
        self.drawgraph()
        self.graph = None
        self.listofarticlekeywords()

    def getcompanyname(self):
        Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" +
               self.stock + """/chartdata;type=quote;range=1d/csv""")
        data = requests.get(Url).text
        info = data.splitlines()
        companyline = info[2]
        companynamelist = companyline.split(":")
        self.companyname = companynamelist[1]

    def listofarticlekeywords(self):
        while self.articledata == None:
            time.sleep(.001)
        if self.articledata == False:
            return
        for i in range(len(self.articledata)):
            self.articlekeywords.append(self.getkeywords(i))

    def geturlandtitle(self, info, newlist=None):
        if newlist == None:
            newlist = []
        if type(info) == str or type(info) == int:
            return newlist
        if type(info) == list:
            for dictionaries in info:
                self.geturlandtitle(dictionaries, newlist)
        else:
            for key, value in info.items():
                if type(value) == dict:
                    if key == "url":
                        newlist.append(info[key])
                    else:
                        self.geturlandtitle(info[key], newlist)
                else:
                    self.geturlandtitle(info[key], newlist)
        self.articledata = newlist

    def chartdata(self):
        stockinfo = []
        Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" +
               self.stock + "/chartdata;type=quote;range=2m/csv")
        data = requests.get(Url).text
        info = data.splitlines()
        highline = info[14].split(",")
        #self.high=highline[1]
        lowline = info[15].split(":")
        #self.low=lowline[1].split(",")[0]
        for line in data.splitlines():
            eachline = []
            for info in line.split(","):
                if line[0].isdigit():
                    eachline += [info]
                    stockinfo += [eachline]
        return stockinfo

    def AlchemyURL(self):
        companynamethread = threading.Thread(target=self.getcompanyname,
                                             args=())
        companynamethread.start()
        while self.companyname == None:
            time.sleep(.0001)
        keys = []
        QueryURL = (
            """https://access.alchemyapi.com/calls/data/GetNews?apikey=8490c1022cc805b491e2cf81b243c07e1606282c&return=enriched.url.title,enriched.url.url&start="""
            + str(self.startdatetimestamp) + "&end=" +
            str(self.todaydatetimestamp) +
            """&q.enriched.url.entities.entity=|text=""" + self.stock +
            """,type=company|&q.enriched.url.docSentiment.type=positive&q.enriched.url.taxonomy.taxonomy_.label=technology%20and%20computing&count=6&outputMode=json"""
        )
        r = requests.get(QueryURL).text
        string = json.dumps(r)
        convertedtopython = json.loads(r)
        if convertedtopython["status"] == 'OK':
            geturlandtitlethread = GetUrlAndTitleThread(
                self.geturlandtitle, convertedtopython)
            geturlandtitlethread.start()
        else:
            self.articledata = False

    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)
        # Return a handle which contains a reference to the photo object
        # which must be kept live or else the picture disappears
        #return self.photo
        #Don't create the image, store the image and then add it

    def drawgraph(self):
        #Learnt how to use matoplotlib from youtube videos
        while self.companyname == None:
            time.sleep(0.001)
        self.stockinfo = self.chartdata()
        date = []
        closeprice = []
        highprice = []
        lowprice = []
        openprice = []
        for line in self.stockinfo:
            date.append(datetime.datetime.strptime(line[0], "%Y%m%d"))
            closeprice.append((float((line[1]))))
            highprice.append((float(line[2])))
            lowprice.append((float((line[3]))))
            openprice.append((float((line[4]))))
        # Create the figure we desire to add to an existing canvas
        fig = plt.figure(facecolor="white", figsize=(7, 6), dpi=90)
        graph = plt.subplot(1, 1, 1)
        graph.plot(date, highprice, '#008080', label="High Price")
        graph.plot(date,
                   lowprice,
                   label="Low Price",
                   linestyle=":",
                   linewidth=2)
        graph.plot(date, openprice, label="Open Price", linestyle="--")
        graph.plot(date,
                   closeprice,
                   label="Close Price",
                   linestyle="-.",
                   linewidth=2)
        plt.legend(loc=2,
                   fontsize="x-small",
                   fancybox=True,
                   shadow=True,
                   frameon=True,
                   framealpha=None)
        graph.grid(True, which="major", axis="both", color="red")
        plt.xlabel("Date", color="green", fontsize=11)
        plt.ylabel("Price", color="green", fontsize=11)
        graph.spines["bottom"].set_color("purple")
        graph.spines["top"].set_color("purple")
        graph.spines["right"].set_color("purple")
        graph.spines["left"].set_color("purple")
        graph.tick_params(axis="y", colors="navy")
        graph.tick_params(axis="x", colors="navy")
        plt.title(self.companyname, color="purple")
        graph.xaxis.set_major_locator(mticker.MaxNLocator(6))
        graph.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
        labelsx = graph.get_xticklabels()
        plt.setp(labelsx, rotation=30, fontsize=11)
        labelsy = graph.get_yticklabels()
        plt.setp(labelsy, rotation=0, fontsize=11)
        self.low, self.high = graph.get_ylim()
        plt.tight_layout()
        self.figure = fig

    def drawinformation(self, canvas):
        self.drawarticle = []
        if self.articledata != False and self.articledata != None:
            gap = 0
            while len(self.articledata) < 6:
                self.articledata.append({
                    "title":
                    "Could not find enough article\
                    s in recent times"
                })
            for article in self.articledata:
                left = 400
                top = 160 + (gap * self.celly)
                if article[
                        "title"] != "Could not find enough articles in recent \
                times. There's not much information about the stock in \
                the news":
                    self.drawarticle.append(
                        canvas.create_text(left,
                                           top,
                                           text=article["title"],
                                           anchor=NW,
                                           width=210,
                                           fill="medium blue",
                                           font="Helvetica 13 underline"))
                    gap += 1
                else:
                    self.drawarticle.append(
                        canvas.create_text(left,
                                           top,
                                           text=article["title"],
                                           anchor=NW,
                                           width=210,
                                           fill="orangered2",
                                           font="Helvetica 13 underline"))
                    gap += 1
        else:
            canvas.create_text(400,
                               160,
                               text="""You've exhausted your daily 
                limit. \n\n Sincerely, \n Smart Trading.""",
                               fill="darkorchid4",
                               anchor=NW)

    def givestockinfo(self):
        self.volume = 0
        Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" +
               self.stock + """/chartdata;type=quote;range=1d/csv""")
        data = requests.get(Url).text
        info = data.splitlines()
        lineforlastclose = info[8].split(":")
        self.lastclose = lineforlastclose[1]
        lastprice = info[-1]
        mostrecent = lastprice.split(",")
        self.price = mostrecent[1]
        self.change = float(self.price) - float(self.lastclose)
        alldata = data.splitlines()
        stockdata = []
        for line in alldata:
            databydate = []
            for info in line.split(","):
                if line[0].isdigit():
                    databydate += [info]
                    stockdata += [databydate]
        for dates in stockdata:
            self.volume += int(dates[5])
            self.volume = self.volume

    def drawstockinfo(self, canvas, gap):
        self.displaystockinfo = []
        while self.price == None:
            time.sleep(.0001)
        price = round(float(self.price), 2)
        change = round(self.change, 2)
        left = 205
        top = 170 + (gap * self.celly)
        self.displaystockinfo.append(
            canvas.create_text(left,
                               top,
                               text=self.stock,
                               width=210,
                               fill="red2",
                               font="Helvetica 15"))
        self.displaystockinfo.append(
            canvas.create_line(96,
                               195 + (gap * self.celly),
                               317,
                               195 + (gap * self.celly),
                               fill="grey"))
        self.displaystockinfo.append(
            canvas.create_line(250,
                               200 + (gap * self.celly),
                               250,
                               240 + (gap * self.celly),
                               fill="grey"))
        self.displaystockinfo.append(
            canvas.create_line(160,
                               200 + (gap * self.celly),
                               160,
                               240 + (gap * self.celly),
                               fill="grey"))
        self.displaystockinfo.append(
            canvas.create_text(100,
                               200 + (gap * self.celly),
                               text="Price",
                               anchor=NW,
                               fill="gray25"))
        self.displaystockinfo.append(
            canvas.create_text(100,
                               220 + (gap * self.celly),
                               text=price,
                               anchor=NW))
        self.displaystockinfo.append(
            canvas.create_text(175,
                               200 + (gap * self.celly),
                               text="Volume",
                               anchor=NW,
                               fill="gray25"))
        self.displaystockinfo.append(
            canvas.create_text(175,
                               220 + (gap * self.celly),
                               text=self.volume,
                               anchor=NW))
        self.displaystockinfo.append(
            canvas.create_text(260,
                               200 + (gap * self.celly),
                               text="Change",
                               anchor=NW,
                               fill="gray25"))
        if change != None:
            if change < 0:
                self.displaystockinfo.append(
                    canvas.create_text(260,
                                       220 + (gap * self.celly),
                                       text=change,
                                       anchor=NW,
                                       fill="red"))
            else:
                self.displaystockinfo.append(
                    canvas.create_text(260,
                                       220 + (gap * self.celly),
                                       text=change,
                                       anchor=NW,
                                       fill="green"))
            gap += 1

    def drawcurrentstock(self, canvas):
        self.displaycurrentstock = []
        while self.price == None:
            time.sleep(.0001)
        price = round(float(self.price), 2)
        change = round(self.change, 2)
        self.displaycurrentstock.append(
            canvas.create_rectangle(800,
                                    50,
                                    1100,
                                    110,
                                    outline="purple",
                                    width=3))
        self.displaycurrentstock.append(
            canvas.create_rectangle(800, 50, 1100, 110, outline="red",
                                    width=2))
        self.displaycurrentstock.append(
            canvas.create_text(830, 70, text=self.stock, fill="purple"))
        self.displaycurrentstock.append(
            canvas.create_text(830,
                               90,
                               text="+",
                               fill="green3",
                               font="Helvetica 17 bold"))
        self.displaycurrentstock.append(
            canvas.create_text(870, 60, text="Price", anchor=NW,
                               fill="gray25"))
        self.displaycurrentstock.append(
            canvas.create_text(870, 85, text=price, anchor=NW))
        self.displaycurrentstock.append(
            canvas.create_text(945,
                               60,
                               text="Volume",
                               anchor=NW,
                               fill="gray25"))
        self.displaycurrentstock.append(
            canvas.create_text(945, 85, text=self.volume, anchor=NW))
        self.displaycurrentstock.append(
            canvas.create_text(1025,
                               60,
                               text="Change",
                               anchor=NW,
                               fill="gray25"))
        self.displaycurrentstock.append(
            canvas.create_line(860, 60, 860, 100, fill="grey"))
        self.displaycurrentstock.append(
            canvas.create_line(935, 60, 935, 100, fill="grey"))
        self.displaycurrentstock.append(
            canvas.create_line(1015, 60, 1015, 100, fill="grey"))
        if change != None:
            if change < 0:
                self.displaycurrentstock.append(
                    canvas.create_text(1025,
                                       85,
                                       text=change,
                                       anchor=NW,
                                       fill="red"))
            else:
                self.displaycurrentstock.append(
                    canvas.create_text(1025,
                                       85,
                                       text=change,
                                       anchor=NW,
                                       fill="green"))

    def drawgraphbox(self, canvas, x, y):
        differenceinpixels = 415
        differenceinprice = abs(self.high - self.low)
        change = differenceinprice / differenceinpixels
        top = 175
        ydifference = y - top
        difference = (change * ydifference)
        canvas.create_rectangle(x - 30,
                                y - 30,
                                x + 30,
                                y - 10,
                                fill="white",
                                outline="darkorchid4",
                                width=2)
        canvas.create_rectangle(x - 30,
                                y - 30,
                                x + 30,
                                y - 10,
                                outline="white",
                                width=1)
        canvas.create_text(x,
                           y - 20,
                           text=abs(round(float(self.high) - difference, 2)),
                           fill="darkorchid4")

    def getkeywords(self, number):
        keywords = set()
        if self.articledata == None or self.articledata == False:
            return
        articles = self.articledata
        dictionary = articles[number]
        url = dictionary["url"]
        QueryURL = (
            "http://gateway-a.watsonplatform.net/calls/url/URLGetRankedKeywords?apikey=8490c1022cc805b491e2cf81b243c07e1606282c&url="
            + url + "&outputMode=json")
        r = requests.get(QueryURL).text
        string = json.dumps(r)
        convertedtopython = json.loads(r)
        if convertedtopython['status'] == 'OK':
            for keyword in convertedtopython['keywords']:
                if len(keywords) < 15:
                    keywords.add(keyword["text"].strip())
                else:
                    break
        else:
            if len(keywords) == 0:
                keywords.add("We're sorry but you've hit the transactions per \
                    day.\n\n Sincerely,  Smart Trading.")
        return keywords

    def __eq__(self, other):
        return isinstance(other, AlchemyYahoo) and self.stock == other.stock
示例#29
0
class PlotWrap(object):
    __debug = False
    __keyArgDict =  {
        'title' : None,
        'winTitle' : None,
        'xlabel' : None,
        'xticks' : None,
        'ylabel' : None,
        'yticks' : None,
        'ylog' : False,
        'xlog' : False,
        'ybound' : (None,None),
        'xbound' : (None,None),
        'legend' : None,
        'style' : None,
        'aging' : None,
        'alphaMin' : 0.02,
        'agingCull' : True,
        'bball' : None,
        'accum' : False,
        'showByDefault' : True,
        'makeWinByDefault': True,
        'axes' :  None,
        'axesRect' :  None,
        'axprops' :  {},
        'figsize' : (5,4),
        'dpi' : 100,
        'window' :  None,
        'as3D' : False,
        }
    def __init__(self,
                 **keyArgs
                 ):

        # defaults
        for parm, val in self.__keyArgDict.iteritems():
            self.__setattr__(parm, val)
        #
        # parse keyword args
        for keyArg in self.getKeyArgList():
            if keyArgs.has_key(keyArg):
                self.__setattr__(keyArg, keyArgs.pop(keyArg))
        if len(keyArgs) > 0:
            raise RuntimeError, 'unparsed keyword args : '+str(keyArgs)
        #
        window = self.window
        del self.window
        #
        self.x_accum = self.accum
        del self.accum
        #
        axes = self.axes
        del self.axes

        self.x_prev = None
        self.x_store = [[],[]]

        self.win = None
        self.a   = None
        self.canvas = None

        self.ownCanvas = True
        if window is None:
            self.ownCanvas = True
            'checking self.showByDefault here causes trouble because it is hard to attach a figure to a window later for a general backend ***'
            if self.showByDefault or self.makeWinByDefault:
                # 'go ahead and make a window, using PlotWinP to increase backend flexibility'
                # self.win    = ...PlotWinP(as3D=self.as3D, figsize=self.figsize, dpi=self.dpi)
                # self.a      = self.win.getAxes(0)
                # self.f      = self.win.getFigure()
                # self.canvas = self.win.getCanvas()
                # self.a.set_autoscale_on(True)
                self.__checkWin()
                self.f = self.win.f
            else:
                from matplotlib.figure import Figure
                self.f = Figure(figsize=self.figsize, dpi=self.dpi)
            if self.as3D:
                import mpl_toolkits.mplot3d.axes3d as p3
                self.a = p3.Axes3D(self.f)
            else:
                if self.axesRect is None:
                    self.a = self.f.add_subplot(1, 1, 1, **self.axprops)
                else:
                    self.a = self.f.add_axes(self.axesRect, **self.axprops)

            if axes is not None:
                raise RuntimeError, 'do not specify axes when have not passed a window'
        else:
            self.ownCanvas = False
            self.win = window
            self.canvas = self.win.getCanvas()
            self.f = self.win.getFigure()
            if axes is None:
                if self.__debug: print 'using axprops: '+str(self.axprops)
                self.a = self.win.getNextAxes(rect=self.axesRect, attachPW=self, **self.axprops)
            elif isinstance(axes, int):
                self.a = self.win.getAxes(axes, **self.axprops)
            else:
                self.a = axes
        #
        self.clear() # sets labels and so forth

        # self.style = style # can be None
        # self.bball = bball # can be None
        #
        #self.aging = aging
        #self.agingCull = agingCull
        #self.alphaMin = alphaMin
        self.agingNumAge = -1
        if self.aging is not None:
            from math import log
            self.agingNumAge = max(int(log(self.alphaMin)/log(self.aging)),1)
        self.plotProps = {}
        # self.lineListList = [] # not needed, can, and should, use a.lines

        self.asImIJ = False
        # self.transform = None
        self.axIm = None
        self.__colorbar = None

        return
    def add_axes(self, arect, kwAddAxes={}, **kwarg):
        aNew = self.f.add_axes(arect, **kwAddAxes)
        # self.a.set_position((0.05, 0.05, 0.45, 0.9))
        new = self.__class__(window=self.win, axes=aNew, **kwarg)
        return new
    @classmethod
    def popKeyArgs(cls, kwargs):
        retval = {}
        for key in cls.getKeyArgList():
            if kwargs.has_key(key):
                retval[key] = kwargs.pop(key)
        return retval
    @classmethod
    def getKeyArgList(cls):
        return cls.__keyArgDict.keys()
    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

    def __checkWin(self):
        if self.win is not None: return
        winTitle = self.winTitle
        if winTitle is None : winTitle = self.title
        if winTitle is None : winTitle = 'plotWin'
        if hasattr(self,'f'):
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, figure=self.f, axesList=[self.a])
        else:
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, axesList=[self.a])
        #self.win = PlotWinP(title=winTitle, figure=self.f, axes=self.a)
        self.canvas = self.win.getCanvas()
        return
    def removeLines(self):
        lines = self.a.get_lines()
        for line in lines:
            line.remove()
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def show(self):
        self.__checkWin()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if hasattr(self.a,'mouse_init'):
            self.a.mouse_init()
        if hasattr(self.f, 'show'):
            self.f.show()
        elif hasattr(self.canvas, 'show'):
            self.canvas.show()
        else:
            raise RuntimeError, 'do not know how to do show'
        return
    def clear(self):
        self.asImIJ = False
        self.axIm = None
        # self.transform = None
        self.x_prev = None
        self.__colorbar = None
        self.x_store = [[],[]]
        if self.showByDefault:
            self.__checkWin()
        if self.a is not None:
            if hasattr(self.a,'mouse_init'):
                'doing a.clear() seems like it causes trouble with plotting collections?'
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
            else:
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
        if self.xticks is not None:
            self.a.set_xticks(self.xticks)
        if self.title is not None:
            self.a.set_title(self.title)
        if self.xlabel is not None:
            self.a.set_xlabel(self.xlabel)  # r'X axis label $\mu\mbox{lentz}$'
            if self.win is not None:
                'make some room for the label'
                self.win.haveXLabels()
        if self.yticks is not None:
            self.a.set_yticks(self.yticks)
        if self.xlog: self.a.set_xscale('log')
        if self.ylog: self.a.set_yscale('log')
        #self.a.set_ybound(self.ybound)
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if self.ylabel is not None:
            self.a.set_ylabel(self.ylabel)
            if self.win is not None:
                'make some room for the label'
                self.win.haveYLabels()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if self.a is not None:
            self.a.set_autoscale_on(True)
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def setLegend(self, val=True):
        # if self.legend is None:
        #     self.legend = True
        # if val is not None:
        #     self.legend = val
        self.legend = val
        return
    def save(self, **keyArgs):
        '''make hardcopy of the current figure;
        specify filename or prefix keyword argument
        '''
        import numpy as num

        filename = None
        prefix = None
        if keyArgs.has_key('filename'):
            filename = keyArgs.pop('filename')
        if keyArgs.has_key('prefix'):
            prefix = keyArgs.pop('prefix')
            filename = prefix+'.pdf' # .eps

        if prefix is not None:
            'export data'
            if len(self.x_store[0]) > 0:
                dataFilename = prefix+'.data'
                from hexrd import arrayutil
                try:
                    arrayutil.writeArray(dataFilename, num.array(self.x_store))
                except:
                    import sys
                    print 'problem writing to '+dataFilename+' : '+str(self.x_store)
                    sys.exit(1)

        if not self.ownCanvas:
            if self.__debug:
                print 'skipping print_figure because this plot does not own its canvas'
        else:
            self.__checkCanvas()
            if filename is None:
                raise RuntimeError, 'need filename or prefix entry in keyArgs'
            #dpi = self.f.get_dpi()
            #self.canvas.print_figure(filename, dpi=dpi, **keyArgs)
            self.f.savefig(filename, **keyArgs)

        return
    def destroy(self):
        'does not clean up self.a, just kills the window if this plot owns the window'
        if self.ownCanvas and self.win is not None:
            self.win.destroy()
        return
    def drawBBox(self, bbox, **kwargs):
        import numpy as num
        bbox_x = bbox[0]
        bbox_y = bbox[1]
        xBBox = num.array([ bbox_x[0], bbox_x[1], bbox_x[1], bbox_x[0], bbox_x[0] ])
        yBBox = num.array([ bbox_y[0], bbox_y[0], bbox_y[1], bbox_y[1], bbox_y[0] ])
        'go through call, instead of callXY, in case of asImIJ'
        self.__call__(xBBox, yBBox, **kwargs)
        return
    def __call__(self, *args, **keyArgs):
        import numpy as num
        noShow = False
        retVal = None
        # if keyArgs.has_key('transform'):
        #     'pop transform so that can keep it for other (overlaid) plots'
        #     self.transform = keyArgs.pop('transform')
        if keyArgs.has_key('noShow'):
            noShow = keyArgs.pop('noShow')
        if len(args) == 2:
            alphas = None
            if self.asImIJ:
                x = args[1]
                y = args[0]
            else:
                x = args[0]
                y = args[1]
            if keyArgs.has_key('alphas'):
                alphas = keyArgs.pop('alphas')
                assert len(args) == 2, 'len(args) != 2'
                assert len(alphas) == len(y), 'len(alphas) != len(y)'
                self.x_prev = None
                for iX in range(len(x)):
                    self.callXY([x[iX]],[y[iX]],alpha=alphas[iX],**keyArgs)
            else:
                self.callXY(x, y, **keyArgs)
        elif len(args) == 3:
            X = args[0]; Y = args[1]; data = args[2];
            cont = self.callContour(X, Y, data, **keyArgs)
            retVal = cont
        elif len(args) == 1 and isinstance(args[0],str):
            'interpret string as name of a file to plot in axes'
            filename = args[0]
            im = self.callImage(filename, **keyArgs)
            retVal = im
        elif len(args) == 1 and isinstance(args[0],num.ndarray):
            im = self.callIm(args[0], **keyArgs)
            retVal = im
        else:
            raise RuntimeError, 'do not know what to do with args'
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if not noShow:
            if self.showByDefault:
                self.show()
        return retVal
    def callImage(self, filename,
                  **keyArgs):
        import Image
        im = Image.open(filename)
        s = im.tostring() # convert PIL image -> string
        import numpy as num
        rgb = num.fromstring(s, dtype=num.uint8).astype(num.float)/255.0 # convert string -> array of floats
        rgb = num.resize(rgb, (im.size[1], im.size[0], 3)) # resize to RGB array
        retval = self.callIm(rgb, **keyArgs)
        return retval
    def callIm(self, im,
               interpolation='nearest', aspect='equal',
               ijAsXY=False,
               clear=True, **keyArgs):
        if clear:
            self.clear()
        self.a.axis('off')
        # self.a.set_autoscale_on(True)
        if ijAsXY:
            self.asImIJ = False
            'imshow does not yet really support transform'
            if len(im.shape) == 3:
                imT = im.transpose(1,0,2)
            else:
                imT = im.T
            axIm = self.a.imshow(imT,
                                 interpolation=interpolation, aspect=aspect, origin='lower',
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(x), round(y), str(im[round(x),round(y)]))
        else:
            self.asImIJ = True
            'imshow does not yet really support transform'
            axIm = self.a.imshow(im,
                                 interpolation=interpolation, aspect=aspect,
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(y), round(x), str(im[round(y),round(x)]))
        'turn off autoscale so that axis limits do not get reset on replots'
        self.axIm = axIm
        self.mappable = axIm
        self.a.set_autoscale_on(False)
        return axIm
    def callContour(self, X, Y, data,
                    interpolation=None, aspect=None,
                    **keyArgs):
        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        #cont = self.a.contourf(X, Y, data, 200, **keyArgs)
        'imshow does not yet really support transform'
        # self.a.set_autoscale_on(True)
        cont = self.a.imshow(data, origin='lower',
                             extent=(X[0,0],X[0,-1],Y[0,0],Y[-1,0]),
                             interpolation=interpolation,
                             aspect=aspect,
                             # transform=self.transform,
                             **keyArgs)
        self.a.set_autoscale_on(False)
        self.mappable = cont
        return cont
    def discontXY(self):
        self.x_prev = None
        return
    def callXY(self, x, y, style=None, **keyArgs):
        assert len(x) == len(y), \
               'x and y must be same length'

        xUse = x
        yUse = y
        if len(x) == 1:
            if self.x_prev is not None:
                xUse = []; xUse.append(self.x_prev[0]); xUse.append(x)
                yUse = []; yUse.append(self.x_prev[1]); yUse.append(y)

        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        if self.bball is not None:
            'first, get rid of last bball'
            lenCur = len(self.a.lines)
            if lenCur>0:
                self.a.lines = self.a.lines[0:lenCur-1]
        if self.aging is not None:
            #for lineList in self.lineListList[:-1]:
            #    for line in lineList:
            lenCur = len(self.a.lines)
            for line in self.a.lines[max(0,lenCur-self.agingNumAge):lenCur]:
                alphaCur = line.get_alpha()
                line.set_alpha(alphaCur*self.aging)
            if self.agingCull:
                if lenCur > self.agingNumAge:
                    self.a.lines = self.a.lines[lenCur-self.agingNumAge:lenCur]
        if style is not None:
            'passing transform of None can cause trouble'
            lines = self.a.plot(xUse, yUse, style,
                                # transform=self.transform,
                                **pp)
        elif self.style is not None:
            #self.lineListList.append(self.a.plot(x,y,self.style,**pp))
            lines = self.a.plot(xUse, yUse, self.style,
                                # transform=self.transform,
                                **pp)
        else:
            #self.lineListList.append(self.a.plot(x,y,**pp))
            lines = self.a.plot(xUse, yUse,
                                # transform=self.transform,
                                **pp)
        if self.bball is not None:
            'add bball at end'
            self.a.plot([x[-1]],[y[-1]], self.bball)
            # transform=self.transform
        if len(x) == 1:
            if self.x_accum:
                self.x_prev = [x, y]
            self.x_store[0] = self.x_store[0] + list(x)
            self.x_store[1] = self.x_store[1] + list(y)
        else:
            self.x_prev = None
            if len(x) == len(self.x_store[0]):
                'assume called with the same x values'
                self.x_store.append(list(y))
            else:
                self.x_store[0] = list(x)
                self.x_store[1] = list(y)
        return
    def setVMM(self, vMM):
        if type(vMM) == int:
            iCol = vMM
            vMM = self.a.collections[iCol].get_clim()
        for col in self.a.collections:
            col.set_clim(vmin=vMM[0],vmax=vMM[1])
        return
    def colorbar(self, rect=(0.80,0.1,0.05,0.8), adjustPos=True, thing=None, **kwargs):
        '''
        if set rect to None, then colorbar steals self.a
        '''
        self.__checkWin()
        w = self.win
        f = self.f
        if len(self.a.collections) > 0:
            self.setVMM(0)
        if thing is None:
            if len(self.a.collections) > 0:
                thing = self.a.collections[0]
            elif hasattr(self, 'mappable'):
                thing = self.mappable
            else:
                raise RuntimeError, 'do not know what to colobar, pass in a thing'
        if rect is None:
            self.__colorbar = f.colorbar(thing, cax=self.a, **kwargs)
        else:
            cax = w.getNextAxes(rect=rect)
            self.__colorbar = f.colorbar(thing, cax=cax, **kwargs)
            if adjustPos:
                'adjust existing position to make room for colorbar'
                bbox = self.a.get_position().get_points()
                arect = (bbox[0,0], # left
                         bbox[0,1], # bottom
                         rect[0]-bbox[0,0]-0.02, # width
                         bbox[1,1]-bbox[0,1], # height
                         )
                self.a.set_position(arect)
        self.show()
        return