Python matplotlib.pyplot.hold() Examples

The following are code examples for showing how to use matplotlib.pyplot.hold(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: gardenia   Author: xuzhenqi   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def show(img, show_max=False):
    '''show response map'''
    img = img - img.min()
    img = img / img.max()
    plt.imshow(img, cmap='gray')
    shape = img.shape
    idx = np.argmax(img)
    hi = idx / shape[1]
    wi = idx % shape[1]
    print hi, wi
    if show_max:
        plt.hold(True)
        plt.plot(wi, hi, 'r.', markersize=12)
        plt.axis('off')
        plt.axis('image')
    plt.show() 
Example 2
Project: radiometric_normalization   Author: planetlabs   File: display.py    Apache License 2.0 6 votes vote down vote up
def plot_histograms(file_name, candidate_data_multiple_bands,
                    reference_data_multiple_bands=None,
                    # Default is for Blue-Green-Red-NIR:
                    colour_order=['b', 'g', 'r', 'y'],
                    x_limits=None, y_limits=None):
    logging.info('Display: Creating histogram plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hold(True)
    for colour, c_band in zip(colour_order, candidate_data_multiple_bands):
        c_bh, c_bins = numpy.histogram(c_band, bins=256)
        plt.plot(c_bins[:-1], c_bh, color=colour, linestyle='-', linewidth=2)
    if reference_data_multiple_bands:
        for colour, r_band in zip(colour_order, reference_data_multiple_bands):
            r_bh, r_bins = numpy.histogram(r_band, bins=256)
            plt.plot(
                r_bins[:-1], r_bh, color=colour, linestyle='--', linewidth=2)
    plt.xlabel('DN')
    plt.ylabel('Number of pixels')
    if x_limits:
        plt.xlim(x_limits)
    if y_limits:
        plt.ylim(y_limits)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig) 
Example 3
Project: laplacian-meshes   Author: bmershon   File: Utilities2D.py    GNU General Public License v3.0 6 votes vote down vote up
def getBarycentricCoords(A, B, C, X, checkValidity = True):
    T = np.array( [ [A.x - C.x, B.x - C.x ], [A.y - C.y, B.y - C.y] ] )
    y = np.array( [ [X.x - C.x], [X.y - C.y] ] )
    lambdas = linalg.solve(T, y)
    lambdas = lambdas.flatten()
    lambdas = np.append(lambdas, 1 - (lambdas[0] + lambdas[1]))
    if checkValidity:
        if (lambdas[0] < 0 or lambdas[1] < 0 or lambdas[2] < 0):
            print "ERROR: Not a convex combination; lambda = %s"%lambdas
            print "pointInsideConvexPolygon2D = %s"%pointInsideConvexPolygon2D([A, B, C], X, 0)
            plt.plot([A.x, B.x, C.x, A.x], [A.y, B.y, C.y, A.y], 'r')
            plt.hold(True)
            plt.plot([X.x], [X.y], 'b.')
            plt.show()
        assert (lambdas[0] >= 0 and lambdas[1] >= 0 and lambdas[2] >= 0)
    else:
        lambdas[0] = max(lambdas[0], 0)
        lambdas[1] = max(lambdas[1], 0)
        lambdas[2] = max(lambdas[2], 0)
    return lambdas 
Example 4
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 6 votes vote down vote up
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 5
Project: SlidingWindowVideoTDA   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 6 votes vote down vote up
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm', axcolor = np.array([0.0, 0.0, 0.0]), marker = None):
    if dgm.size == 0:
        return
    # Create Lists
    # set axis values
    axMin = np.min(dgm)
    axMax = np.max(dgm)
    axRange = axMax-axMin
    a = max(axMin - axRange/5, 0)
    b = axMax+axRange/5
    # plot line
    plt.plot([a, b], [a, b], c = axcolor, label = 'none')
    plt.hold(True)
    # plot points
    if marker:
        H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, marker, label=label, edgecolor = 'none')
    else:
        H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, label=label, edgecolor = 'none')
    # add labels
    plt.xlabel('Time of Birth')
    plt.ylabel('Time of Death')
    return H 
Example 6
Project: ebola_eradication   Author: anindyabd   File: diff_eq.py    MIT License 6 votes vote down vote up
def draw_figure(y, figno, figname):

    times = linspace(0, 300, 400)
    plt.figure(figno)
    plt.plot(times, y[:,0], '-g', label='S') 
    plt.plot(times, y[:,1], '-y', label='E')
    plt.plot(times, y[:,2], '-b', label='I') 
    plt.plot(times, y[:,3], '-m', label='H') 
    plt.plot(times, y[:,4], '-c', label='F')
    plt.plot(times, y[:,5], '#2E0854', label='M')  
    plt.plot(times, y[:,6], '-r', label='R') 
    plt.legend() 
    #plt.title('Figure ' + str(figno))
    plt.xlabel('Time (days)')
    plt.ylabel('Population')
    plt.savefig(figname)
    #plt.hold(False) 
