Example #1
0
def make_figure(*args, **kwargs):
    'Create an Agg figure for testing'
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    fig = Figure(*args, **kwargs)
    fig.canvas = FigureCanvasAgg(fig)
    return fig
Example #2
0
def make_figure(*args, **kwargs):
    """Create an Agg figure for testing."""
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    if 'dpi' not in kwargs:
        kwargs['dpi'] = 100
    fig = Figure(*args, **kwargs)
    fig.canvas = FigureCanvasAgg(fig)
    return fig
Example #3
0
def ree_plot(fn, **kwargs):
    """
    Context manager to create plot with appropriate
    axes for plotting REE data
    """
    fig = Figure(figsize=kwargs.pop('size', (4, 6)))
    fig.canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.set_yscale('log')
    yield ax
    fig.savefig(fn, bbox_inches='tight')
Example #4
0
def main():

    app = QtGui.QApplication(sys.argv)

    mu, sigma = 2000, 200
    arr = mu + sigma * np.random.standard_normal(size=2400)
    #arr = np.arange(2400)
    arr.shape = (40, 60)

    fig = Figure((10.0, 10.0),
                 dpi=100,
                 facecolor='w',
                 edgecolor='w',
                 frameon=True)
    fig.canvas = FigureCanvas(fig)  # Graphic window specific stuff

    ex = GUIMainWindow(None, fig, arr)
    #ex.set_image_array(arr)

    ex.show()
    app.exec_()
Example #5
0
    def draw(self, cr):
        dpi = 96
        f = Figure(figsize=(self.width / dpi, self.height / dpi), dpi=dpi)
        ax = f.add_subplot(111)
        t = arange(0, 100, 1)
        s = self.values
        f.set_facecolor((0, 0, 0, 0))
        ax.set_facecolor((0, 0, 0, 0))
        f.subplots_adjust(wspace=0, top=1.0, bottom=0.0, left=0, right=1.0)

        ax.axis('off')
        ax.set_ylim([0, 100])

        ax.fill_between(t, s, [0] * 100)

        renderer = RendererGTK3Cairo(f.dpi)
        renderer.set_context(cr)
        renderer.set_width_height(self.width, self.height)

        f.canvas = MockCanvas()  # Monkey patch to reduce memory footprint.
        f.draw(renderer)
Example #6
0
def save(filename, np_array, png=False):
    """ saves numpy array as bitmap and/or png image. A list of details
    may be included to save relevant info about the images in a CSV file
    of the same name. By default only a bitmap is produced.

    Parameters
    ----------

    filename : string
        Filename (without extension).

    np_array : numpy.array
        2D numpy array (dtype=uint8) representing grayscale image to save.

    png : bool
        By default, a bmp file is produced. If png=True, a png file will be
        retained along with the bitmap.
    """

    value_min = 0
    value_max = 255
    color_map = 'gray'

    fig = Figure(figsize=np_array.shape[::-1], dpi=1, frameon=False)
    fig.canvas = FigureCanvas(fig)
    fig.figimage(np_array, cmap=color_map, vmin=value_min,
                 vmax=value_max, origin=None)
    fig.savefig(filename, dpi=1, format=None)

    # save bitmap (convert from PNG)
    img = PIL.Image.open(filename + '.png')
    if len(img.split()) == 4:  # prevent IOError: cannot write mode RGBA as BMP
        r, g, b, a = img.split()
        img = PIL.Image.merge("RGB", (r, g, b))
    greyscale = img.convert("L")  # L indicates PIL's greyscale mode
    greyscale.save(filename + '.bmp')

    # delete PNG
    if not png:
        os.remove(filename + '.png')
Example #7
0
def test_figure_no_canvas():
    fig = Figure()
    fig.canvas = None
    pt.print_figure(fig)
