Python pylab.show() Examples

The following are 30 code examples of pylab.show(). 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: test_turbo_seti.py    From turbo_seti with MIT License 7 votes vote down vote up
def plot_hits(filename_fil, filename_dat):
    """ Plot the hits in a .dat file. """
    table = find_event.read_dat(filename_dat)
    print(table)

    plt.figure(figsize=(10, 8))
    N_hit = len(table)
    if N_hit > 10:
        print("Warning: More than 10 hits found. Only plotting first 10")
        N_hit = 10

    for ii in range(N_hit):
        plt.subplot(N_hit, 1, ii+1)
        plot_event.plot_hit(filename_fil, filename_dat, ii)
    plt.tight_layout()
    plt.savefig(filename_dat.replace('.dat', '.png'))
    plt.show() 
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: proj3d.py    From opticspy with MIT License 7 votes vote down vote up
def test_proj():
    import pylab
    M = test_proj_make_M()

    ts = ['%d' % i for i in [0,1,2,3,0,4,5,6,7,4]]
    xs, ys, zs = [0,1,1,0,0, 0,1,1,0,0], [0,0,1,1,0, 0,0,1,1,0], \
            [0,0,0,0,0, 1,1,1,1,1]
    xs, ys, zs = [np.array(v)*300 for v in (xs, ys, zs)]
    #
    test_proj_draw_axes(M, s=400)
    txs, tys, tzs = proj_transform(xs, ys, zs, M)
    ixs, iys, izs = inv_transform(txs, tys, tzs, M)

    pylab.scatter(txs, tys, c=tzs)
    pylab.plot(txs, tys, c='r')
    for x, y, t in zip(txs, tys, ts):
        pylab.text(x, y, t)

    pylab.xlim(-0.2, 0.2)
    pylab.ylim(-0.2, 0.2)

    pylab.show() 
Example #4
Source File: homework1.py    From principles-of-computing with MIT License 7 votes vote down vote up
def time_upgrades_relationship():
    '''
    helper function to show relationship between time and number of upgrades,
    for upgrade_cost_increment == 1.0
    '''
    print 'Time unit / Incremental resources'
    data = resources_vs_time(1.0, 10)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]
    for index in xrange(len(time) - 1):
        delta = resource[index + 1] - resource[index]
        print time[index], '\t', delta
    print 'sum is known as a triangular sum, 1/2(n + 1)n; for t it\'s 1/2(t + 1)t'    

#time_upgrades_relationship()

    
# Question 10 
Example #5
Source File: proj3d.py    From Computable with MIT License 6 votes vote down vote up
def test_proj():
    import pylab
    M = test_proj_make_M()

    ts = ['%d' % i for i in [0,1,2,3,0,4,5,6,7,4]]
    xs, ys, zs = [0,1,1,0,0, 0,1,1,0,0], [0,0,1,1,0, 0,0,1,1,0], \
            [0,0,0,0,0, 1,1,1,1,1]
    xs, ys, zs = [np.array(v)*300 for v in (xs, ys, zs)]
    #
    test_proj_draw_axes(M, s=400)
    txs, tys, tzs = proj_transform(xs, ys, zs, M)
    ixs, iys, izs = inv_transform(txs, tys, tzs, M)

    pylab.scatter(txs, tys, c=tzs)
    pylab.plot(txs, tys, c='r')
    for x, y, t in zip(txs, tys, ts):
        pylab.text(x, y, t)

    pylab.xlim(-0.2, 0.2)
    pylab.ylim(-0.2, 0.2)

    pylab.show() 