Example 7
Project: SamplingBasedPlanning   Author: ryanfarr01   File: collisions.py    MIT License 6 votes vote down vote up
def draw(self, q, color='b', show=False, base_color='g'):
        '''
        Draw the robot with the provided configuration
        '''
        plotter.hold(True)
        pts = self.fk(q)
        for i, p in enumerate(pts):
            if i == 0:
                style = base_color+'o'
            else:
                style = color+'o'
            plotter.plot(p[0], p[1], style)
            if i > 0:
                plotter.plot([prev_p[0], p[0]],
                             [prev_p[1], p[1]], color)
            prev_p = p[:]
        if show:
            plotter.show() 
Example 8
Project: Emergence   Author: LennonLab   File: macroecotools.py    MIT License 6 votes vote down vote up
def plot_SARs(list_of_A_and_S):
    """Plot multiple SARs on a single plot. 
    
    Input: a list of lists, each sublist contains one vector for S and one vector for A.
    Output: a graph with SARs plotted on log-log scale, with colors spanning the spectrum.
    
    """
    N = len(list_of_A_and_S)
    HSV_tuples = [(x * 1.0 / N, 0.5, 0.5) for x in range(N)]
    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
    for i in range(len(list_of_A_and_S)):
        sublist = list_of_A_and_S[i]
        plt.loglog(sublist[0], sublist[1], color = RGB_tuples[i])
    plt.hold(False)
    plt.xlabel('Area')
    plt.ylabel('Richness') 
Example 9
Project: Emergence   Author: LennonLab   File: mete.py    MIT License 6 votes vote down vote up
def plot_universal_curve(slopes_data):
    """plots ln(N/S) x slope for empirical data and MaxEnt predictions.

    Predictions should look like Harte's universal curve
    input data is a list of lists. Each list contains:
    [area, empirical slope, predicted slope, N/S]

    """
    #TO DO: Add argument for axes
    slopes = array(slopes_data)
    NS = slopes[:, 3]
    z_pred = slopes[:, 2]
    z_obs = slopes[:, 1]
    #plot Harte's universal curve from predictions with empirical data to analyze fit
    plt.semilogx(NS, z_pred, 'bo')
    plt.xlabel("ln(N/S)")
    plt.ylabel("Slope")
    plt.hold(True)
    plt.semilogx(NS, z_obs, 'ro')
    plt.show() 
Example 10
Project: Math412S2017   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 6 votes vote down vote up
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm', axcolor = np.array([0.0, 0.0, 0.0]), marker = None):
    if dgm.size == 0:
        return
    # Create Lists
    # set axis values
    axMin = np.min(dgm)
    axMax = np.max(dgm)
    axRange = axMax-axMin
    a = max(axMin - axRange/5, 0)
    b = axMax+axRange/5
    # plot line
    plt.plot([a, b], [a, b], c = axcolor, label = 'none')
    plt.hold(True)
    # plot points
    if marker:
        H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, marker, label=label, edgecolor = 'none')
    else:
        H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, label=label, edgecolor = 'none')
    # add labels
    plt.xlabel('Time of Birth')
    plt.ylabel('Time of Death')
    return H 
Example 11
Project: Math412S2017   Author: ctralie   File: ImagePatches.py    Apache License 2.0 6 votes vote down vote up
def plotLinePatches(P, name):
    plotPatches(P)
    plt.savefig("%sPatches.svg"%name, bbox_inches='tight')
    plt.clf()
    sio.savemat("P%s.mat"%name, {"P":P})

    plt.subplot(121)
    PDs = doRipsFiltration(P, 2, coeff = 2)
    print PDs[2]
    H1 = plotDGM(PDs[1], color = np.array([1.0, 0.0, 0.2]), label = 'H1', sz = 50, axcolor = np.array([0.8]*3))
    plt.hold(True)
    H2 = plotDGM(PDs[2], color = np.array([0.43, 0.67, 0.27]), marker = 'x', sz = 50, label = 'H2', axcolor = np.array([0.8]*3))
    plt.title("$\mathbb{Z}2$ Coefficients")

    plt.subplot(122)
    PDs = doRipsFiltration(P, 2, coeff = 3)
    print PDs[2]
    H1 = plotDGM(PDs[1], color = np.array([1.0, 0.0, 0.2]), label = 'H1', sz = 50, axcolor = np.array([0.8]*3))
    plt.hold(True)
    H2 = plotDGM(PDs[2], color = np.array([0.43, 0.67, 0.27]), marker = 'x', sz = 50, label = 'H2', axcolor = np.array([0.8]*3))
    plt.title("$\mathbb{Z}3$ Coefficients")
    plt.show() 
Example 12
Project: SynthText   Author: ankush-me   File: synthgen.py    Apache License 2.0 6 votes vote down vote up
def viz_textbb(fignum,text_im, bb_list,alpha=1.0):
    """
    text_im : image containing text
    bb_list : list of 2x4xn_i boundinb-box matrices
    """
    plt.close(fignum)
    plt.figure(fignum)
    plt.imshow(text_im)
    plt.hold(True)
    H,W = text_im.shape[:2]
    for i in xrange(len(bb_list)):
        bbs = bb_list[i]
        ni = bbs.shape[-1]
        for j in xrange(ni):
            bb = bbs[:,:,j]
            bb = np.c_[bb,bb[:,0]]
            plt.plot(bb[0,:], bb[1,:], 'r', linewidth=2, alpha=alpha)
    plt.gca().set_xlim([0,W-1])
    plt.gca().set_ylim([H-1,0])
    plt.show(block=False) 