Example #8
0
def loadFigureFromFile(filename: str,
                       figure: Figure = None,
                       offset: list = None,
                       dpi: int = None,
                       cache: bool = False):
    """
    Add contents to the current figure from the file defined by filename. It can be either a python script defining
    a figure, an image (filename or directly the numpy array), or an svg file.

    See also :ref:`composing`.

    Parameters
    ----------
    filename : str
        The file to load. Can point to a python script file, an image file or an svg file.
    figure : Figure, optional
        The figure where to add the loaded file. Defaults to the current figure.
    offset : list, optional
        The offset where to import the file. The first two parts define the x and y position and the third part defines
        the units to use. Default is "%", a percentage of the current figure size. It can also be "cm" or "in".
    cache : bool, optional
        Whether to try to cache the figure generated from the file. Only for python files. This option is experimental
        and may not be stable.
    """
    from matplotlib import rcParams
    from pylustrator import changeFigureSize
    import pylustrator

    # change to the directory of the filename (to execute the code relative to this directory)
    dirname, filename = os.path.split(filename)
    dirname = os.path.abspath(dirname)
    with changeFolder(dirname):
        if dirname:
            os.chdir(dirname)

        # defaults to the current figure
        if figure is None:
            figure = plt.gcf()

        class noShow:
            """
            An environment that prevents the script from calling the plt.show function
            """
            def __enter__(self):
                # store the show function
                self.show = plt.show
                self.dragger = pylustrator.start

                # define an empty function
                def empty(*args, **kwargs):
                    pass

                # set the show function to the empty function
                plt.show = empty
                pylustrator.start = empty

            def __exit__(self, type, value, traceback):
                # restore the old show function
                plt.show = self.show
                pylustrator.start = self.dragger

        class noNewFigures:
            """
            An environment that prevents the script from creating new figures in the figure manager
            """
            def __enter__(self):
                fig = plt.gcf()
                self.fig = plt.figure
                figsize = rcParams['figure.figsize']
                fig.set_size_inches(figsize[0], figsize[1])

                def figure(num=None, figsize=None, *args, **kwargs):
                    fig = plt.gcf()
                    if figsize is not None:
                        fig.set_size_inches(figsize[0],
                                            figsize[1],
                                            forward=True)
                    return fig

                plt.figure = figure

            def __exit__(self, type, value, traceback):
                from matplotlib.figure import Figure
                from matplotlib.transforms import TransformedBbox, Affine2D
                plt.figure = self.fig

        # get the size of the old figure
        w1, h1 = figure.get_size_inches()
        axes1 = removeContentFromFigure(figure)
        if len(axes1) == 0:
            w1 = 0
            h1 = 0

        # try to load the filename as an image
        try:
            im = plt.imread(filename)
        except OSError:
            im = None

        # if it is an image, just display the image
        if im is not None:
            im = plt.imread(filename)
            imShowFullFigure(im, os.path.split(filename)[1], figure, dpi=dpi)
        # if the image is a numpy array, just display the array
        elif isinstance(filename, np.ndarray):
            im = filename
            imShowFullFigure(im, str(im.shape), figure, dpi)
        # if it is a svg file, display the svg file
        elif filename.endswith(".svg"):
            svgread(filename)
        # if not, it should be a python script
        else:
            filename = os.path.abspath(filename)
            cache_filename = filename + ".cache.pkl"

            with noNewFigures():
                # prevent the script we want to load from calling show
                with noShow():
                    import pickle
                    if cache and os.path.exists(
                            cache_filename) and os.path.getmtime(
                                cache_filename) > os.path.getmtime(filename):
                        print("loading from cached file", cache_filename)
                        fig2 = pickle.load(open(cache_filename, "rb"))
                        w, h = fig2.get_size_inches()
                        figure.set_size_inches(w, h)

                        str(figure
                            )  # important! (for some reason I don't know)
                        for ax in fig2.axes:
                            fig2.delaxes(ax)
                            figure._axstack.add(figure._make_key(ax), ax)
                            figure.bbox._parents.update(fig2.bbox._parents)
                            figure.dpi_scale_trans._parents.update(
                                fig2.dpi_scale_trans._parents)
                            replace_all_refs(fig2.bbox, figure.bbox)
                            replace_all_refs(fig2.dpi_scale_trans,
                                             figure.dpi_scale_trans)
                            replace_all_refs(fig2, figure)
                    else:
                        # execute the file
                        exec(
                            compile(
                                open(filename, "rb").read(), filename, 'exec'),
                            globals())
                        if cache is True:
                            c = figure.canvas
                            figure.canvas = None
                            figure.bbox.pylustrator = True
                            figure.dpi_scale_trans.pylustrator = True
                            pickle.dump(figure, open(cache_filename, 'wb'))

                            figure.canvas = c

        # get the size of the new figure
        w2, h2 = figure.get_size_inches()
        if offset is not None:
            if len(offset) == 2 or offset[2] == "%":
                w2 += w1 * offset[0]
                h2 += h1 * offset[1]
            elif offset[2] == "in":
                w2 += offset[0]
                h2 += offset[1]
            elif offset[2] == "cm":
                w2 += offset[0] / 2.54
                h2 += offset[1] / 2.54
            changeFigureSize(w2,
                             h2,
                             cut_from_top=True,
                             cut_from_left=True,
                             fig=figure)
        w = max(w1, w2)
        h = max(h1, h2)
        changeFigureSize(w, h, fig=figure)
        if len(axes1):
            axes2 = removeContentFromFigure(figure)
            changeFigureSize(w1, h1, fig=figure)
            addContentToFigure(figure, axes1)

            changeFigureSize(w, h, fig=figure)
            addContentToFigure(figure, axes2)