Example #6
Source File: utils_2dfmc.py    From msaf with MIT License 6 votes vote down vote up
def compute_ffmc2d(X):
    """Computes the 2D-Fourier Magnitude Coefficients."""
    # 2d-fft
    fft2 = scipy.fftpack.fft2(X)

    # Magnitude
    fft2m = magnitude(fft2)

    # FFTshift and flatten
    fftshift = scipy.fftpack.fftshift(fft2m).flatten()

    #cmap = plt.cm.get_cmap('hot')
    #plt.imshow(np.log1p(scipy.fftpack.fftshift(fft2m)).T, interpolation="nearest",
    #    aspect="auto", cmap=cmap)
    #plt.show()

    # Take out redundant components
    return fftshift[:fftshift.shape[0] // 2 + 1] 
Example #7
Source File: plot.py    From TOPFARM with GNU Affero General Public License v3.0 6 votes vote down vote up
def execute(self):
        plt.ion()
        if self.inc==0:
            try:
                pa(self.result_file+'.results').remove()
            except:
                pass
            self.iterations = [self.inc]
            self.targvalue = [[getattr(self, i) for i in self.targname]]
            self.pre_plot()
        else:
            self.iterations.append(self.inc)
            self.targvalue.append([getattr(self, i) for i in self.targname])
            #print self.iterations,self.targvalue
        #if self.inc % (2*self.wt_positions.shape[0]) == 0:
        #self.refresh()
        #plt.show()
        self.save_plot('fig/'+self.png_name+'layout%d.png'%(self.inc))
        self.inc += 1 
Example #8
Source File: transfer_learning.py    From plastering with MIT License 6 votes vote down vote up
def plot_confusion_matrix(test_label, pred):

    mapping = {1:'co2',2:'humidity',3:'pressure',4:'rmt',5:'status',6:'stpt',7:'flow',8:'HW sup',9:'HW ret',10:'CW sup',11:'CW ret',12:'SAT',13:'RAT',17:'MAT',18:'C enter',19:'C leave',21:'occu',30:'pos',31:'power',32:'ctrl',33:'fan spd',34:'timer'}
    cm_ = CM(test_label, pred)
    cm = normalize(cm_.astype(np.float), axis=1, norm='l1')
    fig = pl.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm, cmap=Color.YlOrBr)
    fig.colorbar(cax)
    for x in range(len(cm)):
        for y in range(len(cm)):
            ax.annotate(str("%.3f(%d)"%(cm[x][y], cm_[x][y])), xy=(y,x),
                        horizontalalignment='center',
                        verticalalignment='center',
                        fontsize=9)
    cm_cls =np.unique(np.hstack((test_label, pred)))
    cls = []
    for c in cm_cls:
        cls.append(mapping[c])
    pl.yticks(range(len(cls)), cls)
    pl.ylabel('True label')
    pl.xticks(range(len(cls)), cls)
    pl.xlabel('Predicted label')
    pl.title('Confusion Matrix (%.3f)'%(ACC(pred, test_label)))
    pl.show() 
Example #9
Source File: phaseResettingCurve.py    From Motiftoolbox with GNU General Public License v2.0 6 votes vote down vote up
def show(self):
		from pylab import figure, subplot, plot, show, tight_layout

		phase = np.arange(0., 2.*np.pi+0.01, 0.01)

		fig = figure()
		X = self.evaluate_orbit(phase)
		PRC = self.evaluate_prc(phase)
		ax = fig.add_subplot(self.dimensions, 1, 1)

		for i in xrange(self.dimensions):
			if i > 0: ax = fig.add_subplot(self.dimensions, 1, i+1, sharex=ax)
			ax.plot(phase, X[i], 'k-', lw=2.)
			ax2 = ax.twinx()
			ax2.plot(phase, PRC[i], 'r-', lw=2.)
			ax2.axhline(y=0., ls='--')

			ax.set_xlim(0., 2.*np.pi)

		tight_layout()
		show() 
Example #10
Source File: rnnrbm.py    From bachbot with MIT License 6 votes vote down vote up
def generate(self, filename, show=True):
        '''Generate a sample sequence, plot the resulting piano-roll and save
        it as a MIDI file.
        filename : string
            A MIDI file will be created at this location.
        show : boolean
            If True, a piano-roll of the generated sequence will be shown.'''

        piano_roll = self.generate_function()
        midiwrite(filename, piano_roll, self.r, self.dt)
        if show:
            extent = (0, self.dt * len(piano_roll)) + self.r
            pylab.figure()
            pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
                         interpolation='nearest', cmap=pylab.cm.gray_r,
                         extent=extent)
            pylab.xlabel('time (s)')
            pylab.ylabel('MIDI note number')
            pylab.title('generated piano-roll') 