Example 13
Project: Email-Classification-NNs   Author: 01dkg   File: kerasExperiments.py    GNU General Public License v3.0 6 votes vote down vote up
def make_plots(xs, ys, labels, title=None, x_name=None, y_name=None, y_bounds=None, save_to=None):
    colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
    handles = []
    plt.figure()
    plt.hold(True)
    for i in range(len(labels)):
        plot, = make_plot(xs[i], ys[i], color=colors[i % len(colors)], new_fig=False)
        handles.append(plot)
    plt.legend(handles, labels)
    if title is not None:
        plt.title(title)
    if x_name is not None:
        plt.xlabel(x_name)
    if y_name is not None:
        plt.ylabel(y_name)
    if y_bounds is not None:
        plt.ylim(y_bounds)
    if save_to is not None:
        plt.savefig(save_to, bbox_inches='tight')
    plt.hold(False) 
Example 14
Project: ConvNetQuake   Author: tperol   File: fig_comparison.py    MIT License 6 votes vote down vote up
def fig_memory_usage():

    # FAST memory
    x = [1,3,7,14,30,90,180]
    y_fast = [0.653,1.44,2.94,4.97,9.05,19.9,35.2]
    # ConvNetQuake
    y_convnet = [6.8*1e-5]*7
    # Create figure
    plt.loglog(x,y_fast,"o-")
    plt.hold('on')
    plt.loglog(x,y_convnet,"o-")
    # plot markers
    plt.loglog(x,[1e-5,1e-5,1e-5,1e-5,1e-5,1e-5,1e-5],'o')
    plt.ylabel("Memory usage (GB)")
    plt.xlabel("Continous data duration (days)")
    plt.xlim(1,180)
    plt.grid("on")
    plt.savefig("./figures/memoryusage.eps")
    plt.close() 
Example 15
Project: ConvNetQuake   Author: tperol   File: fig_comparison.py    MIT License 6 votes vote down vote up
def fig_run_time():
    # fast run time
    x_fast = [1,3,7,14,30,90,180]
    y_fast = [289,1.13*1e3,2.48*1e3,5.41*1e3,1.56*1e4,
              6.61*1e4,1.98*1e5]
    x_auto = [1,3]
    y_auto = [1.54*1e4, 8.06*1e5]
    x_convnet = [1,3,7,14,30]
    y_convnet = [9,27,61,144,291]
    # create figure
    plt.loglog(x_auto,y_auto,"o-")
    plt.hold('on')
    plt.loglog(x_fast[0:5],y_fast[0:5],"o-")
    plt.loglog(x_convnet,y_convnet,"o-")
    # plot x markers
    plt.loglog(x_convnet,[1e0]*len(x_convnet),'o')
    # plot y markers
    y_markers = [1,60,3600,3600*24]
    plt.plot([1]*4,y_markers,'ko')
    plt.ylabel("run time (s)")
    plt.xlabel("continous data duration (days)")
    plt.xlim(1,35)
    plt.grid("on")
    plt.savefig("./figures/runtimes.eps") 
Example 16
Project: imtools   Author: mjirik   File: tools.py    MIT License 6 votes vote down vote up
def seeds2superpixels(seed_mask, superpixels, debug=False, im=None):
    seeds = np.argwhere(seed_mask)
    superseeds = np.zeros_like(seed_mask)

    for s in seeds:
        label = superpixels[s[0], s[1]]
        superseeds = np.where(superpixels==label, 1, superseeds)

    if debug:
        plt.figure(), plt.gray()
        plt.subplot(121), plt.imshow(im), plt.hold(True), plt.plot(seeds[:,1], seeds[:,0], 'ro'), plt.axis('image')
        plt.subplot(122), plt.imshow(im), plt.hold(True), plt.plot(seeds[:,1], seeds[:,0], 'ro'),
        plt.imshow(mark_boundaries(im, superseeds, color=(1,0,0))), plt.axis('image')
        plt.show()

    return superseeds


#----------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------- 
Example 17
Project: imtools   Author: mjirik   File: tools.py    MIT License 6 votes vote down vote up
def get_hist_mode(im, mask=None, debug=False):
    if mask is None:
        mask = np.ones(im.shape, dtype=np.bool)
    data = im[np.nonzero(mask)]

    hist, bins = skiexp.histogram(data)
    max_peak_idx = hist.argmax()

    mode = bins[max_peak_idx]

    if debug:
        plt.figure()
        plt.plot(bins, hist)
        plt.hold(True)

        plt.plot(bins[max_peak_idx], hist[max_peak_idx], 'ro')
        plt.title('Histogram of input data with marked mode = %i' % mode)
        plt.show()

    return mode 