Example #9
0
    def __init__(self, parent=None, **kwargs):
        figsize = kwargs.pop('figsize', (3,3))
        dpi = kwargs.pop('dpi', 100)
        if 'limits' in kwargs:
            self._full_fov_lims = kwargs.pop('limits')
        extents = limits_to_extents(self._full_fov_lims)
        QtGui.QWidget.__init__(self, parent)
        # set up the Sag, Cor, Axi SliceFigures
        self.horizontalLayout = QtGui.QHBoxLayout(self)
        self.horizontalLayout.setObjectName("FigureLayout")


        # set axial figure
        fig = Figure(figsize=figsize, dpi=dpi)
        fig.canvas = Canvas(fig)
        Canvas.setSizePolicy(fig.canvas, QtGui.QSizePolicy.Expanding,
                             QtGui.QSizePolicy.Expanding)
        Canvas.updateGeometry(fig.canvas)
        fig.canvas.setParent(self)
        self.axi_fig = ssp.SliceFigure(fig, extents[AXI], blit=BLITTING)
        self.axi_fig.ax.set_xlabel('left to right', fontsize=8)
        self.axi_fig.ax.set_ylabel('posterior to anterior', fontsize=8)
        self.horizontalLayout.addWidget(fig.canvas)
        # set coronal figure
        fig = Figure(figsize=figsize, dpi=dpi)
        fig.canvas = Canvas(fig)
        Canvas.setSizePolicy(fig.canvas, QtGui.QSizePolicy.Expanding,
                             QtGui.QSizePolicy.Expanding)
        Canvas.updateGeometry(fig.canvas)
        fig.canvas.setParent(self)
        self.cor_fig = ssp.SliceFigure(fig, extents[COR], blit=BLITTING)
        self.cor_fig.ax.set_xlabel('left to right', fontsize=8)
        self.cor_fig.ax.set_ylabel('inferior to superior', fontsize=8)
        self.horizontalLayout.addWidget(fig.canvas)        
        # set sagittal figure
        fig = Figure(figsize=figsize, dpi=dpi)
        fig.canvas = Canvas(fig)
        Canvas.setSizePolicy(fig.canvas, QtGui.QSizePolicy.Expanding,
                             QtGui.QSizePolicy.Expanding)
        Canvas.updateGeometry(fig.canvas)
        fig.canvas.setParent(self)
        self.sag_fig = ssp.SliceFigure(fig, extents[SAG], blit=BLITTING)
        self.sag_fig.ax.set_xlabel('posterior to anterior', fontsize=8)
        self.sag_fig.ax.set_ylabel('inferior to superior', fontsize=8)        
        self.horizontalLayout.addWidget(fig.canvas)
        
        # put down figures in x, y, z order
        self.figs = [self.sag_fig, self.cor_fig, self.axi_fig]
        self.canvas_lookup = dict( ((f.canvas, f) for f in self.figs) )
        self._mouse_dragging = False
        # this should be something like a signal too, which can emit status
        self._xyz_position = [0,0,0]
        self._connect_events()

        self.setParent(parent)
        QtGui.QWidget.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                                    QtGui.QSizePolicy.Expanding)
        QtGui.QWidget.updateGeometry(self)
        self._main_plotted = False
        self.main_plots = []
        self._over_plotted = False
        self.over_plots = []