Example #11
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 #12
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 #13
Source File: segmenter.py    From msaf with MIT License 6 votes vote down vote up
def pick_peaks(nc, L=16):
    """Obtain peaks from a novelty curve using an adaptive threshold."""
    offset = nc.mean() / 20.

    nc = filters.gaussian_filter1d(nc, sigma=4)  # Smooth out nc

    th = filters.median_filter(nc, size=L) + offset
    #th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offset

    peaks = []
    for i in range(1, nc.shape[0] - 1):
        # is it a peak?
        if nc[i - 1] < nc[i] and nc[i] > nc[i + 1]:
            # is it above the threshold?
            if nc[i] > th[i]:
                peaks.append(i)
    #plt.plot(nc)
    #plt.plot(th)
    #for peak in peaks:
        #plt.axvline(peak)
    #plt.show()

    return peaks 
Example #14
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 #15
Source File: proj3d.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def test_proj():
    import pylab
    M = test_proj_make_M()

    ts = ['%d' % i for i in [0,1,2,3,0,4,5,6,7,4]]
    xs, ys, zs = [0,1,1,0,0, 0,1,1,0,0], [0,0,1,1,0, 0,0,1,1,0], \
            [0,0,0,0,0, 1,1,1,1,1]
    xs, ys, zs = [np.array(v)*300 for v in (xs, ys, zs)]
    #
    test_proj_draw_axes(M, s=400)
    txs, tys, tzs = proj_transform(xs, ys, zs, M)
    ixs, iys, izs = inv_transform(txs, tys, tzs, M)

    pylab.scatter(txs, tys, c=tzs)
    pylab.plot(txs, tys, c='r')
    for x, y, t in zip(txs, tys, ts):
        pylab.text(x, y, t)

    pylab.xlim(-0.2, 0.2)
    pylab.ylim(-0.2, 0.2)

    pylab.show() 
Example #16
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_it():
    '''
    helper function to gain insight on provided data sets background,
    using pylab
    '''
    data1 = [[1.0, 1], [2.25, 3.5], [3.58333333333, 7.5], [4.95833333333, 13.0], [6.35833333333, 20.0], [7.775, 28.5], [9.20357142857, 38.5], [10.6410714286, 50.0], [12.085515873, 63.0], [13.535515873, 77.5]]
    data2 = [[1.0, 1], [1.75, 2.5], [2.41666666667, 4.5], [3.04166666667, 7.0], [3.64166666667, 10.0], [4.225, 13.5], [4.79642857143, 17.5], [5.35892857143, 22.0], [5.91448412698, 27.0], [6.46448412698, 32.5], [7.00993867244, 38.5], [7.55160533911, 45.0], [8.09006687757, 52.0], [8.62578116328, 59.5], [9.15911449661, 67.5], [9.69036449661, 76.0], [10.2197762613, 85.0], [10.7475540391, 94.5], [11.2738698286, 104.5], [11.7988698286, 115.0]]
    time1 = [item[0] for item in data1]
    resource1 = [item[1] for item in data1]
    time2 = [item[0] for item in data2]
    resource2 = [item[1] for item in data2]
    
    # plot in pylab (total resources over time)
    pylab.plot(time1, resource1, 'o')
    pylab.plot(time2, resource2, 'o')
    pylab.title('Silly Homework')
    pylab.legend(('Data Set no.1', 'Data Set no.2'))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_it() 
Example #17
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_question2():
    '''
    graph of total resources generated as a function of time,
    for four various upgrade_cost_increment values
    '''
    for upgrade_cost_increment in [0.0, 0.5, 1.0, 2.0]:
        data = resources_vs_time(upgrade_cost_increment, 5)
        time = [item[0] for item in data]
        resource = [item[1] for item in data]
    
        # plot in pylab (total resources over time for each constant)
        pylab.plot(time, resource, 'o')
        
    pylab.title('Silly Homework')
    pylab.legend(('0.0', '0.5', '1.0', '2.0'))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_question2()   