Example 18
Project: gardenia   Author: xuzhenqi   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def show_predict(img, shape, label=None):
    '''
    :param img: H*W*3 array
    :param label: 68*2 point labels
    :return: None
    '''
    if img is not None:
        plt.imshow(img)
        plt.axis('image')
    plt.hold(True)
    plt.plot(shape[::2], shape[1::2], 'r.', markersize=12)
    if label is not None:
        plt.plot(label[::2], label[1::2], 'g.', markersize=12)
    plt.axis('off')
    plt.show() 
Example 19
Project: GeoPy   Author: aerler   File: signalsmooth.py    GNU General Public License v3.0 5 votes vote down vote up
def smooth_demo():
    import matplotlib.pyplot as plt

    t = np.linspace(-4,4,100)
    x = np.sin(t)
    xn = x + np.random.randn(len(t)) * 0.1
    y = smooth(x)
    ws = 31

    plt.subplot(211)
    plt.plot(np.ones(ws))

    windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']

    plt.hold(True)
    for w in windows[1:]:
        #eval('plt.plot('+w+'(ws) )')
        plt.plot(getattr(np, w)(ws))

    plt.axis([0,30,0,1.1])

    plt.legend(windows)
    plt.title("The smoothing windows")
    plt.subplot(212)
    plt.plot(x)
    plt.plot(xn)
    for w in windows:
        plt.plot(smooth(xn,10,w))
    l = ['original signal', 'signal with noise']
    l.extend(windows)
    plt.legend(l)
    plt.title("Smoothing a noisy signal")
    #plt.show() 
Example 20
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP_testfunc(self, model, hutil):
        '''Plot the GP at its current stage in the minimization
        with the test function "model".

        Parameters

        model: A tets function giving a fast merit function evaluation'''

        xt = self.xt; mean = np.squeeze( self.mean ); cov = self.cov; u = self.u;
        maxloc = self.maxloc; umax = self.umax
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        yt = []
        [yt.append(-model.getMerit((hutil.interp_coords_from_dist(xx)/float(2**hutil.p)))) for xx in xt]

        pl.figure(5)
        pl.hold(False)
        pl.plot(xt,mean)
        pl.hold(True)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),mean+np.squeeze(2*np.sqrt(var)), facecolor = "grey", alpha=0.5)
        pl.plot(xt,yt,'-')
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 21
Project: esys-pbi   Author: fsxfreak   File: matplotlib_standalone.py    MIT License 5 votes vote down vote up
def __init__(self, size=(600,350)):
    self.running = True
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Streaming Live EMG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('Volts')
    plt.show() 
Example 22
Project: esys-pbi   Author: fsxfreak   File: graph_matplotlib.py    MIT License 5 votes vote down vote up
def __init__(self, size=(600,350)):
    streams = resolve_byprop('name', 'bci', timeout=2.5)
    try:
      self.inlet = StreamInlet(streams[0])
    except IndexError:
      raise ValueError('Make sure stream name=bci is opened first.')
   
    self.running = True
    
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1
    self.sampleCount = self.count 
    self.maximum = 0
    self.minimum = 0

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Live Stream EEG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('mV')
    #plt.autoscale(True, 'y', tight = True)
    plt.show()
    #while(1):
    #secondTimes.append(serialData[0])                         #add time stamps to array 'timeValSeconds'
    #floatSecondTimes.append(float(serialData[0])/1000000)     # makes all second times into float from string
    
    #processedSig.append(serialData[6])                           #add processed signal values to 'processedSig'
    #floatProcessedSig.append(float(serialData[6])) 
Example 23
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 24
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 25
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff() 
Example 26
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot(self, plot_cmd=None, tf=lambda y: y):
        """plot the data we have, return ``self``"""
        if not plot_cmd:
            plot_cmd = self.plot_cmd
        colors = 'bgrcmyk'
        pyplot.hold(False)
        res = self.res

        flatx, flatf = self.flattened()
        minf = np.inf
        for i in flatf:
            minf = min((minf, min(flatf[i])))
        addf = 1e-9 - minf if minf <= 1e-9 else 0
        for i in sorted(res.keys()):  # we plot not all values here
            if isinstance(i, int):
                color = colors[i % len(colors)]
                arx = sorted(res[i].keys())
                plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
                pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
                pyplot.hold(True)
                plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
        pyplot.ylabel('f + ' + str(addf))
        pyplot.draw()
        pyplot.ion()
        pyplot.show()
        # raw_input('press return')
        return self 
