Python pylab.legend() Examples

The following are 30 code examples of pylab.legend(). 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: homework1.py    From principles-of-computing with MIT License 7 votes vote down vote up
def plot_question7():
    '''
    graph of total resources generated as a function of time,
    for upgrade_cost_increment == 1
    '''
    data = resources_vs_time(1.0, 50)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]
    a, b, c = pylab.polyfit(time, resource, 2)
    print 'polyfit with argument \'2\' fits the data, thus the degree of the polynomial is 2 (quadratic)'

    # plot in pylab on logarithmic scale (total resources over time for upgrade growth 0.0)
    #pylab.loglog(time, resource, 'o')

    # plot fitting function
    yp = pylab.polyval([a, b, c], time)
    pylab.plot(time, yp)
    pylab.scatter(time, resource)
    pylab.title('Silly Homework, Question 7')
    pylab.legend(('Resources for increment 1', 'Fitting function' + ', slope: ' + str(a)))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.grid()
    pylab.show() 
Example #2
Source File: estimator_utils.py    From EDeN with MIT License 6 votes vote down vote up
def plot_learning_curve(train_sizes, train_scores, test_scores):
    """plot_learning_curve."""
    plt.figure(figsize=(15, 5))
    plt.title('Learning Curve')
    plt.xlabel("Training examples")
    plt.ylabel("AUC ROC")
    tr_ys = compute_stats(train_scores)
    te_ys = compute_stats(test_scores)
    plot_stats(train_sizes, tr_ys,
               label='Training score',
               color='navy')
    plot_stats(train_sizes, te_ys,
               label='Cross-validation score',
               color='orange')
    plt.grid(linestyle=":")
    plt.legend(loc="best")
    plt.show() 
Example #3
Source File: compare_overbeek_profiles.py    From SelfTarget with MIT License 6 votes vote down vote up
def plotInFrame(overbeek_inframes, ours_inframes, oof_sel_overbeek_ids, pred_results_dir):

    PL.figure(figsize=(4.2,4.2))
    data = pd.read_csv(pred_results_dir + '/old_new_kl_predicted_summaries.txt', sep='\t').fillna(-1.0)
    label1, label2 = 'New 2x800x In Frame Perc', 'New 1600x In Frame Perc'
    xdata, ydata = data[label1], data[label2]
    PL.plot(xdata,ydata, '.', label='Synthetic between library (R=%.2f)' %  pearsonr(xdata,ydata)[0], color='C0',alpha=0.15)
    PL.plot(overbeek_inframes, ours_inframes, '^', label='Synthetic vs Endogenous (R=%.2f)' % pearsonr(overbeek_inframes, ours_inframes)[0], color='C1')
    for (x,y,id) in zip(overbeek_inframes, ours_inframes, oof_sel_overbeek_ids):
        if abs(x-y) > 25.0: PL.text(x,y,id)
    PL.plot([0,100],[0,100],'k--')
    PL.ylabel('Percent In-Frame Mutations')
    PL.xlabel('Percent In-Frame Mutations')
    PL.legend()
    PL.xticks([],[])
    PL.yticks([],[])
    PL.show(block=False)
    saveFig('in_frame_full_scatter') 
Example #4
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 #5
Source File: plot_mh_analysis.py    From SelfTarget with MIT License 6 votes vote down vote up
def compareMHlines(all_result_outputs, label='', y_axis = 'Percent Non-Null Reads', data_label='RegrLines'):

    color_map = {'K562':'b','K562_1600x':'lightblue', 'BOB':'g', 'RPE1':'purple', 'TREX2':'k', 'TREX2_2A':'gray', 'HAP1':'r', 'E14TG2A':'orange','eCAS9':'c', 'WT':'pink', 'CHO':'salmon'}
    lysty_map = {2:'--',3:'--',5:'--',7:'-',10:'-.',16:':',20:':'}

    dirnames = [x[1] for x in all_result_outputs]
    lystys = [lysty_map[parseSampleName(x)[1]] for x in dirnames]
    clrs = [color_map[parseSampleName(x)[0]] for x in dirnames]

    for mh_len in [9]:
        PL.figure()
        regr_lines = [x[0][data_label][mh_len] for x in all_result_outputs]
        for dirname, regr_line,lysty,clr in zip(dirnames,regr_lines,lystys, clrs):
            PL.plot(regr_line[0], regr_line[1], label='%s (R=%.1f)' % (getSimpleName(dirname), regr_line[2]), linewidth=2, color=clr, linestyle=lysty, alpha=0.5 )
        PL.xlabel('Distance between nearest ends of microhomologous sequences',fontsize=14)
        PL.ylabel('Corresponding microhomology-mediated deletion\n as percent of total mutated reads',fontsize=14)
        PL.tick_params(labelsize=16)
        PL.legend(loc='upper right')
        PL.ylim((0,70))
        PL.xlim((0,20))
        PL.xticks(range(0,21,5))
        PL.title('Microhomology Length %d' % mh_len,fontsize=18)
        PL.show(block=False)  
        saveFig('mh_regr_lines_all_samples__%d' % mh_len) 