# Question 3 
Example #18
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_question3():
    '''
    graph of total resources generated as a function of time;
    for upgrade_cost_increment == 0
    '''
    data = resources_vs_time(0.0, 100)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]

    # plot in pylab on logarithmic scale (total resources over time for upgrade growth 0.0)
    pylab.loglog(time, resource)
        
    pylab.title('Silly Homework')
    pylab.legend('0.0')
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_question3()


# Question 4 
Example #19
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def time_upgrades_relationship_0():
    '''
    helper function to show relationship between time and number of upgrades,
    for upgrade_cost_increment == 0.0
    '''
    print 'Incremental time to achieve upgrade'
    data = resources_vs_time(0.0, 11)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]
    for index in xrange(len(time) - 1):
        delta1 = time[index + 1] - time[index]
        delta2 = resource[index + 1] - resource[index]
        print delta1, '\t\t', delta2
    print '\nsum is called a harmonic sum and has only an approximate solution: log(t) + constant;'
    print 'question 6 asks for "...we seek the inverse function g for f..." thus e**(t) in form E^t'

#time_upgrades_relationship_0()


# Question 7 
Example #20
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def polyfitting():
    '''
    helper function to play around with polyfit from:
    http://www.wired.com/2011/01/linear-regression-with-pylab/
    '''
    x = [0.2, 1.3, 2.1, 2.9, 3.3]
    y = [3.3, 3.9, 4.8, 5.5, 6.9]
    slope, intercept = pylab.polyfit(x, y, 1)
    print 'slope:', slope, 'intercept:', intercept

    yp = pylab.polyval([slope, intercept], x)
    pylab.plot(x, yp)
    pylab.scatter(x, y)
    pylab.show()

#polyfitting() 
Example #21
Source File: vim-profiler.py    From vim-profiler with GNU General Public License v3.0 6 votes vote down vote up
def plot(self):
        """
        Plot startup data.
        """
        import pylab

        print("Plotting result...", end="")
        avg_data = self.average_data()
        avg_data = self.__sort_data(avg_data, False)
        if len(self.raw_data) > 1:
            err = self.stdev_data()
            sorted_err = [err[k] for k in list(zip(*avg_data))[0]]
        else:
            sorted_err = None
        pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1],
                   xerr=sorted_err, align='center', alpha=0.4)
        pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0])
        pylab.xlabel("Average startup time (ms)")
        pylab.ylabel("Plugins")
        pylab.show()
        print(" done.") 
Example #22
Source File: test_turbo_seti.py    From turbo_seti with MIT License 6 votes vote down vote up
def test_plotting():
    """ Some basic plotting tests

    TODO: Improve these tests (and the functions for that matter!
    """
    filename_fil = os.path.join(HERE, 'Voyager1.single_coarse.fine_res.h5')
    fil = bl.Waterfall(filename_fil)

    # Test make_waterfall_plots -- needs 6x files
    filenames_list = [filename_fil] * 6
    target  = 'Voyager'
    drates  = [-0.392226]
    fvals   = [8419.274785]
    f_start = 8419.274374 - 600e-6
    f_stop  = 8419.274374 + 600e-6
    node_string = 'test'
    filter_level = 1
    plot_event.make_waterfall_plots(filenames_list, target, drates, fvals, f_start, f_stop, node_string, filter_level)
    plt.show() 
Example #23
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show(self):
        if not self.drawn: self.draw()
        import pylab
        pylab.show() 