Example 27
Project: GeometricCoverSongs   Author: ctralie   File: testSequenceAlignment.py    Apache License 2.0 5 votes vote down vote up
def testBacktrace():
    np.random.seed(100)
    t = np.linspace(0, 1, 300)
    t1 = t
    X1 = 0.3*np.random.randn(400, 2)
    X1[50:50+len(t1), 0] = np.cos(2*np.pi*t1)
    X1[50:50+len(t1), 1] = np.sin(4*np.pi*t1)
    t2 = t**2
    X2 = 0.3*np.random.randn(350, 2)
    X2[0:len(t2), 0] = np.cos(2*np.pi*t2)
    X2[0:len(t2), 1] = np.sin(4*np.pi*t2)
    CSM = getCSM(X1, X2)
    CSM = CSMToBinaryMutual(CSM, 0.1)
    (maxD, D, path) = SA.SWBacktrace(CSM)
    sio.savemat("D.mat", {"D":D})
    print("maxD = %g"%maxD)

    plt.subplot(221)
    plt.plot(X1[:, 0], X1[:, 1])
    plt.subplot(222)
    plt.plot(X2[:, 0], X2[:, 1])
    plt.subplot(223)
    plt.imshow(CSM, cmap = 'afmhot')
    plt.subplot(224)
    plt.imshow(D, cmap = 'afmhot')
    plt.hold(True)
    path = np.array(path)
    plt.title("%g"%maxD)
    plt.scatter(path[:, 1], path[:, 0], 20, edgecolor = 'none')
    plt.show() 
Example 28
Project: Resting_State_CFC   Author: palvalab   File: plot_functions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def semi_log_plot(figsize,data,freqs,xlim,ylab,legend=None,outfile=None,legend_pos=None,ylim=None,show=False,cmap='gist_rainbow',ncols=3,CI=False):   
    fig,ax=plt.subplots(figsize=figsize) 
    ax.hold(True)
    if type(cmap) is mpc.LinearSegmentedColormap:
        colorspace = [cmap(i) for i in np.linspace(0, 1, len(data))]            # get colorspace from colormap
    else:
        colorspace = [plt.get_cmap(cmap)(i) for i in np.linspace(0, 1, len(data))]   
    colorspace_CI = np.array(colorspace)*np.array([1,1,1,0.3])                              # colors for confidence intervals
    ax.set_color_cycle(colorspace)                                                          # set different colors for different plots
    for i in range(len(data)):                                                              # for each plot i
        if CI==True: 
            ax.plot(freqs[:len(data[i][0])],data[i][0])                                     # if CI, data for each plot i comes as [mean,CI_low, CI_high]
            ax.fill_between(freqs,data[i][1],data[i][2],color=colorspace_CI[i])             # fill between CI_low and CI_high
        else:
            ax.plot(freqs[:len(data[i])],data[i])          
        
    ax.set_xscale('log')
    ax.set_xticks([1,2,3,5,10,20,30,50,100,200,300])
    ax.get_xaxis().set_major_formatter(mp.ticker.ScalarFormatter())
    ax.set_xlim(xlim) 
    ax.set_ylabel(ylab,fontsize=14)
    ax.set_xlabel('Frequency [Hz]',fontsize=14)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    if ylim!=None:
        ax.set_ylim(ylim) 
    if legend_pos=='uc':
        plt.legend(legend,loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=ncols)
    if legend_pos=='ur':
        plt.legend(legend, loc='upper right', ncol=ncols)    
    if outfile!=None:    
        plt.savefig(outfile) 
    if show:
        plt.show()
    plt.clf() 
Example 29
Project: Resting_State_CFC   Author: palvalab   File: plot_functions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log_log_plot(figsize,data,freqs,xlim,ylab,legend=None,outfile=None,legend_pos=None,ylim=None,show=False,cmap='gist_rainbow',ncols=3):   
    plt.figure(figsize=figsize, dpi=600, facecolor='w', edgecolor='k')
    p,ax=plt.subplots() 
    plt.hold(True)
    ax.set_color_cycle([plt.get_cmap(cmap)(i) for i in np.linspace(0, 0.9, len(data))])
    for i in range(len(data)):
        ax.plot(freqs[:len(data[i])],data[i])
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xticks([1,2,3,5,10,20,30,50,100,200,300])
    ax.get_xaxis().set_major_formatter(mp.ticker.ScalarFormatter())
    ax.set_xlim(xlim) 
    ax.set_ylabel(ylab,fontsize=14)
    ax.set_xlabel('Frequency [Hz]',fontsize=14)
    if ylim!=None:
        ax.set_ylim(ylim) 
    if legend_pos=='uc':
        plt.legend(legend,loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=ncols)
    if legend_pos=='ur':
        plt.legend(legend, loc='upper right', ncol=ncols)    
    if outfile!=None:    
        plt.savefig(outfile)
    if show:
        plt.show()
    plt.clf()
        
    return p 
Example 30
Project: Deep-Learning-Spectroscopy   Author: kunalghosh   File: vis.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_fig(idx, title, filename):
    # plt.rcParams.update({'font.size': fontsize})
    sns.set(style="white", color_codes=True,font_scale=1.5, rc={"lines.linewidth" : 5})
    sns.set_palette("Dark2")
    fig = plt.figure()
    plt.plot(x_vals, Y_test[idx,:], label="True")
    plt.title(title)
    plt.hold(True)
    plt.plot(x_vals, Y_pred[idx,:], label="Pred")
    plt.legend()
    plt.xlabel("Energies [eV]")
    plt.ylabel("Intensity")
    fig.savefig(filename)
    plt.close() 
