Python pylab() Examples

The following are 30 code examples of pylab(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: __init__.py    From EDeN with MIT License 11 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, size=None, normalize=False):
    """plot_confusion_matrix."""
    cm = confusion_matrix(y_true, y_pred)
    fmt = "%d"
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        fmt = "%.2f"
    xticklabels = list(sorted(set(y_pred)))
    yticklabels = list(sorted(set(y_true)))
    if size is not None:
        plt.figure(figsize=(size, size))
    heatmap(cm, xlabel='Predicted label', ylabel='True label',
            xticklabels=xticklabels, yticklabels=yticklabels,
            cmap=plt.cm.Blues, fmt=fmt)
    if normalize:
        plt.title("Confusion matrix (norm.)")
    else:
        plt.title("Confusion matrix")
    plt.gca().invert_yaxis() 
Example #2
Source File: proj3d.py    From opticspy with MIT License 7 votes vote down vote up
def test_lines_dists():
    import pylab
    ax = pylab.gca()

    xs, ys = (0,30), (20,150)
    pylab.plot(xs, ys)
    points = list(zip(xs, ys))
    p0, p1 = points

    xs, ys = (0,0,20,30), (100,150,30,200)
    pylab.scatter(xs, ys)

    dist = line2d_seg_dist(p0, p1, (xs[0], ys[0]))
    dist = line2d_seg_dist(p0, p1, np.array((xs, ys)))
    for x, y, d in zip(xs, ys, dist):
        c = Circle((x, y), d, fill=0)
        ax.add_patch(c)

    pylab.xlim(-200, 200)
    pylab.ylim(-200, 200)
    pylab.show() 
Example #3
Source File: megafacade.py    From facade-segmentation with MIT License 6 votes vote down vote up
def plot_regions(self, fill=True, bgimage=None, alpha=0.5):
        import pylab as pl
        ax = pl.gca()
        assert isinstance(ax, pl.Axes)

        colors = i12.JET_12

        self._plot_background(bgimage)

        for label in self.regions:
            color = colors[i12.LABELS.index(label)] / 255.

            for region in self.regions[label]:
                t = region['top']
                l = self.facade_left + region['left']
                b = region['bottom']
                r = self.facade_left + region['right']
                patch = pl.Rectangle((l, t), r - l, b - t, color=color, fill=fill, alpha=alpha)
                ax.add_patch(patch) 
Example #4
Source File: proj3d.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def test_lines_dists():
    import pylab
    ax = pylab.gca()

    xs, ys = (0,30), (20,150)
    pylab.plot(xs, ys)
    points = zip(xs, ys)
    p0, p1 = points

    xs, ys = (0,0,20,30), (100,150,30,200)
    pylab.scatter(xs, ys)

    dist = line2d_seg_dist(p0, p1, (xs[0], ys[0]))
    dist = line2d_seg_dist(p0, p1, np.array((xs, ys)))
    for x, y, d in zip(xs, ys, dist):
        c = Circle((x, y), d, fill=0)
        ax.add_patch(c)

    pylab.xlim(-200, 200)
    pylab.ylim(-200, 200)
    pylab.show() 
Example #5
Source File: proj3d.py    From Computable with MIT License 6 votes vote down vote up
def test_lines_dists():
    import pylab
    ax = pylab.gca()

    xs, ys = (0,30), (20,150)
    pylab.plot(xs, ys)
    points = zip(xs, ys)
    p0, p1 = points

    xs, ys = (0,0,20,30), (100,150,30,200)
    pylab.scatter(xs, ys)

    dist = line2d_seg_dist(p0, p1, (xs[0], ys[0]))
    dist = line2d_seg_dist(p0, p1, np.array((xs, ys)))
    for x, y, d in zip(xs, ys, dist):
        c = Circle((x, y), d, fill=0)
        ax.add_patch(c)

    pylab.xlim(-200, 200)
    pylab.ylim(-200, 200)
    pylab.show() 