Example #6
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 #7
Source File: followup.py    From pycbc with GNU General Public License v3.0 6 votes vote down vote up
def coinc_timeseries_plot(coinc_file, start, end):
    fig = pylab.figure()
    f = h5py.File(coinc_file, 'r')

    stat1 = f['foreground/stat1']
    stat2 = f['foreground/stat2']
    time1 = f['foreground/time1']
    time2 = f['foreground/time2']
    ifo1 = f.attrs['detector_1']
    ifo2 = f.attrs['detector_2']

    pylab.scatter(time1, stat1, label=ifo1, color=ifo_color[ifo1])
    pylab.scatter(time2, stat2, label=ifo2, color=ifo_color[ifo2])

    fmt = '.12g'
    mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fmt=fmt))
    pylab.legend()
    pylab.xlabel('Time (s)')
    pylab.ylabel('NewSNR')
    pylab.grid()
    return mpld3.fig_to_html(fig) 
Example #8
Source File: thermo_bulk.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_entropy(self):
        """

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        plt.plot(
            self.temperatures,
            self.eV_to_J_per_mol / self.num_atoms * self.get_entropy_p(),
            label="S$_p$",
        )
        plt.plot(
            self.temperatures,
            self.eV_to_J_per_mol / self.num_atoms * self.get_entropy_v(),
            label="S$_V$",
        )
        plt.legend()
        plt.xlabel("Temperature [K]")
        plt.ylabel("Entropy [J K$^{-1}$ mol-atoms$^{-1}$]") 
Example #9
Source File: followup.py    From pycbc with GNU General Public License v3.0 6 votes vote down vote up
def trigger_timeseries_plot(file_list, ifos, start, end):

    fig = pylab.figure()
    for ifo in ifos:
        trigs = columns_from_file_list(file_list,
                                       ['snr', 'end_time'],
                                       ifo, start, end)
        print(trigs)
        pylab.scatter(trigs['end_time'], trigs['snr'], label=ifo,
                      color=ifo_color[ifo])

        fmt = '.12g'
        mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fmt=fmt))
    pylab.legend()
    pylab.xlabel('Time (s)')
    pylab.ylabel('SNR')
    pylab.grid()
    return mpld3.fig_to_html(fig) 
Example #10
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 #11
Source File: plot_mh_analysis.py    From SelfTarget with MIT License 6 votes vote down vote up
def compareMHK562lines(all_result_outputs, label='', y_axis = 'Percent Non-Null Reads', data_label='RegrLines'):

    dirnames = [x[1] for x in all_result_outputs]
    clrs = ['silver','grey','darkgreen','green','lightgreen','royalblue','dodgerblue','skyblue','mediumpurple','orchid','red','orange','salmon']

    fig = PL.figure(figsize=(6,6))
    leg_handles = []
    mh_lens = [3,4,5,6,7,8,9,10,11,12,13,14,15]
    for mh_len, clr in zip(mh_lens,clrs):
        regr_lines = [x[0][data_label][mh_len] for x in all_result_outputs]
        mean_line = np.mean([x[:2] for x in regr_lines], axis=0)
        leg_handles.append(PL.plot(mean_line[0], mean_line[1], label='MH Len=%d  (R=%.1f)' % (mh_len,np.mean([x[2] for x in regr_lines])) , linewidth=2, color=clr )[0])
    PL.xlabel('Distance between nearest ends of\nmicrohomologous sequences',fontsize=16)
    PL.ylabel('Correspondng microhomology-mediated deletion\n as percent of total mutated reads',fontsize=16)
    PL.tick_params(labelsize=16)
    PL.legend(handles=[x for x in reversed(leg_handles)], loc='upper right')
    PL.ylim((0,80))
    PL.xlim((0,20))
    PL.xticks(range(0,21,5))
    PL.show(block=False)  
    saveFig('mh_regr_lines_K562') 
Example #12
Source File: util.py    From Azimuth with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def addqqplotinfo(qnull,M,xl='-log10(P) observed',yl='-log10(P) expected',xlim=None,ylim=None,alphalevel=0.05,legendlist=None,fixaxes=False):    
    distr='log10'
    pl.plot([0,qnull.max()], [0,qnull.max()],'k')
    pl.ylabel(xl)
    pl.xlabel(yl)
    if xlim is not None:
        pl.xlim(xlim)
    if ylim is not None:
        pl.ylim(ylim)        
    if alphalevel is not None:
        if distr == 'log10':
            betaUp, betaDown, theoreticalPvals = _qqplot_bar(M=M,alphalevel=alphalevel,distr=distr)
            lower = -sp.log10(theoreticalPvals-betaDown)
            upper = -sp.log10(theoreticalPvals+betaUp)
            pl.fill_between(-sp.log10(theoreticalPvals),lower,upper,color="grey",alpha=0.5)
            #pl.plot(-sp.log10(theoreticalPvals),lower,'g-.')
            #pl.plot(-sp.log10(theoreticalPvals),upper,'g-.')
    if legendlist is not None:
        leg = pl.legend(legendlist, loc=4, numpoints=1)
        # set the markersize for the legend
        for lo in leg.legendHandles:
            lo.set_markersize(10)

    if fixaxes:
        fix_axes() 
Example #13
Source File: analyser.py    From spotpy with MIT License 6 votes vote down vote up
def plot_Geweke(parameterdistribution,parametername):
    '''Input:  Takes a list of sampled values for a parameter and his name as a string
       Output: Plot as seen for e.g. in BUGS or PyMC'''
    import matplotlib.pyplot as plt

    # perform the Geweke test
    Geweke_values = _Geweke(parameterdistribution)

    # plot the results
    fig = plt.figure()
    plt.plot(Geweke_values,label=parametername)
    plt.legend()
    plt.title(parametername + '- Geweke_Test')
    plt.xlabel('Subinterval')
    plt.ylabel('Geweke Test')
    plt.ylim([-3,3])

    # plot the delimiting line
    plt.plot( [2]*len(Geweke_values), 'r-.')
    plt.plot( [-2]*len(Geweke_values), 'r-.') 
Example #14
Source File: View.py    From Deep-Spying with Apache License 2.0 6 votes vote down vote up
def plot_barchart(self, data, labels, colors, xlabel, ylabel, xticks, legendloc=1):
        self.big_figure()

        index = np.arange(len(data[0][0]))
        bar_width = 0.25

        pylab.grid("on", axis='y')
        pylab.ylim([0.5, 1.0])

        for i in range(0, len(data)):
            rects = pylab.bar(bar_width / 2 + index + (i * bar_width), data[i][0], bar_width,
                              alpha=0.5, color=colors[i],
                              yerr=data[i][1],
                              error_kw={'ecolor': '0.3'},
                              label=labels[i])

        pylab.legend(loc=legendloc, prop={'size': 12})

        pylab.xlabel(xlabel)
        pylab.ylabel(ylabel)
        pylab.xticks(bar_width / 2 + index + ((bar_width * (len(data[0]) + 1)) / len(data[0])), xticks) 
Example #15
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 #16
Source File: View.py    From Deep-Spying with Apache License 2.0 6 votes vote down vote up
def plot_signal_and_label(self, title, timestamp, signal, label_timestamp, label):
        if not self.to_save and not self.to_show:
            return

        pylab.figure()

        pylab.plot(timestamp, signal, color='m', label='signal')

        for i in range(0, len(label_timestamp)):
            pylab.axvline(label_timestamp[i], color="k", label="{}: key {}".format(i, label[i]), ls='dashed')

        pylab.legend()

        pylab.title(title)
        pylab.xlabel('Time')
        pylab.ylabel('Amplitude') 
Example #17
Source File: View.py    From Deep-Spying with Apache License 2.0 6 votes vote down vote up
def plot_data(self, title, data, xlabel, ylabel, colors=None, labels=None):
        if not self.to_save and not self.to_show:
            return

        self.big_figure()

        for i in range(0, len(data)):
            color = 'm' if colors is None else colors[i]

            if labels is None:
                pylab.plot(data[i], color=color)
            else:
                pylab.plot(data[i], color=color, label=labels[i])

        if labels is not None:
            pylab.legend()

        pylab.title(title)
        pylab.xlabel(xlabel)
        pylab.ylabel(ylabel) 
Example #18
Source File: plot_recallPrecision.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _plotFMeasures(fstepsize=.1,  stepsize=0.0005, start = 0.0, end = 1.0):
    """Plots 10 fmeasure Curves into the current canvas."""
    p = sc.arange(start, end, stepsize)[1:]
    for f in sc.arange(0., 1., fstepsize)[1:]:
        points = [(x, _fmeasureCurve(f, x)) for x in p
                  if 0 < _fmeasureCurve(f, x) <= 1.5]
        try:
            xs, ys = zip(*points)
            curve, = pl.plot(xs, ys, "--", color="gray", linewidth=0.8)  # , label=r"$f=%.1f$"%f) # exclude labels, for legend
            # bad hack:
            # gets the 10th last datapoint, from that goes a bit to the left, and a bit down
            datapoint_x_loc = int(len(xs)/2)
            datapoint_y_loc = int(len(ys)/2)
            # x_left = 0.05
            # y_left = 0.035
            x_left = 0.035
            y_left = -0.02
            pl.annotate(r"$f=%.1f$" % f, xy=(xs[datapoint_x_loc], ys[datapoint_y_loc]), xytext=(xs[datapoint_x_loc] - x_left, ys[datapoint_y_loc] - y_left), size="small", color="gray")
        except Exception as e:
            print e 

#colors = "gcmbbbrrryk"
#colors = "yyybbbrrrckgm"  # 7 is a prime, so we'll loop over all combinations of colors and markers, when zipping their cycles 
Example #19
Source File: plot_contrast_sensitive.py    From SceneChangeDet with MIT License 6 votes vote down vote up
def main():

    l2_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/l2_5,6,7/roc'
    cos_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/dist_cos_new_5,6,7/roc'
    CSF_dir = os.path.join(l2_base_dir)
    CSF_fig_dir = os.path.join(l2_base_dir,'fig.png')
    end_number = 22
    csf_conv5_l2_ls,csf_fc6_l2_ls,csf_fc7_l2_ls,x_l2 = get_csf_ls(l2_base_dir,end_number)
    csf_conv5_cos_ls,csf_fc6_cos_ls,csf_fc7_cos_ls,x_cos = get_csf_ls(cos_base_dir,end_number)
    Fig = pylab.figure()
    setFigLinesBW(Fig)
    #pylab.plot(x,csf_conv4_ls, color='k',label= 'conv4')
    pylab.plot(x_l2,csf_conv5_l2_ls, color='m',label= 'l2:conv5')
    pylab.plot(x_l2,csf_fc6_l2_ls, color = 'b',label= 'l2:fc6')
    pylab.plot(x_l2,csf_fc7_l2_ls, color = 'g',label= 'l2:fc7')
    pylab.plot(x_cos,csf_conv5_cos_ls, color='c',label= 'cos:conv5')
    pylab.plot(x_cos,csf_fc6_cos_ls, color = 'r',label= 'cos:fc6')
    pylab.plot(x_cos,csf_fc7_cos_ls, color = 'y',label= 'cos:fc7')
    pylab.legend(loc='lower right', prop={'size': 10})
    pylab.ylabel('RMS Contrast', fontsize=14)
    pylab.xlabel('Epoch', fontsize=14)
    pylab.savefig(CSF_fig_dir) 
Example #20
Source File: View.py    From Deep-Spying with Apache License 2.0 6 votes vote down vote up
def plot_sensor_data(self, title, timestamp, x, y, z):
        if not self.to_save and not self.to_show:
            return

        self.big_figure()
        pylab.grid("on")

        pylab.plot(timestamp, x, color='r', label='x')
        pylab.plot(timestamp, y, color='g', label='y')
        pylab.plot(timestamp, z, color='b', label='z')

        pylab.legend()

        pylab.title(title)
        pylab.xlabel('Time')
        pylab.ylabel('Amplitude') 
Example #21
Source File: test_correlate.py    From rapidtide with Apache License 2.0 6 votes vote down vote up
def test_fastcorrelate(display=False):
    inlen = 1000
    offset = 100
    sig1 = np.zeros((inlen), dtype='float')
    sig2 = np.zeros((inlen), dtype='float')
    sig1[int(inlen // 2) + 1] = 1.0
    sig2[int(inlen // 2) + offset + 1] = 1.0
    fastcorrelate_result = fastcorrelate(sig2, sig1)
    stdcorrelate_result = np.correlate(sig2, sig1, mode='full')
    midpoint = int(len(stdcorrelate_result) // 2) + 1
    if display:
        plt.figure()
        plt.ylim([-1.0, 3.0])
        plt.plot(fastcorrelate_result + 1.0)
        plt.plot(stdcorrelate_result)
        print('maximum occurs at offset', np.argmax(stdcorrelate_result) - midpoint + 1)
        plt.legend(['Fast correlate', 'Standard correlate'])
        plt.show()

    #assert (fastcorrelate_result == stdcorrelate_result).all
    aethresh = 10
    np.testing.assert_almost_equal(fastcorrelate_result, stdcorrelate_result, aethresh) 
Example #22
Source File: build_diagram.py    From NEUCOGAR with GNU General Public License v2.0 5 votes vote down vote up
def voltage_diagram(times, voltages, name, path):
    """
    Function for making voltage diagrams
    :param times:    (dict) times
    :param voltages: (dict) voltages
    :param name:     (str) name of brain part
    :param path:     (str) path to save diagram
    :return: None
    """
    pylab.figure()
    line_style = ""

    if type(times) is dict:
        # for each neuron plot
        for key in times:
            pylab.plot(times[key], voltages[key], line_style, label=key)
    else:
        raise ValueError("Unsupported value")

    pylab.ylabel("Membrane potential (mV)")
    pylab.xlabel("Time (ms)")
    pylab.legend(loc="best")
    pylab.title("Voltage" + name)
    pylab.grid(True)
    pylab.draw()
    pylab.savefig("{0}{1}.png".format(path, name), dpi=dpi_n, format='png')
    pylab.close() 
Example #23
Source File: helpers.py    From ESAC-stats-2014 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_polynomial_regression():
    rng = np.random.RandomState(0)
    x = 2*rng.rand(100) - 1

    f = lambda t: 1.2 * t**2 + .1 * t**3 - .4 * t **5 - .5 * t ** 9
    y = f(x) + .4 * rng.normal(size=100)

    x_test = np.linspace(-1, 1, 100)

    pl.figure()
    pl.scatter(x, y, s=4)

    X = np.array([x**i for i in range(5)]).T
    X_test = np.array([x_test**i for i in range(5)]).T
    regr = linear_model.LinearRegression()
    regr.fit(X, y)
    pl.plot(x_test, regr.predict(X_test), label='4th order')

    X = np.array([x**i for i in range(10)]).T
    X_test = np.array([x_test**i for i in range(10)]).T
    regr = linear_model.LinearRegression()
    regr.fit(X, y)
    pl.plot(x_test, regr.predict(X_test), label='9th order')

    pl.legend(loc='best')
    pl.axis('tight')
    pl.title('Fitting a 4th and a 9th order polynomial')

    pl.figure()
    pl.scatter(x, y, s=4)
    pl.plot(x_test, f(x_test), label="truth")
    pl.axis('tight')
    pl.title('Ground truth (9th order polynomial)') 
Example #24
Source File: View.py    From Deep-Spying with Apache License 2.0 5 votes vote down vote up
def plot_signal(self, title, timestamp, signal):
        if not self.to_save and not self.to_show:
            return

        pylab.figure()

        pylab.plot(timestamp, signal, color='m', label="signal")

        pylab.legend()

        pylab.title(title)
        pylab.xlabel('Time')
        pylab.ylabel('Amplitude') 
Example #25
Source File: View.py    From Deep-Spying with Apache License 2.0 5 votes vote down vote up
def plot_sensor_data_and_label(self, title, timestamp, x, y, z, label_timestamp, label=None):
        if not self.to_save and not self.to_show:
            return

        self.big_figure()

        pylab.plot(timestamp, x, color='r', label='x')
        pylab.plot(timestamp, y, color='g', label='y')
        pylab.plot(timestamp, z, color='b', label='z')

        for i in range(0, len(label_timestamp)):
            if label is not None:
                if i != 0:
                    pylab.axvline(label_timestamp[i], color="k", ls='dashed')
                else:
                    pylab.axvline(label_timestamp[i], color="k", label="keystroke", ls='dashed')
            else:
                pylab.axvline(label_timestamp[i], color="k", ls='dashed')

        pylab.legend()

        pylab.title(title)
        pylab.xlabel('Time')
        pylab.ylabel('Amplitude')
        if label:
            pylab.xticks(label_timestamp, label) 
Example #26
Source File: texttiling.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def demo(text=None):
    from nltk.corpus import brown
    import pylab
    tt=TextTilingTokenizer(demo_mode=True)
    if text is None: text=brown.raw()[:10000]
    s,ss,d,b=tt.tokenize(text)
    pylab.xlabel("Sentence Gap index")
    pylab.ylabel("Gap Scores")
    pylab.plot(range(len(s)), s, label="Gap Scores")
    pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores")
    pylab.plot(range(len(d)), d, label="Depth scores")
    pylab.stem(range(len(b)),b)
    pylab.legend()
    pylab.show() 
Example #27
Source File: helpers.py    From sklearn_pydata2015 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_polynomial_regression():
    rng = np.random.RandomState(0)
    x = 2*rng.rand(100) - 1

    f = lambda t: 1.2 * t**2 + .1 * t**3 - .4 * t **5 - .5 * t ** 9
    y = f(x) + .4 * rng.normal(size=100)

    x_test = np.linspace(-1, 1, 100)

    pl.figure()
    pl.scatter(x, y, s=4)

    X = np.array([x**i for i in range(5)]).T
    X_test = np.array([x_test**i for i in range(5)]).T
    regr = linear_model.LinearRegression()
    regr.fit(X, y)
    pl.plot(x_test, regr.predict(X_test), label='4th order')

    X = np.array([x**i for i in range(10)]).T
    X_test = np.array([x_test**i for i in range(10)]).T
    regr = linear_model.LinearRegression()
    regr.fit(X, y)
    pl.plot(x_test, regr.predict(X_test), label='9th order')

    pl.legend(loc='best')
    pl.axis('tight')
    pl.title('Fitting a 4th and a 9th order polynomial')

    pl.figure()
    pl.scatter(x, y, s=4)
    pl.plot(x_test, f(x_test), label="truth")
    pl.axis('tight')
    pl.title('Ground truth (9th order polynomial)') 
Example #28
Source File: resample.py    From rapidtide with Apache License 2.0 5 votes vote down vote up
def __init__(self, timeaxis, timecourse, padvalue=30.0, upsampleratio=100, doplot=False, debug=False,
                 method='univariate'):
        self.upsampleratio = upsampleratio
        self.padvalue = padvalue
        self.initstep = timeaxis[1] - timeaxis[0]
        self.initstart = timeaxis[0]
        self.initend = timeaxis[-1]
        self.hiresstep = self.initstep / np.float64(self.upsampleratio)
        self.hires_x = np.arange(timeaxis[0] - self.padvalue, self.initstep * len(timeaxis) + self.padvalue,
                                 self.hiresstep)
        self.hiresstart = self.hires_x[0]
        self.hiresend = self.hires_x[-1]
        if method == 'poly':
            self.hires_y = 0.0 * self.hires_x
            self.hires_y[int(self.padvalue // self.hiresstep) + 1:-(int(self.padvalue // self.hiresstep) + 1)] = \
                signal.resample_poly(timecourse, np.int(self.upsampleratio * 10), 10)
        elif method == 'fourier':
            self.hires_y = 0.0 * self.hires_x
            self.hires_y[int(self.padvalue // self.hiresstep) + 1:-(int(self.padvalue // self.hiresstep) + 1)] = \
                signal.resample(timecourse, self.upsampleratio * len(timeaxis))
        else:
            self.hires_y = doresample(timeaxis, timecourse, self.hires_x, method=method)
        self.hires_y[:int(self.padvalue // self.hiresstep)] = self.hires_y[int(self.padvalue // self.hiresstep)]
        self.hires_y[-int(self.padvalue // self.hiresstep):] = self.hires_y[-int(self.padvalue // self.hiresstep)]
        if debug:
            print('fastresampler __init__:')
            print('    padvalue:, ', self.padvalue)
            print('    initstep, hiresstep:', self.initstep, self.hiresstep)
            print('    initial axis limits:', self.initstart, self.initend)
            print('    hires axis limits:', self.hiresstart, self.hiresend)

        # self.hires_y[:int(self.padvalue // self.hiresstep)] = 0.0
        # self.hires_y[-int(self.padvalue // self.hiresstep):] = 0.0
        if doplot:
            fig = pl.figure()
            ax = fig.add_subplot(111)
            ax.set_title('fastresampler initial timecourses')
            pl.plot(timeaxis, timecourse, self.hires_x, self.hires_y)
            pl.legend(('input', 'hires'))
            pl.show() 
Example #29
Source File: test_mi.py    From rapidtide with Apache License 2.0 5 votes vote down vote up
def test_calc_MI(display=False):
    inlen = 1000
    offset = 100
    filename1 = "testdata/lforegressor.txt"
    filename2 = "testdata/lforegressor.txt"
    sig1 = tide_io.readvec(filename1)
    sig2 = np.power(sig1, 2.0)
    sig3 = np.power(sig1, 3.0)
    
    kstart = 3
    kend = 100
    linmivals = []
    sqmivals = []
    cubemivals = []
    for clustersize in range(kstart, kend, 2):
        linmivals.append(calc_MI(sig1, sig1, clustersize) / np.log(clustersize))
        sqmivals.append(calc_MI(sig2, sig1, clustersize) / np.log(clustersize))
        cubemivals.append(calc_MI(sig3, sig1, clustersize) / np.log(clustersize))

    if display:
        plt.figure()
        #plt.ylim([-1.0, 3.0])
        plt.plot(np.array(range(kstart, kend, 2)), np.array(linmivals), 'r')
        plt.plot(np.array(range(kstart, kend, 2)), np.array(sqmivals), 'g')
        plt.plot(np.array(range(kstart, kend, 2)), np.array(cubemivals), 'b')
        #print('maximum occurs at offset', np.argmax(stdcorrelate_result) - midpoint + 1)
        plt.legend(['Mutual information', 'Squared mutual information', 'Cubed mutual information'])
        plt.show()

    aethresh = 10
    np.testing.assert_almost_equal(1.0, 1.0, 1e-5) 
Example #30
Source File: system.py    From Motiftoolbox with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, info=None, position=None, traces=None):
		win.window.__init__(self, position)

		self.x_orbit, self.y_orbit, self.z_orbit, self.orbit_period = None, None, None, None
		self.dt = 0.03
		self.stride = 10
		self.THRESHOLD = model.THRESHOLD
		self.info = info
		self.traces = traces

		self.ax = self.fig.add_subplot(111, yticks=[-50, -25, 0, 25])
		self.ax.set_xlim(0., 0.6)
		self.V_min, self.V_max = -60.0, 40.0
		self.ax.set_ylim(self.V_min, self.V_max)

		self.ax.set_xlabel(r'K$^{+}$ gating $m_{K2}$ (a.u.)', fontsize=17)
		self.ax.set_ylabel(r'membrane voltage $V$ (mV)', fontsize=17)

		self.li_traj, = self.ax.plot([], [], 'k-', lw=1., label='Bursting Orbit')
		self.li_ncl_x, = self.ax.plot([], [], 'r--', lw=2., label='$\dot{V}=0$')
		self.li_ncl_z, = self.ax.plot([], [], 'g--', lw=2., label='$\dot{m}_{K2}=0$')
		pl.legend(loc=0)
		self.li_threshold = self.ax.axhline(y=1000.*model.THRESHOLD)
		self.tx_state_space = self.ax.text(0.2, -0.01, '', color='r')

		self.refresh_nullclines()
		self.refresh_orbit()

		self.fig.canvas.mpl_connect('button_press_event', self.on_button)
		self.fig.canvas.mpl_connect('button_release_event', self.off_button)
		self.fig.canvas.mpl_connect('axes_enter_event', self.focus_in)