Example 31
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 32
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff() 
Example 33
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot(self, plot_cmd=None, tf=lambda y: y):
        """plot the data we have, return ``self``"""
        if not plot_cmd:
            plot_cmd = self.plot_cmd
        colors = 'bgrcmyk'
        pyplot.hold(False)
        res = self.res

        flatx, flatf = self.flattened()
        minf = np.inf
        for i in flatf:
            minf = min((minf, min(flatf[i])))
        addf = 1e-9 - minf if minf <= 1e-9 else 0
        for i in sorted(res.keys()):  # we plot not all values here
            if isinstance(i, int):
                color = colors[i % len(colors)]
                arx = sorted(res[i].keys())
                plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
                pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
                pyplot.hold(True)
                plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
        pyplot.ylabel('f + ' + str(addf))
        pyplot.draw()
        pyplot.ion()
        pyplot.show()
        # raw_input('press return')
        return self 
Example 34
Project: GWNRTools   Author: prayush   File: PlotOverlaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_effectualness_vs_totalmass(self, inkey=None,\
                          logy=True, figtype='pdf'):
    #{{{
    try: import matplotlib.pyplot as plt
    except: return
    if self.data == None: self.read_data_from_all_files()
    all_sims = self.data.data.keys()
    for sim in all_sims:
      plt.figure(int(1e7 * np.random.random()))
      for idx, app in enumerate(self.ApproxList):
        mm, ff = self.data.effectualness_vs_totalmass(inkey=sim, approx=app)
        #print "Masses = ", mm
        #print "FF = ", ff
        if not logy:
          plt.plot(mm, ff, label=app, \
                  linestyle=self.lines[-1],\
                  lw=3,\
                  marker=self.markers[idx],\
                  markersize=3,\
                  color=self.colors[idx])
        else:
          plt.semilogy(mm, 1.-ff, label=app, \
                  linestyle=self.lines[-1],\
                  lw=3,\
                  marker=self.markers[idx],\
                  markersize=3,\
                  color=self.colors[idx])
        plt.hold(True)
      plt.ylim(1.e-4,1)
      plt.legend(loc='best')
      plt.grid()
      plt.xlabel('Total Mass')# ($M_\odot$)')
      plt.ylabel('Effectualness')
      plt.title(sim.replace('_','-'))
      plt.savefig(self.plotdir+'/FF_%s.%s' % (sim[:-4],figtype))
    return
    #}}} 
Example 35
Project: audio_scripts   Author: audiofilter   File: test_notch.py    MIT License 5 votes vote down vote up
def plot_and_wait(audio_in,d,col):
    print "starting plot"
    plt.xlim([0,4000]);
    plt.ylim([-1,1]);
    plt.plot(audio_in, 'r')
    plt.grid(True)
    plt.hold(True)
    plt.plot(d,col)
    plt.hold(False)
    plt.draw() 
Example 36
Project: audio_scripts   Author: audiofilter   File: test_notch.py    MIT License 5 votes vote down vote up
def plot_fft(d):
    eps = 1e-6
    d = abs(fft(d))+eps
    plt.plot(d,'r')
    plt.grid(True)
    plt.hold(False)
    plt.xlim([0,400]);
    plt.draw() 
Example 37
Project: ecg-identification   Author: shafeeqbsse   File: ecg_segmentator.py    Apache License 2.0 5 votes vote down vote up
def plot_list_rows(figure_name, data):
    plt.figure(figure_name)
    for j in xrange(data.shape[0]):
        plt.plot(data[j, :])
        plt.hold(True) 
Example 38
Project: SlidingWindowVideoTDA   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 5 votes vote down vote up
def plotDGMAx(ax, dgm, color = 'b', sz = 20, label = 'dgm'):
    if dgm.size == 0:
        return
    axMin = np.min(dgm)
    axMax = np.max(dgm)
    axRange = axMax-axMin;
    ax.scatter(dgm[:, 0], dgm[:, 1], sz, color,label=label)
    ax.hold(True)
    ax.plot([axMin-axRange/5,axMax+axRange/5], [axMin-axRange/5, axMax+axRange/5],'k');
    ax.set_xlabel('Time of Birth')
    ax.set_ylabel('Time of Death') 
Example 39
Project: SlidingWindowVideoTDA   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 5 votes vote down vote up
def plot2DGMs(P1, P2, l1 = 'Diagram 1', l2 = 'Diagram 2'):
    plotDGM(P1, 'r', 10, label = l1)
    plt.hold(True)
    plt.plot(P2[:, 0], P2[:, 1], 'bx', label = l2)
    plt.legend()
    plt.xlabel("Birth Time")
    plt.ylabel("Death Time") 
Example 40
Project: SlidingWindowVideoTDA   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 5 votes vote down vote up
def plotTriangles(X, A, B, C):
    plt.hold(True)
    ax = plt.gca()
    for i in range(len(A)):
        poly = [X[A[i], :], X[B[i], :], X[C[i], :]]
        ax.add_patch(Polygon(np.array(poly), linestyle='solid', color='#00FF00', alpha=0.05)) 