Example #6
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def scale_x(scale, axes="current"):
    """

    This function scales lines horizontally.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            line.set_xdata(_pylab.array(line.get_xdata())*scale)

    # update the title
    title = axes.title.get_text()
    title += ", x_scale="+str(scale)
    axes.title.set_text(title)

    # zoom to surround the data properly
    auto_zoom() 
Example #7
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def impose_legend_limit(limit=30, axes="gca", **kwargs):
    """
    This will erase all but, say, 30 of the legend entries and remake the legend.
    You'll probably have to move it back into your favorite position at this point.
    """
    if axes=="gca": axes = _pylab.gca()

    # make these axes current
    _pylab.axes(axes)

    # loop over all the lines_pylab.
    for n in range(0,len(axes.lines)):
        if n >  limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("_nolegend_")
        if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("...")

    _pylab.legend(**kwargs) 
Example #8
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_click_xshift(axes = "gca"):
    """
    Takes a starting and ending point, then shifts the image y by this amount
    """
    if axes == "gca": axes = _pylab.gca()

    try:
        p1 = _pylab.ginput()
        p2 = _pylab.ginput()

        xshift = p2[0][0]-p1[0][0]

        e = axes.images[0].get_extent()

        e[0] = e[0] + xshift
        e[1] = e[1] + xshift

        axes.images[0].set_extent(e)

        _pylab.draw()
    except:
        print("whoops") 
Example #9
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_shift(xshift=0, yshift=0, axes="gca"):
    """
    This will shift an image to a new location on x and y.
    """

    if axes=="gca": axes = _pylab.gca()

    e = axes.images[0].get_extent()

    e[0] = e[0] + xshift
    e[1] = e[1] + xshift
    e[2] = e[2] + yshift
    e[3] = e[3] + yshift

    axes.images[0].set_extent(e)

    _pylab.draw() 
Example #10
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def image_set_clim(zmin=None, zmax=None, axes="gca"):
    """
    This will set the clim (range) of the colorbar.

    Setting zmin or zmax to None will not change them.
    Setting zmin or zmax to "auto" will auto-scale them to include all the data.
    """
    if axes=="gca": axes=_pylab.gca()

    image = axes.images[0]

    if zmin=='auto': zmin = _n.min(image.get_array())
    if zmax=='auto': zmax = _n.max(image.get_array())

    if zmin==None: zmin = image.get_clim()[0]
    if zmax==None: zmax = image.get_clim()[1]

    image.set_clim(zmin, zmax)

    _pylab.draw() 
Example #11
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def set_all_line_attributes(attribute="lw", value=2, axes="current", refresh=True):
    """

    This function sets all the specified line attributes.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # loop over the lines and trim the data
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            _pylab.setp(line, attribute, value)

    # update the plot
    if refresh: _pylab.draw() 
Example #12
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def line_math(fx=None, fy=None, axes='gca'):
    """
    applies function fx to all xdata and fy to all ydata.
    """

    if axes=='gca': axes = _pylab.gca()

    lines = axes.get_lines()

    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):
            xdata, ydata = line.get_data()
            if not fx==None: xdata = fx(xdata)
            if not fy==None: ydata = fy(ydata)
            line.set_data(xdata,ydata)

    _pylab.draw() 
Example #13
Source File: render_sdf.py    From PointNetGPD with MIT License 6 votes vote down vote up
def render_sdf(obj_, object_name_):
    plt.figure()
    # ax = h.add_subplot(111, projection='3d')

    # surface_points = np.where(np.abs(sdf.sdf_values) < thresh)
    # surface_points = np.array(surface_points)
    # surface_points = surface_points[:, np.random.choice(surface_points[0].size, 3000, replace=True)]
    # # from IPython import embed; embed()
    surface_points = obj_.sdf.surface_points()[0]
    surface_points = np.array(surface_points)
    ind = np.random.choice(np.arange(len(surface_points)), 1000)
    x = surface_points[ind, 0]
    y = surface_points[ind, 1]
    z = surface_points[ind, 2]

    ax = plt.gca(projection=Axes3D.name)
    ax.scatter(x, y, z, '.', s=np.ones_like(x) * 0.3, c='b')
    ax.set_xlim3d(0, obj_.sdf.dims_[0])
    ax.set_ylim3d(0, obj_.sdf.dims_[1])
    ax.set_zlim3d(0, obj_.sdf.dims_[2])
    plt.title(object_name_)
    plt.show() 