Example #24
Source File: _data.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def trim(self, n='all', x=True, y=True):
        """
        This will set xmin and xmax based on the current zoom-level of the
        figures.

        n='all'     Which figure to use for setting xmin and xmax.
                    'all' means all figures. You may also specify a list.
        x=True      Trim the x-range
        y=True      Trim the y-range
        """
        if len(self._set_xdata)==0 or len(self._set_ydata)==0:
            self._error("No data. Please use set_data() and plot() prior to trimming.")
            return
        
        if _s.fun.is_a_number(n): n = [n]
        elif isinstance(n,str):   n = list(range(len(self._set_xdata)))

        # loop over the specified plots
        for i in n:
            try:
                if x:
                    xmin, xmax = _p.figure(self['first_figure']+i).axes[1].get_xlim()
                    self['xmin'][i] = xmin
                    self['xmax'][i] = xmax

                if y:
                    ymin, ymax = _p.figure(self['first_figure']+i).axes[1].get_ylim()
                    self['ymin'][i] = ymin
                    self['ymax'][i] = ymax

            except:
                self._error("Data "+str(i)+" is not currently plotted.")

        # now show the update.
        self.clear_results()
        if self['autoplot']: self.plot()

        return self 
Example #25
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def showPlots():
    import pylab
    pylab.show()   
    
# example plots 
Example #26
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show(self):
        if not self.drawn: self.draw()
        import pylab
        pylab.show() 
Example #27
Source File: active_learning.py    From plastering with MIT License 5 votes vote down vote up
def plot_confusion_matrix(self, label_test, fn_test):

        fn_preds = self.clf.predict(fn_test)
        acc = accuracy_score(label_test, fn_preds)

        cm_ = CM(label_test, fn_preds)
        cm = normalize(cm_.astype(np.float), axis=1, norm='l1')

        fig = pl.figure()
        ax = fig.add_subplot(111)
        cax = ax.matshow(cm)
        fig.colorbar(cax)
        for x in range(len(cm)):
            for y in range(len(cm)):
                ax.annotate(str("%.3f(%d)"%(cm[x][y], cm_[x][y])), xy=(y,x),
                            horizontalalignment='center',
                            verticalalignment='center',
                            fontsize=10)
        cm_cls =np.unique(np.hstack((label_test,fn_preds)))

        cls = []
        for c in cm_cls:
            cls.append(mapping[c])
        pl.yticks(range(len(cls)), cls)
        pl.ylabel('True label')
        pl.xticks(range(len(cls)), cls)
        pl.xlabel('Predicted label')
        pl.title('Mn Confusion matrix (%.3f)'%acc)

        pl.show() 
Example #28
Source File: prcNetwork.py    From Motiftoolbox with GNU General Public License v2.0 5 votes vote down vote up
def show(self):
		from pylab import figure, subplot, plot, show, tight_layout

		phase = np.arange(0., 2.*np.pi+0.01, 0.01)

		fig = figure()
		ax = fig.add_subplot(1, 1, 1)
		tight_layout()
		show() 
Example #29
Source File: plot_loss.py    From ophelia with Apache License 2.0 5 votes vote down vote up
def main_work():

    #################################################
      
    # ======== Get stuff from command line ==========

    a = ArgumentParser()
    a.add_argument('-o', dest='outfile', required=True)
    a.add_argument('-l', dest='logfile', required=True)
    opts = a.parse_args()
    
    # ===============================================
    
    log = readlist(opts.logfile)
    log = [line.split('|') for line in log]
    log = [line[3].strip() for line in log if len(line) >=4]
    
    #validation = [line.replace('validation epoch ', '') for line in log if line.startswith('validation epoch')]
    #train = [line.replace('train epoch ', '') for line in log if line.startswith('validation epoch')]

    validation = [line.split(':')[1].strip().split(' ') for line in log if line.startswith('validation epoch')]
    train = [line.split(':')[1].strip().split(' ') for line in log if line.startswith('train epoch')]
    validation = np.array(validation, dtype=float)
    train = np.array(train, dtype=float)
    print train.shape
    print validation.shape

    pl.subplot(211)
    pl.plot(validation.flatten())
    pl.subplot(212)
    pl.plot(train[:,:4])
    pl.show() 
Example #30
Source File: plot.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def showPlots():
    import pylab
    pylab.show()   
    
# example plots