Example 41
Project: SlidingWindowVideoTDA   Author: ctralie   File: TDAPlotting.py    Apache License 2.0 5 votes vote down vote up
def drawLineColored(X, C):
    plt.hold(True)
    for i in range(X.shape[0]-1):
        plt.plot(X[i:i+2, 0], X[i:i+2, 1], c=C[i, :], lineWidth = 3) 
Example 42
Project: optimizer   Author: ocelot-collab   File: genesis_tools.py    GNU General Public License v3.0 5 votes vote down vote up
def subtract_off_K_slope(self,flat_up_to_und=13,plotQ=True):
        
        # backup Ks
        origKs = copy.deepcopy(self.und_Ks)
        
        # fit a line to the first flat_up_to_und undulators
        fitKs = origKs[origKs != 0] #remove the zeros before linear fit
        
        xs = np.array(range(flat_up_to_und))
        ys = np.array([fitKs[i] for i in xs])
        
        xm = xs.mean() # average position
        ym = ys.mean() # average K
        
        m = np.sum((xs-xm) * (ys-ym)) / np.sum((xs-xm) * (xs-xm)) # slope
        b = ym - m * xm # intercept
        
        # subtract off linear slope
        for i in range(len(self.und_Ks)):
            if (self.und_Ks[i] != 0): 
                self.und_Ks[i] -= m * i # subtract off slope only for the nonzero undulators (thus keeping the zero undulators at zero)
        #print 'Flattened Ks = ', self.und_Ks
        print 'Linear component of undulator taper has been flattened.'
        if plotQ:
            from matplotlib import pyplot as plt
            plt.plot(origKs, label='orig')
            plt.hold('on')
            plt.plot(self.und_Ks, label='flattened')
            plt.legend()
            plt.xlabel('z / 3.9 m')
            plt.ylabel('K_peak')
            plt.savefig('taper.png')
            plt.hold('off')
            plt.close()
        
    # stub - fcn to calculate the twiss given a lattice 
Example 43
Project: SamplingBasedPlanning   Author: ryanfarr01   File: collisions.py    MIT License 5 votes vote down vote up
def draw(self, q, color='b', show=False, base_color='b'):
        '''
        Draw the robot with the provided configuration
        '''
        plotter.hold(True)
        pts = self.fk(q)
        for i, p in enumerate(pts):
            if i == 0:
                plotter.plot(p[0], p[1], base_color+'o')
            else:
                plotter.plot([prev_p[0], p[0]],
                             [prev_p[1], p[1]], color)
            prev_p = p[:]
        if show:
            plotter.show() 
Example 44
Project: SamplingBasedPlanning   Author: ryanfarr01   File: collisions.py    MIT License 5 votes vote down vote up
def draw_env(self, q=None, show=True, show_points=True):
        '''
        Draw the environment obstacle map
        '''
        plotter.hold(True)
        plotter.axis([self.x_min, self.x_max, self.y_min, self.y_max])

        # Draw all obstacles
        for p in self.polygons:
            prev_pt = p[-1]
            for pt in p:
                plotter.plot([prev_pt[0], pt[0]],
                             [prev_pt[1], pt[1]], 'r')
                prev_pt = pt[:]

        # Draw robot
        if q is not None:
            self.robot.draw(q)

        # Draw goal
        goal_fk = self.robot.fk(self.goal)
        goal_x = goal_fk[-1]
        if show_points:
            plotter.plot(goal_x[0], goal_x[1], 'go')

        if show:
            plotter.show() 
Example 45
Project: pymake   Author: dtrckd   File: algo.py    GNU General Public License v3.0 5 votes vote down vote up
def kmeans_plus(X=None, K=4):
    if X is None:
        centers = [[1, 1], [-1, -1], [1, -1]]
        K = len(centers)
        X, labels_true = make_blobs(n_samples=3000, centers=centers, cluster_std=0.7)

    ###################################
    # Compute clustering with Means

    k_means = KMeans(init='k-means++', n_clusters=K, n_init=10)
    k_means.fit(X)
    k_means_labels = k_means.labels_
    k_means_cluster_centers = k_means.cluster_centers_
    k_means_labels_unique = np.unique(k_means_labels)

    ###################################
    # Plot result

    colors = ['#4EACC5', '#FF9C34', '#4E9A06', '#4E9A97']
    plt.figure()
    plt.hold(True)
    for k, col in zip(range(K), colors):
    #for k in range(K):
        my_members = k_means_labels == k
        cluster_center = k_means_cluster_centers[k]
        plt.plot(X[my_members, 0], X[my_members, 1], 'w',
                 markerfacecolor=col, marker='.')
        plt.plot(cluster_center[0], cluster_center[1], 'o',
                 markeredgecolor='k', markersize=6, markerfacecolor=col)
    plt.title('KMeans')
    plt.grid(True)
    plt.show() 