Example #14
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 6 votes vote down vote up
def plot(ifile, varkey, options, before='', after=''):
    import pylab as pl
    outpath = getattr(options, 'outpath', '.')
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 1:
        raise ValueError(
            'Plots can have only 1 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    exec(before)
    ax = pl.gca()
    print(varkey, end='')
    if options.logscale:
        ax.set_yscale('log')

    ax.plot(var[:].squeeze())
    ax.set_xlabel('unknown')
    ax.set_ylabel(getattr(var, 'standard_name',
                          varkey).strip() + ' ' + var.units.strip())
    fmt = 'png'
    figpath = os.path.join(outpath + '_1d_' + varkey + '.' + fmt)
    exec(after)
    pl.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #15
Source File: VOCpr.py    From face-magnet with Apache License 2.0 6 votes vote down vote up
def drawPrfast(tp, fp, tot, show=True, col="g"):
    tp = numpy.cumsum(tp)
    fp = numpy.cumsum(fp)
    rec = tp / tot
    prec = tp / (fp + tp)
    ap = VOColdap(rec, prec)
    ap1 = VOCap(rec, prec)
    if show:
        pylab.plot(rec, prec, '-%s' % col)
        pylab.title("AP=%.1f 11pt(%.1f)" % (ap1 * 100, ap * 100))
        pylab.xlabel("Recall")
        pylab.ylabel("Precision")
        pylab.grid()
        pylab.gca().set_xlim((0, 1))
        pylab.gca().set_ylim((0, 1))
        pylab.show()
        pylab.draw()
    return rec, prec, ap1 
Example #16
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def reverse_draw_order(axes="current"):
    """

    This function takes the graph and reverses the draw order.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    lines = axes.get_lines()

    # reverse the order
    lines.reverse()

    for n in range(0, len(lines)):
        if isinstance(lines[n], _mpl.lines.Line2D):
            axes.lines[n]=lines[n]

    _pylab.draw() 
Example #17
Source File: functional_map.py    From cmm with GNU General Public License v2.0 6 votes vote down vote up
def plot_functional_map(C, newfig=True):
    vmax = max(np.abs(C.max()), np.abs(C.min()))
    vmin = -vmax
    C = ((C - vmin) / (vmax - vmin)) * 2 - 1
    if newfig:
        pl.figure(figsize=(5,5))
    else:
        pl.clf()
    ax = pl.gca()
    pl.pcolor(C[::-1], edgecolor=(0.9, 0.9, 0.9, 1), lw=0.5,
              vmin=-1, vmax=1, cmap=nice_mpl_color_map())
    # colorbar
    tick_locs   = [-1., 0.0, 1.0]
    tick_labels = ['min', 0, 'max']
    bar = pl.colorbar()
    bar.locator = matplotlib.ticker.FixedLocator(tick_locs)
    bar.formatter = matplotlib.ticker.FixedFormatter(tick_labels)
    bar.update_ticks()
    ax.set_aspect(1)
    pl.xticks([])
    pl.yticks([])
    if newfig:
        pl.show() 
Example #18
Source File: plot.py    From minian with GNU General Public License v3.0 6 votes vote down vote up
def plot_spatial(alist, idlist=None, dims=None, ax=None, cmaplist=None):
    if not idlist:
        idlist = []
        for cur_a in alist:
            idlist.append(np.arange(cur_a.shape[-1]))
    if not cmaplist:
        cmaplist = []
        cmaplist = ['gray'] * len(alist)
    if not ax:
        ax = pl.gca()
        ax.set_facecolor('white')
    for ida, a in enumerate(alist):
        if np.ndim(a) < 3:
            a = a.reshape(np.append(dims, [-1]))
        for idx in idlist[ida]:
            ax.imshow(
                np.ma.masked_equal(a[:, :, idx], 0),
                alpha=0.5,
                cmap=cmaplist[ida])
    return ax 
Example #19
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
    """
    This function does nearest-neighbor coarsening of the data. See 
    spinmob.fun.coarsen_data for more information.
    
    Parameters
    ----------
    level=2
        How strongly to coarsen.
    exponential=False
        If True, use the exponential method (great for log-x plots).
    axes="all"
        Which axes to coarsen.
    figure=None
        Which figure to use.
    
    """
    if axes=="gca": axes=_pylab.gca()
    if axes=="all":
        if not figure: f = _pylab.gcf()
        axes = f.axes

    if not _fun.is_iterable(axes): axes = [axes]

    for a in axes:
        # get the lines from the plot
        lines = a.get_lines()

        # loop over the lines and trim the data
        for line in lines:
            if isinstance(line, _mpl.lines.Line2D):
                coarsen_line(line, level, exponential, draw=False)
    _pylab.draw() 
Example #20
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def save_plot(axes="gca", path=None):
    """
    Saves the figure in my own ascii format
    """

    global line_attributes

    # choose a path to save to
    if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    if not path.split(".")[-1] == "plot": path = path+".plot"

    f = file(path, "w")

    # if no argument was given, get the current axes
    if axes=="gca": axes=_pylab.gca()

    # now loop over the available lines
    f.write("title="  +axes.title.get_text().replace('\n', '\\n')+'\n')
    f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n')
    f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n')

    for l in axes.lines:
        # write the data header
        f.write("trace=new\n")
        f.write("legend="+l.get_label().replace('\n', '\\n')+"\n")

        for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n")

        # get the data
        x = l.get_xdata()
        y = l.get_ydata()

        # loop over the data
        for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n")

    f.close() 
Example #21
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_line_attribute(line=-1, attribute="lw", value=2, axes="current", refresh=True):
    """

    This function sets all the specified line attributes.

    """

    if axes=="current": axes = _pylab.gca()

    # get the lines from the plot
    line = axes.get_lines()[-1]
    _pylab.setp(line, attribute, value)

    # update the plot
    if refresh: _pylab.draw() 
Example #22
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_markers(marker="o", axes="current"):
    if axes == "current": axes = _pylab.gca()
    set_all_line_attributes("marker", marker, axes) 
Example #23
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def invert(axes="current"):
    """

    inverts the plot

    """
    if axes=="current": axes = _pylab.gca()
    scale_y(-1,axes) 
Example #24
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def smooth_selected_trace(trim=True, axes="gca"):
    """

    This cycles through all the lines in a set of axes, highlighting them,
    and asking for how much you want to smooth by (0 or <enter> is valid)

    """

    if axes=="gca": axes = _pylab.gca()

    # get all the lines
    lines = axes.get_lines()

    for line in lines:

        if isinstance(line, _mpl.lines.Line2D):
            # first highlight it
            fatten_line(line)

            # get the smoothing factor
            ready = 0
            while not ready:
                response = input("Smoothing Factor (<enter> to skip): ")
                try:
                    int(response)
                    ready=1
                except:
                    if response=="\n": ready = 1
                    else:              print("No!")

            if not response == "\n":
                smooth_line(line, int(response), trim)

            # return the line to normal
            unfatten_line(line) 
Example #25
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def modify_legend(axes="gca"):
    # get the axes
    if axes=="gca": axes = _pylab.gca()

    # get the lines
    lines = axes.get_lines()

    # loop over the lines
    for line in lines:
        if isinstance(line, _mpl.lines.Line2D):

            # highlight the line
            fatten_line(line)

            # get the label (from the legend)
            label = line.get_label()

            print(label)

            new_label = input("New Label: ")
            if new_label == "q" or new_label == "quit":
                unfatten_line(line)
                return

            if not new_label == "\n": line.set_label(new_label)

            unfatten_line(line)
            format_figure() 
Example #26
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def legend(location='best', fontsize=16, axes="gca"):
    if axes=="gca": axes = _pylab.gca()

    axes.legend(loc=location, prop=_mpl.font_manager.FontProperties(size=fontsize))
    _pylab.draw()




#
# Style cycle, available for use in plotting
# 
Example #27
Source File: helper.py    From KittiSeg with MIT License 5 votes vote down vote up
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
Example #28
Source File: complete_faces.py    From fancyimpute with Apache License 2.0 5 votes vote down vote up
def save_images(self, images, base_filename, flattened=True):
        self.ensure_dir(self.dirname)
        for i in self.saved_image_indices:
            label = self.labels[i].lower().replace(" ", "_")
            image = images[i, :].copy()
            if flattened:
                image = image.reshape(self.image_shape)
            image[np.isnan(image)] = 0
            figure = pylab.gcf()
            axes = pylab.gca()
            extra_kwargs = {}
            if self.color:
                extra_kwargs["cmap"] = "gray"
            assert image.min() >= 0, "Image can't contain negative numbers"
            if image.max() <= 1:
                image *= 256
            image[image > 255] = 255
            axes.imshow(image.astype("uint8"), **extra_kwargs)
            axes.get_xaxis().set_visible(False)
            axes.get_yaxis().set_visible(False)
            filename = base_filename + ".png"
            subdir = join(self.dirname, label)
            self.ensure_dir(subdir)
            path = join(subdir, filename)
            figure.savefig(
                path,
                bbox_inches='tight')
            self.saved_images[i][base_filename] = path 
Example #29
Source File: window.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,
            yaxis_label_position="right"):
        """Plotting method to plot both time and frequency domain results.

        See :meth:`plot_frequencies` for the optional arguments.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.plot_time_freq()

        """
        from pylab import subplot, gca

        subplot(1, 2, 1)
        self.plot_window()

        subplot(1, 2, 2)
        self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm)

        if yaxis_label_position=="left":
            try: tight_layout()
            except: pass
        else:
            ax = gca()
            ax.yaxis.set_label_position("right") 
Example #30
Source File: _melt.py    From UWGeodynamics with GNU General Public License v3.0 5 votes vote down vote up
def plot(self, pressure):
        import pylab as plt
        temperature = dimensionalise(self.temperature(pressure), u.kelvin)
        pressure = dimensionalise(pressure, u.pascal)
        plt.plot(temperature, pressure)
        plt.gca().invert_yaxis()
        plt.show()