Example #10
0
def setup_figure(*args, **kwargs):
    projection = kwargs.pop("projection","stereonet")
    fig = Figure(*args, **kwargs)
    fig.canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111, projection=projection)
    return fig,ax
Example #11
0
def main():
    matplotlib.use('TkAgg')
    root = Tk()
    root.title("数据预测")
    center_window(root)

    menu = Menu(root)
    root.config(menu=menu)
    # 创建File菜单,下面有Save和Exit两个子菜单
    file = Menu(menu, tearoff=0)
    file.add_command(label='保存图片', command=savePic)
    file.add_command(label='保存运行日志', command=saveLog)
    file.add_separator()
    file.add_command(label='退出', command=lambda: close_window(root))
    menu.add_cascade(label='文件', menu=file)
    # 创建about菜单
    about = Menu(menu, tearoff=0)
    about.add_command(label='关于', command=about_per)
    menu.add_cascade(label='关于', menu=about)

    global var_option
    var_option = StringVar(root)
    var_option.set("model1")
    OptionMenu(root, var_option, "model1", "model2", "model3",
               "model4").grid(row=0, column=0, padx=45, pady=10, sticky=W)

    global var_checkbutton
    var_checkbutton = IntVar()
    checkbutton = Checkbutton(root, text='是否选上', variable=var_checkbutton)
    checkbutton.grid(row=1, column=0, padx=45, pady=5, sticky=W)

    Label(root, text="待定1").grid(row=0, column=1, padx=20, pady=10, sticky=E)
    Label(root, text="待定2").grid(row=1, column=1, padx=20, pady=5, sticky=E)

    global var_entry1, var_entry2
    var_entry1 = StringVar()
    var_entry1.set("default value1")
    var_entry2 = StringVar()
    var_entry2.set("default value2")
    Entry(root, textvariable=var_entry1).grid(row=0,
                                              column=2,
                                              padx=0,
                                              pady=10,
                                              sticky=W)
    Entry(root, textvariable=var_entry2).grid(row=1,
                                              column=2,
                                              padx=0,
                                              pady=5,
                                              sticky=W)
    # 放置标签、文本框和按钮等部件,并设置文本框的默认值和按钮的事件函数
    Button(root, text='画图', width=12, height=1,
           command=drawPicFun).grid(row=0,
                                    column=3,
                                    padx=45,
                                    pady=10,
                                    sticky=E)
    Button(root, text='待定', width=12, height=1,
           command=undeterminted).grid(row=1,
                                       column=3,
                                       padx=45,
                                       pady=5,
                                       sticky=E)

    # 在Tk的GUI上放置一个画布,并用.grid()来调整布局
    global drawPic
    drawPic = Figure(figsize=(10.0, 5.0), dpi=80)
    drawPic.canvas = FigureCanvasTkAgg(drawPic, master=root)
    drawPic.canvas.show()
    drawPic.canvas.get_tk_widget().grid(row=2,
                                        columnspan=4,
                                        padx=45,
                                        pady=10,
                                        sticky=S + N + E + W)

    global message_frame
    message_frame = ShowMessageFrame()
    message_frame.frame.grid(row=3,
                             columnspan=4,
                             padx=45,
                             pady=5,
                             sticky=S + N + E + W)

    Label(root, text="powerd by Lab204").grid(row=4,
                                              column=3,
                                              padx=45,
                                              pady=5,
                                              sticky=E)
    # 启动事件循环
    root.mainloop()