Example 46
Project: csnmf   Author: marianotepper   File: test_climate.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot(x, dict_res, plot_func):
    colors = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3']

    plt.hold(True)
    k = 0
    for (alg, dtype) in dict_res.keys():
        for comp in dict_res[(alg, dtype)]:
            if len(alg) < 4:
                label = '{0:4s}'.format(alg.upper()) + ' - '
            else:
                label = '{0:4s}'.format(alg.upper()) + ' - '
            if comp:
                label += '{0:5s} - '.format('comp.')
                linestyle = '-'
            else:
                label += '{0:5s} - '.format('QR')
                linestyle = '--'
            label += dtype

            y = dict_res[(alg, dtype)][comp]
            valid = np.isfinite(y).flatten()
            if not np.any(valid):
                continue
            plot_func(x[valid], y[valid], label=label,
                      linestyle=linestyle, linewidth=2,
                      marker='o', markeredgecolor='none', color=colors[k])
        k += 1

    plt.hold(False) 
Example 47
Project: text_renderer   Author: Sanster   File: utils.py    MIT License 5 votes vote down vote up
def viz_img(text_im, fignum=1):
    """
    text_im : image containing text
    """
    text_im = text_im.astype(int)
    plt.close(fignum)
    plt.figure(fignum)
    plt.imshow(text_im, cmap='gray')
    plt.show(block=True)
    # plt.hold(True)
    #
    # H, W = text_im.shape[:2]
    # plt.gca().set_xlim([0, W - 1])
    # plt.gca().set_ylim([H - 1, 0])
    # plt.show(block=True) 
Example 48
Project: SamPy   Author: sniemi   File: cookb_signalsmooth.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def smooth_demo():
    t = np.linspace(-4,4,100)
    x = np.sin(t)
    xn = x + np.random.randn(len(t)) * 0.1
    y = smooth(x)
    ws = 31

    plt.subplot(211)
    plt.plot(np.ones(ws))

    windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']

    plt.hold(True)
    for w in windows[1:]:
        #eval('plt.plot('+w+'(ws) )')
        plt.plot(getattr(np, w)(ws))

    plt.axis([0,30,0,1.1])

    plt.legend(windows)
    plt.title("The smoothing windows")
    plt.subplot(212)
    plt.plot(x)
    plt.plot(xn)
    for w in windows:
        plt.plot(smooth(xn,10,w))
    l = ['original signal', 'signal with noise']
    l.extend(windows)
    plt.legend(l)
    plt.title("Smoothing a noisy signal")
    #plt.show() 
Example 49
Project: Emergence   Author: LennonLab   File: macroecotools.py    MIT License 5 votes vote down vote up
def richness_in_group(composition_data, group_cols, spid_cols):
    """Determine the number of species in a grouping (e.g., at each site)

    Counts the number of species grouped at one or more levels. For example,
    the number of species occuring at each of a series of sites or in each of
    a series of years.

    If a combination of grouping variables is not present in the data, then no
    values will be returned for that combination. In other words, if these
    missing combinations should be treated as zeros, this will need to be
    handled elsewhere.

    Args:
        composition_data: A Pandas data frame with one or more columns with
            information on species identity and one or more columns with
            information on the groups, e.g., years or sites.
        group_cols: A list of strings of the names othe columns in
            composition_data that hold the grouping fields.
        spid_cols: A list of strings of the names of the columns in
            composition_data that hold the data on species ID. This could be a
            single column with a unique ID or two columns containing the latin binomial.

    Returns:
        A data frame with the grouping fields and the species richness

    """
    spid_series = [composition_data[spid_col] for spid_col in spid_cols]
    single_spid = combined_spID(*spid_series)
    composition_data['_spid'] = single_spid
    richness = composition_data.groupby(group_cols)._spid.nunique()
    richness = richness.reset_index()
    richness.columns = group_cols + ['richness']
    del composition_data['_spid']
    return richness 
Example 50
Project: Emergence   Author: LennonLab   File: macroecotools.py    MIT License 5 votes vote down vote up
def abundance_in_group(composition_data, group_cols, abund_col=None):
    """Determine the number of individuals in a grouping (e.g., at each site)

    Counts the number of individuals grouped at one or more levels. For example,
    the number of species occuring at each of a series of sites or in each of
    a series of genus-species combinations.

    If a combination of grouping variables is not present in the data, then no
    values will be returned for that combination. In other words, if these
    missing combinations should be treated as zeros, this will need to be
    handled elsewhere.

    Args:
        composition_data: A Pandas data frame with one or more columns with
            information on species identity and one or more columns with
            information on the groups, e.g., years or sites, and a column
            containing the abundance value.
        group_cols: A list of strings of the names othe columns in
            composition_data that hold the grouping fields.
        abund_col: A column containing abundance data. If this column is not
            provided then it is assumed that the abundances are to be obtained
            by counting the number of rows in the group (e.g., there is one
            sample per individual in many ecological datasets)

    Returns:
        A data frame with the grouping fields and the species richness

    """
    if abund_col:
        abundance = composition_data[group_cols + abund_col].groupby(group_cols).sum()
    else:
        abundance = composition_data[group_cols].groupby(group_cols).size()
    abundance = pandas.DataFrame(abundance)
    abundance.columns = ['abundance']
    abundance = abundance.reset_index()
    return abundance