Example #12
0
    def __init__(self, loc_connections, image_connections,
                 image_props_connections, bbox,
                 functional_manager=None,
                 external_loc=None, parent=None, main_ref=None,
                 tfbeam=None, **kwargs):
        """
        Creates a new MplQT4TimeFreqWindow, which controls interaction
        with Nutmeg TFBeam objects. This window is a QT4TopLevelAuxiliaryWindow,
        giving it top level status. It contains:
         *a 2D image of the time-frequency plane with selectable bins (emits a
          functional image update event and a tf event, described below)
         *a TFBeam management panel, with data management and feature
          localizations (events described below)
         *a threshold management panel, to create different mask criteria

         Time-frequency point updates cause emission of the tf_point signal.
         To cause methods to be connected to this signal, include them in the
         tf_connections iterable argument. Methods will have this signature
         pattern:
         meth(timept, freq_a, freq_b)

         Overlay image updates are also signalled. To cause methods to be
         connected, include them in the image_connections iterable argument.
         Methods will have this signature pattern:
         meth(obj)
          * obj will give access to obj.overlay, obj.alpha,
          * obj.norm, obj.fill_value

         Spatial location updates cause emission of the xyz_point signal. To
         cause methods to be connected to this signal, include them in the
         loc_connections interable argument. Methods will have this signature
         pattern:
         meth(x, y, z)

         Parameters
         ----------
         loc_connections: iterable
             Methods to connect to the xyz_point signal
         image_connections: iterable
             Methods to connect to the new_image signal
         parent: QObject (optional)
             A QT4 QObject to set as the parent of this widget (thus causing
             this widget NOT to run as a top level window)
         main_ref: QObject (optional)
             A QT4 QObject to be considered as the "parent" of this widget,
             when this widget is running as a top level window
         tfbeam: TFBeam (optional)
             A TFBeam with which to preload the beam manager.
         **kwargs:
             figsize, dpi for the time-frequency plane figure
         """

        
        figsize = kwargs.pop('figsize', (6,4))
        dpi = kwargs.pop('dpi', 100)
        # insert some local callbacks into the connection lists
        image_connections = (self._update_from_new_overlay,) + \
                            image_connections
        image_props_connections = (self.update_tf_figure,) + \
                                  image_props_connections
        OverlayWindowInterface.__init__(self,
                                        loc_connections,
                                        image_connections,
                                        image_props_connections,
                                        bbox,
                                        external_loc=external_loc,
                                        parent=parent,
                                        main_ref=main_ref,
                                        functional_manager=functional_manager)

        # make sure that when the tfbeam manager's voxel index changes,
        # the tfplane image gets updated
        self.bvox_signal.connect(self.update_tf_figure)
        if functional_manager is None or \
           not isinstance(functional_manager, TFBeamManager):
            self.func_man = TFBeamManager(
                bbox, image_signal = self.image_changed,
                loc_signal = self.loc_changed,
                props_signal = self.image_props_changed,
                beam_vox_signal=self.bvox_signal
                )

        self.func_man.beam_vox_signal = self.bvox_signal
        
        vbox = QtGui.QVBoxLayout(self)

        # set up figure
        fig = Figure(figsize=figsize, dpi=dpi)
        fig.canvas = Canvas(fig)
        QtGui.QWidget.setSizePolicy(fig.canvas,
                                    QtGui.QSizePolicy.Expanding,
                                    QtGui.QSizePolicy.Expanding)
        Canvas.updateGeometry(fig.canvas)
        fig.canvas.setParent(self)
        self.fig = fig

        # fake plane at first
        self.tf_plane = self._initialize_tf_plane()
        vbox.addWidget(self.fig.canvas)

        vbox.addWidget(self.func_man.make_panel(parent=self))

        QtGui.QWidget.setSizePolicy(self,
                                    QtGui.QSizePolicy.Expanding,
                                    QtGui.QSizePolicy.Expanding)
        self.updateGeometry()
        if tfbeam is not None:
            self.func_man.update_beam(tfbeam)
Example #13
0
def plot_aligned(pca, sparse=True, **kwargs):
    """ Plots the residuals of a principal component
        analysis of attiude data.
    """
    colormap = kwargs.pop('colormap',None)

    A = pca.rotated()
    # Flip the result if upside down
    if pca.normal[2] < 0:
        A[:,-1] *= -1
    minmax = [(A[:,i].min(),A[:,i].max()) for i in range(3)]
    lengths = [j-i for i,j in minmax]

    if sparse:
        i = 1
        l = len(A)
        if l > 10000:
            i = N.ceil(l/10000)
            A = A[::int(i)]

    log.info("Plotting with {} points".format(len(A)))

    w = 8
    ratio = (lengths[2]*2+lengths[1])/lengths[0]*1.5
    h = w*ratio
    if h < 3: h = 3

    r = (lengths[1]+5)/(lengths[2]+5)
    if r > 5:
        r = 5

    fig = Figure(figsize=(w,h))
    fig.canvas = FigureCanvas(fig)

    def setup_axes():
        gs = GridSpec(3,1, height_ratios=[r,1,1])
        kwargs = dict()
        axes = []
        for g in gs:
            ax = fig.add_subplot(g,**kwargs)
            kwargs['sharex'] = ax
            yield ax

    axes = list(setup_axes())

    fig.subplots_adjust(hspace=0, wspace=0.1)

    #lengths = attitude.pca.singular_values[::-1]

    titles = (
        "Plan view",
        "Long cross-section",
        "Short cross-section")

    ylabels = (
        "Meters",
        "Residuals (m)",
        "Residuals (m)")

    colors = ['cornflowerblue','red']

    hyp = sampling_axes(pca)
    vertical = vector(0,0,1)

    for title,ax,(a,b),ylabel in zip(titles,axes,
            [(0,1),(0,2),(1,2)],ylabels):

        kw = dict(linewidth=2, alpha=0.5)
        bounds = minmax[a]
        if b != 2:
            ax.plot(bounds,(0,0), c=colors[a], **kw)
            ax.plot((0,0),minmax[b], c=colors[b], **kw)
        else:
            ax.plot(bounds,(-10,-10), c=colors[a], **kw)
            v0 = N.zeros(3)
            v0[a] = 1
            axes = N.array([v0,vertical])

            ax_ = ([email protected](hyp)@axes.T).T
            ax_ = N.sqrt(ax_)
            l1 = N.linalg.norm(ax_[:-1])
            l2 = N.linalg.norm(ax_[-1])
            ang_error = 2*N.degrees(N.arctan2(l2,l1))

            title += ": {:.0f} m long, angular error (95% CI): {:.2f}º".format(lengths[a], ang_error)

            bounds = minmax[0]
            x_ = N.linspace(bounds[0]*1.2,bounds[1]*1.2,100)

            err = HyperbolicErrors(hyp,x_,axes=axes)
            err.plot(ax, fc='#cccccc', alpha=0.3)

        x,y = A[:,a], A[:,b]
        kw = dict(alpha=0.5, zorder=5)

        if colormap is None:
            ax.plot(x,y,c="#555555", linestyle='None', marker='.',**kw)
        else:
            ax.scatter(x,y,c=A[:,-1], cmap=colormap, **kw)

        #ax.set_aspect("equal")

        ax.text(0.01,.99,title,
            verticalalignment='top',
            transform=ax.transAxes)
        #ax.autoscale(tight=True)
        ax.yaxis.set_ticks([])
        ax.xaxis.set_ticks_position('bottom')
        if a != 1:
            pass
            #ax.xaxis.set_ticks([])
            #ax.spines['bottom'].set_color('none')
        for spine in ax.spines.values():
            spine.set_visible(False)


    ax.text(0.99,0.99,"Max residual: {:.1f} m".format(lengths[2]),
        verticalalignment='bottom',
        ha='right',
        transform=ax.transAxes)


    ax.set_xlabel("Meters")
    return fig
Example #14
0
#%% Script
if __name__ == '__main__':
    # data
    time = np.arange(0, 10)
    data = np.sin(time)
    this_title = 'Sin vs. Time'

    # create GUI for figure
    frame = QMainWindow()
    gui_widget = QWidget(frame)
    frame.setCentralWidget(gui_widget)
    layout = QVBoxLayout(gui_widget)

    # create figure
    fig = Figure()
    fig.canvas = FigureCanvas(fig)
    fig.canvas.manager.set_window_title(this_title)
    fig.canvas.toolbar = NavigationToolbar(fig.canvas, frame)

    # add figure to GUI
    layout.addWidget(fig.canvas.toolbar)
    layout.addWidget(fig.canvas)

    # add an axis and plot the data
    ax = fig.add_subplot(111)
    ax.plot(time, data, '.-', label='Sin')

    # add labels and legends
    ax.set_xlabel('Time')
    ax.set_ylabel('Amp')
    ax.set_title(this_title)