• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python cm.rainbow函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.pyplot.cm.rainbow函数的典型用法代码示例。如果您正苦于以下问题:Python rainbow函数的具体用法?Python rainbow怎么用?Python rainbow使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了rainbow函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: single_genome

def single_genome( alignment_full, number=5):
    samples=random.sample(range(len(alignment_full)), number)
    ref=samples[0]
    rest=samples[1:]
    fig=plt.figure()
    fig = plt.figure(figsize=(18, 12))
    fig.patch.set_facecolor('w')
    fig.add_axes=True
    color=iter(cm.rainbow(numpy.linspace(0,1,number)))
    i=1
    for other in rest:
        c=next(color)
        align=[alignment_full[ref], alignment_full[other]]
        seg=generate_windows(align)
        x1=[rec[0] for rec in seg]
        y1=[rec[1] for rec in seg]
        mean_div=numpy.mean(y1)
        sub1=plt.subplot(2, 2, i)
        plt.plot(x1, y1, color=c)
        plt.axhline(y=mean_div, color='r', linestyle='-')
        plt.xlabel("Position in Core Genome (bp)")
        print ref
        print other
        plt.ylabel('Pairwise nucleotide diversity', fontsize=16)
        plt.xlim(0, max(x1))
        i=i+1
    fig.patch.set_facecolor('w')
    fig.add_axes=True
    fig.tight_layout()
    plt.savefig("pairwise_divergence_statistics.pdf", facecolor=fig.get_facecolor(), edgecolor='black', transparent=True)
    print "Reference is:" + str(ref)
    print "Rest are:" + str(rest)
开发者ID:tkarasov,项目名称:Pseudomonas_genomes,代码行数:32,代码来源:plot_core_diversity.py


示例2: class_wise_rocch

def class_wise_rocch(y_true_df, y_score_df):
    """
    y_true_df: DataFrame, [samples x classes]
    y_score_df: DataFrame, [samples x classes]
    """
    # calculate fpr/tpr per class
    fprs, tprs, aucs, eer_vals = [], [], [], []
    for yc, pc in zip(y_true_df, y_score_df):
        y_true = y_true_df[yc].values
        y_score = y_score_df[pc].values
        fpr, tpr, _, y_calibr, p_calibr = sklearn_rocch(y_true, y_score)
        fprs.append(fpr)
        tprs.append(tpr)
        aucs.append(sk_metrics.auc(fpr, tpr))
        eer_vals.append(eer(y_calibr, p_calibr))

    # plot ROCCH curves
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, frameon=True)
    n_classes = len(y_true_df.columns)
    color = iter(cm.rainbow(np.linspace(0, 1, n_classes)))
    for c in range(n_classes):
        mfom_plt.view_roc_curve(ax, fprs[c], tprs[c], roc_auc=aucs[c], eer_val=eer_vals[c],
                                color=next(color), title='ROC convex hull')
    fig.tight_layout()
    plt.show()
开发者ID:Vanova,项目名称:PyNNier,代码行数:26,代码来源:score_analysis.py


示例3: plotdisptraj

def plotdisptraj(s, P_UCS, E, E0, UCS, UC, diagnostics):
    # measured energy dependant offset at FOMS normalized to 0 for EbE0=1
    xf1t = lambda EbE0: -.078269*EbE0 + .078269     # + .059449
    xf2t = lambda EbE0: -.241473*EbE0 + .241473     # + .229314
    xf6t = lambda EbE0: 1.174523*EbE0 - 1.174523    # - 1.196090
    xf7t = lambda EbE0: .998679*EbE0 - .998679      # - 1.018895
    xf8t = lambda EbE0: .769875*EbE0 - .769875      # - .787049
    steps = 6
    X = [empty([6, P_UCS+1]) for i in range(steps)]
    dEbE = linspace(-0.005, 0.005, steps)
    for deltaE, i in zip(dEbE, range(steps)):
        # R calculated for every energy (not necessary)
        gamma = (E+deltaE*E)/E0+1
        R = UCS2R(P_UCS, UCS, gamma)
        X[i][:, 0] = array([0, 0, 0, 0, 0, deltaE])
        X[i] = trackpart(X[i], R, P_UCS, P_UCS)*1e3
    fig = Figure()
    ax = fig.add_subplot(1, 1, 1)
    drawlattice(ax, UC, diagnostics, X, 0)
    ax.set_xlabel(r'orbit position s / (m)')
    ax.set_ylabel(r'radial displacement / (mm)')
    x = [s[UCS[0, :] == 7][i] for i in [0, 1, 5, 6, 7]]
    color = iter(cm.rainbow(linspace(0, 1, steps)))
    for i in range(steps):
        c = next(color)
        EE0 = 1 + dEbE[i]
        y = array([xf1t(EE0), xf2t(EE0), xf6t(EE0), xf7t(EE0), xf8t(EE0)])*1e3
        ax.plot(x, y, 'o', c=c)
        ax.plot(s, X[i][0, :], c=c, label=r'$\delta={:g}$\textperthousand'.format(dEbE[i]*1e3))
    ax.plot([], [], 'ok', label=r'measured')
    #ax.get_xaxis().set_visible(False)
    #leg = ax.legend(fancybox=True, loc=0)
    #leg.get_frame().set_alpha(0.5)
    ax.set_xlim([0, nanmax(s)])
    return fig
开发者ID:kramerfelix,项目名称:accpy,代码行数:35,代码来源:plot.py


示例4: branch_plot

def branch_plot(name, results):
    if not results: return
    for res in results:
        del res['Clock']
        del res['Instruct']
        del res['Core cyc']
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import cm
    import numpy as np
    fig, ax = plt.subplots()
    fig.canvas.set_window_title(name)
    num_samples = len(results)
    num_counters = len(results[0])
    width = 1.0 / (num_counters + 1)
    rects = []
    color = cm.rainbow(np.linspace(0, 1, num_counters))
    for counter_index in range(num_counters):
        counter_name = results[0].keys()[counter_index]
        xs = np.arange(num_samples) + width * counter_index
        ys = [a[counter_name] for a in results]
        rects.append(ax.bar(xs, ys, width, color=color[counter_index]))
    ax.set_ylabel("Count")
    ax.set_xlabel("Run #")
    ax.set_title(name)
    ax.legend((x[0] for x in rects), results[0].keys())
开发者ID:FeiYeYe,项目名称:agner,代码行数:25,代码来源:branch.py


示例5: visualize_edges

def visualize_edges(X, A, Z, threshold, title = ""):
    '''Visualize the unweighted instance-anchor edges

    Example: tools.visualize_edges(X, A, Z, 1e-6, alg)
    '''
    d = X.shape[1]
    assert d == 2 or d == 3, "only 2/3-D edges can be visualized"

    links = np.where(Z>threshold)
    # source and target vertices
    s = X[links[0],:]
    t = A[links[1],:]

    fig = pyplot.figure()
    color=cm.rainbow(np.linspace(0, 1, A.shape[0]))

    if d == 3:
        ax = fig.add_subplot(111, projection='3d')
        ax.view_init(10,-75)
        edge = lambda i:([s[i,0], t[i,0]], [s[i,1], t[i,1]], [s[i,2], t[i,2]])
    if d == 2:
        ax = fig.add_subplot(111)
        edge = lambda i:([s[i,0], t[i,0]], [s[i,1], t[i,1]])

    for i in xrange(s.shape[0]):
        ax.plot(*edge(i), c=color[links[1][i],:], alpha=0.6)

    ax.set_title(title)
    fig.show()
开发者ID:quark0,项目名称:AnchorClouds,代码行数:29,代码来源:tools.py


示例6: plot_yhat

def plot_yhat(yhat, data, model_name):
	'''
	Args:
		yhat: an ndarray of the probability of each event for each class
		data: dictionary containing relevant data
	 Returns:
		a plot of the probability that each event in a known classes is predicted to be in a specific class
	'''
	y_test = data['y_test']
	w_test = data['w_test']
	matplotlib.rcParams.update({'font.size': 16})
	bins = np.linspace(0, 1, 30)
	plt.clf()

	#find probability of each class 
	for k in np.unique(y_test):
		fig = plt.figure(figsize=(11.69, 8.27), dpi=100)
		color = iter(cm.rainbow(np.linspace(0, 1, len(np.unique(y_test)))))
		#find the truth label for each class
		for j in np.unique(y_test):
			c = next(color)
			_ = plt.hist(
				yhat[:, k][y_test == j], 
				bins=bins, 
				histtype='step', 
				normed=True, 
				label=data['LabelEncoder'].inverse_transform(j),
				weights=w_test[y_test == j],
				color=c, 
				linewidth=1
			)
		plt.xlabel('P(y == {})'.format(data['LabelEncoder'].inverse_transform(k)))
		plt.ylabel('Weighted Normalized Number of Events')
		plt.legend()
		fig.savefig('p(y=={})_'.format(data['LabelEncoder'].inverse_transform(k)) + model_name + '.pdf')
开发者ID:YaleATLAS,项目名称:hh2yybbEventClassifier,代码行数:35,代码来源:plotting.py


示例7: plot_fcts

def plot_fcts(axis, x, ys, **plot_kargs):
    plot_kargs = check_matplot_arguments("linePlot",**plot_kargs)

    N = len(ys)
    if not plot_kargs['colors']:
        plot_kargs['colors']=cm.rainbow(np.linspace(0,1,N))

    # matplotlib.rcParams['text.usetex'] = True
    font_style = {'weight' : 'normal', 'size': plot_kargs['ticks_size'],'family':'serif','serif':['Palatino']}
    matplotlib.rc('font',**font_style)

    for y, label, color, lineStyle, opacity in zip(ys,plot_kargs['labels'],plot_kargs['colors'],plot_kargs['lineStyles'],plot_kargs['opacities']):
        axis.plot(x,y,lineStyle,color=color,label=r'%s'%(label),alpha=opacity)
    if plot_kargs['grid']==True:
        axis.grid(True)
    axis.legend(loc=plot_kargs['legend'])
    if 'x' in plot_kargs['log']:
        if 'symx' in plot_kargs['log']:
            axis.set_xscale('symlog')
        else:
            axis.set_xscale('log')
    if 'symy' in plot_kargs['log']:
        axis.set_yscale('symlog')
    elif 'symx' in plot_kargs['log']:
        print "boh"
    elif 'y' in plot_kargs['log']:
        axis.set_yscale('log')
    if plot_kargs["xrange"]!=0:
        axis.set_xlim(plot_kargs["xrange"])
    if plot_kargs["yrange"]!=0:
        axis.set_ylim(plot_kargs["yrange"])
    axis.set_xlabel(r'%s' %(plot_kargs['xyLabels'][0]),fontsize=plot_kargs["label_size"])
    axis.set_ylabel(r'%s' %(plot_kargs['xyLabels'][1]),fontsize=plot_kargs["label_size"])

    return axis
开发者ID:abailoni,项目名称:greedy_CNN,代码行数:35,代码来源:visualize.py


示例8: plot_time

def plot_time():

    file_list = os.listdir('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/')
    max_len = 0
    max_time = 0
    lines = ["", "--", "-.", ":"]
    color = iter(cm.rainbow(np.linspace(0, 1, len(file_list))))
    for item in file_list:
        filename = os.path.join('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/', item)
        maxflow_time = [] 
        iter_time = []
        energy = []
        extract_time(filename, maxflow_time, iter_time, energy)
        c = next(color)
        plot_list(maxflow_time, c)
        if(len(maxflow_time) > max_len):
            max_len = len(maxflow_time)
        if(max(maxflow_time) > max_time):
            max_time = max(maxflow_time)

    plt.axis([1, max_len + 1, 0, 1.1*max_time])
    plt.legend()
    plt.xlabel('Number of iteration')
    plt.ylabel('Time (in s)')
    plt.title('Linear static case: L = 10')
    plt.show()
开发者ID:pankajpansari,项目名称:max_of_convex,代码行数:26,代码来源:max_flow_time_plot.py


示例9: plot_energy

def plot_energy():

    file_list = os.listdir('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/')
    max_len = 0
    max_energy= 0
    min_energy= 1000000 
    lines = ["", "--", "-.", ":"]
    color = iter(cm.rainbow(np.linspace(0, 1, len(file_list))))
    for item in file_list:
        #        item = 'linear_L10_0.txt'
        filename = os.path.join('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/', item)
        #filename = '/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/linear_L10_7.txt'
        maxflow_time = [] 
        iter_time = []
        energy = []
        extract_time(filename, maxflow_time, iter_time, energy)
        c = next(color)
        plot_list(energy[1:], c)
        if(len(energy) > max_len):
            max_len = len(energy)
        if(max(energy[1:]) > max_energy):
            max_energy = max(energy[1:])
        if(min(energy) < min_energy):
            min_energy = min(energy)

    plt.axis([1, max_len + 1, 0.9*min_energy, 1.1*max_energy])
    plt.legend()
    plt.xlabel('Number of iteration')
    plt.ylabel('Energy')
    plt.title('Linear static case: L = 10')
    plt.show()
开发者ID:pankajpansari,项目名称:max_of_convex,代码行数:31,代码来源:max_flow_time_plot.py


示例10: get_colours

 def get_colours(self, ncolours):
     '''
     Returns n colors from the matplotlib rainbow colormap.
     '''
     from matplotlib.pyplot import cm
     colours = cm.rainbow(np.linspace(0,1,ncolours))
     return colours
开发者ID:sjara,项目名称:jaratoolbox,代码行数:7,代码来源:ephysinterface.py


示例11: display_analyze_results

def display_analyze_results(data):
    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig_crvfrq = plt.figure()
    ax_crvfrqplt = fig_crvfrq.add_subplot(111)
    #prepare color
    tol_nr_sctn = np.sum([len(strk) for strk in data['sections']])
    color_lettertraj=iter(cm.rainbow(np.linspace(0,1,tol_nr_sctn)))
    color_crvfrq=iter(cm.rainbow(np.linspace(0,1,tol_nr_sctn)))
    #plot letter sections in canvas
    letter_trajs = []
    for strk in data['sections']:
        for sctn in strk:
            c = next(color_lettertraj)
            tmp_letter_traj, = ax.plot(np.array(sctn)[:, 0], -np.array(sctn)[:, 1], linewidth=2.0, color=c)
            letter_trajs+=[tmp_letter_traj]
            ax.hold(True)
    ax.hold(False)
    #frequency analysis
    for strk_crv, strk_vel, strk_ang in zip(data['crvfrq'], data['velfrq'], data['ang_sections']):
        for crvt_sctn, vel_sctn, ang_sctn in zip(strk_crv, strk_vel, strk_ang):
            freq_bins = fftfreq(n=len(ang_sctn), d=ang_sctn[1]-ang_sctn[0])
            #cut to show only low frequency part
            n_freq = len(ang_sctn)/2+1
            #<hyin/Sep-25th-2015> need more investigation to see the meaning of fftfreq
            #some threads on stackoverflow suggests the frequency should be normalized by the length of array
            #but the result seems weird...                
            #power spectrum coefficient, see Huh et al, Spectrum of power laws for curved hand movements
            freq = np.abs(freq_bins[0:n_freq]*2*np.pi)
            beta = 2.0/3.0 * (1+freq**2/2.0)/(1+freq**2+freq**4/15.0)
            # print 'new section'
            # print freq
            # print beta
            # print np.abs(crvt_sctn[0:n_freq])
            c = next(color_crvfrq)
            ax_crvfrqplt.plot(freq, np.abs(crvt_sctn[0:n_freq])*beta, color=c)
            ax_crvfrqplt.hold(True)
            ax_crvfrqplt.plot(freq, np.abs(vel_sctn[0:n_freq]), color=c, linestyle='dashed')
            ax_crvfrqplt.set_ylabel('Normed Amplitude')
            ax_crvfrqplt.set_xlabel('Frequency')
            #cut the xlim
            ax_crvfrqplt.set_xlim([0, 8])
            ax_crvfrqplt.set_ylim([0.0, 1.0])
    ax_crvfrqplt.hold(False)
    plt.draw()
    return
开发者ID:navigator8972,项目名称:pytrajkin,代码行数:47,代码来源:pytrajkin_crvfrq.py


示例12: plotGraph

    def plotGraph(self, blocks, Q, pos=None):
        numOfActions = len(self.actions)
        numOfBlocks = len(blocks)

        plt.figure(1)
        if not pos:
            pos = nx.spring_layout(Q)
        nodeColors = cm.rainbow(np.linspace(0,1,numOfBlocks))
        edgeColors = cm.rainbow(np.linspace(0,1,numOfActions))
        for i in xrange(len(blocks)):
            nx.draw_networkx_nodes(Q,pos,nodelist=blocks[i],node_color=nodeColors[i])
        for i in xrange(numOfActions):
            acts = []
            for edge in Q.edges():
                if(Q.get_edge_data(*edge)["action"]==self.actions[i]):
                    acts.append(edge)
            nx.draw_networkx_edges(Q,pos,edgelist=acts,edge_color=[edgeColors[i]]*len(acts))
        plt.show()
开发者ID:ArielCHoffman,项目名称:BisimulationAlgorithms,代码行数:18,代码来源:PaigeAndTarjan.py


示例13: plot_straight_tracks

def plot_straight_tracks(event, labels=None):
    """
    Generate plot of the event with its tracks and noise hits.
    :param event: pandas.DataFrame with one event.
    :param labels: numpy.array shape=[n_hits], labels of recognized tracks.
    :return: matplotlib.pyplot object.
    """

    plt.figure(figsize=(10, 7))

    tracks_id = numpy.unique(event.TrackID.values)
    event_id = event.EventID.values[0]

    color=cm.rainbow(numpy.linspace(0,1,len(tracks_id)))

    # Plot hits
    for num, track in enumerate(tracks_id):

        X = event[event.TrackID == track].X.values.reshape((-1, 1))
        y = event[event.TrackID == track].y.values

        plt.scatter(X, y, color=color[num])

        # Plot tracks
        if track != -1:

            lr = LinearRegression()
            lr.fit(X, y)

            plt.plot(X, lr.predict(X), label=str(track), color=color[num])


    if labels != None:

        unique_labels = numpy.unique(labels)

        for lab in unique_labels:

            if lab != -1:

                X = event[labels == lab].X.values.reshape((-1, 1))
                y = event[labels == lab].y.values

                lr = LinearRegression()
                lr.fit(X, y)

                X = event.X.values.reshape((-1, 1))

                plt.plot(X, lr.predict(X), color='0', alpha=0.5)




    plt.xlabel('X')
    plt.ylabel('y')
    plt.legend(loc='best')
    plt.title('EventID is ' + str(event_id))
开发者ID:ClaudiaBert,项目名称:mlhep2016,代码行数:57,代码来源:utils.py


示例14: _get_color_dict

def _get_color_dict(baseline_tagger, cFraction):
    from matplotlib.pyplot import cm

    color_dict = {}
    color=iter(cm.rainbow(np.linspace(0,1,len(cFraction))))
    for c_fraction in cFraction:
        c=next(color)
        color_dict.update({"DL1c"+str(int(c_fraction*100.)): c,})

    color_dict.update({baseline_tagger: "black"})
    return color_dict
开发者ID:Marie89,项目名称:BTagging_DL1,代码行数:11,代码来源:PlotROC.py


示例15: plot_latent_variable

 def plot_latent_variable(epoch):
     output = f_enc()
     plt.figure(figsize=(8,8))
     color=cm.rainbow(numpy.linspace(0,1,10))
     for l,c in zip(range(10),color):
         ix = numpy.where(dataset[1][1].get_value()==l)[0]
         plt.scatter(output[ix,0],output[ix,1],c=c,label=l,s=8,linewidth=0)
     plt.xlim([-5.0,5.0])
     plt.ylim([-5.0,5.0])
     plt.legend(fontsize=15)
     plt.savefig('z_epoch' + str(epoch) + '.pdf')
开发者ID:boscotsang,项目名称:adversarial_autoencoder,代码行数:11,代码来源:train.py


示例16: plot_points_on_background

def plot_points_on_background(points, background, noise=False, base_size=200):
    plt.imshow(background, cmap='gray')

    colours = cm.rainbow(numpy.linspace(0, 1, len(points)))
    for colour, (x, y) in zip(colours, points):
        if noise:
            x += numpy.random.normal(scale=0.5)
            y += numpy.random.normal(scale=0.5)
        plt.scatter(x, y, marker='x', c=colour, s=base_size)
    plt.axis('off')
    plt.xlim((0, background.shape[0]))
    plt.ylim((0, background.shape[1]))
开发者ID:chengsoonong,项目名称:crowdastro,代码行数:12,代码来源:plot.py


示例17: plot_graph

def plot_graph(time_stamp, HR, SBP, DBP, RR, SpO2):
        plot = []
        plot.append(HR)
        plot.append(SBP)
        plot.append(DBP)
        plot.append(RR)
        plot.append(SpO2)

        nums = np.linspace(0,1,5) - 0.01
        time_stamp = convert_to_float(time_stamp)

        min_x = time_stamp[0]
        max_x = time_stamp[-1]
        min_y = max_d(HR, SBP, DBP, RR, SpO2)
        max_y = min_d(HR, SBP, DBP, RR, SpO2)

        for i in range(5):
                plt.plot(time_stamp, plot[i], color=cm.rainbow(nums[i]))

        # fig = plt.figure(1)
        # ax = fig.add_subplot(111, autoscale_on=False, xlim=(min_x,max_x), ylim=(min_y,max_y))


        plt.title("Physiological Data Log")
        plt.xlabel("Time")
        plt.ylabel("Value")
        # plt.text(50,80,"purple: HR")
        # plt.text(50,70,"blue: SBP")
        # plt.text(50,60,"green: DBP")
        # plt.text(50,50,"orange: RR")
        # plt.text(50,40,"red: SpO2")

        arrow_width = 6
        arrow_shrink = 0.1
        arrow_frac = 0.4
        plt.annotate("HR", xy=(max_x*4/5,HR[len(time_stamp)*4/5-1]),xytext=(max_x*4/5 - 30,HR[len(time_stamp)*4/5-1] + 10),
                     arrowprops=dict(facecolor='purple', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac))

        plt.annotate("SBP", xy=(max_x*2/5,SBP[len(time_stamp)*2/5-1]),xytext=(max_x*2/5 - 30,SBP[len(time_stamp)*2/5-1] + 10),
                     arrowprops=dict(facecolor='blue', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac))

        plt.annotate("DBP", xy=(max_x*3/5,DBP[len(time_stamp)*3/5-1]),xytext=(max_x*3/5 - 30,DBP[len(time_stamp)*3/5-1] + 10),
                     arrowprops=dict(facecolor='green', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac))

        plt.annotate("RR", xy=(max_x/5,RR[len(time_stamp)/5-1]),xytext=(max_x/5 - 30,RR[len(time_stamp)/5-1] + 10),
                     arrowprops=dict(facecolor='orange', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac))

        plt.annotate("SpO2", xy=(max_x,SpO2[-1]),xytext=(max_x - 30,SpO2[len(time_stamp)-1] + 10),
                     arrowprops=dict(facecolor='red', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac))
        plt.show()
开发者ID:ScreenBasedSimulator,项目名称:BioGears-Paper,代码行数:50,代码来源:plot_csv.py


示例18: plot_dat_variance

def plot_dat_variance(TE,TRE):
	fig, ax = plt.subplots()
	ax.minorticks_on()
	color=cm.rainbow(np.linspace(0,1.0,5))
	for x in TE:
		plt.plot(range(1,21,2),[np.array(TE[x][i]).mean() for i in range(len(TE[x]))],linewidth=3,c=color[x-1],label='$2j='+str(x)+'$'+' test')
		plt.plot(range(1,21,2),[np.array(TRE[x][i]).mean() for i in range(len(TRE[x]))],'--',linewidth=3,c=color[x-1],label='$2j='+str(x)+'$'+' training')	
	
	plt.xlabel('Number of Nearest Neighbors',fontsize=24)
	plt.ylabel('Prediction Accuracy', fontsize=24)
	plt.axis([1,19,0.6,1.0], fontsize=24)	
	plt.legend(bbox_to_anchor=(1.1,-0.11),prop={'size':18},ncol=3)	
	#plt.legend()
	plt.savefig('Variance.eps', edgecolor='none',bbox_inches='tight')
开发者ID:Sandy4321,项目名称:BiDef,代码行数:14,代码来源:generate_defect_structs.py


示例19: plot_q_z

def plot_q_z(data, filename, n_label=10, xlim=None, ylim=None):
    plt.clf()
    fig, ax = plt.subplots(ncols=1, figsize=(8,8))
    color = cm.rainbow(np.linspace(0,1,n_label))
    for l, c in zip(range(10), color):
        ix = np.where(data[:,2]==l)
        ax.scatter(data[ix,0], data[ix, 1], c=c, label=l, s=8, linewidth=0)
    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)
        
    plt.savefig(filename)
    plt.close()
开发者ID:supersaiakujin,项目名称:adversarial_autoencoders,代码行数:14,代码来源:adversarial_autoencoders.py


示例20: cluster_and_plot

def cluster_and_plot(list_of_lists, plot_full_file_name):
    """
    the second stage of the plotting that clusters and plots the data
    TODO's: format graph
    :param list_of_lists: list of lists that has the pertinent plotting data
    :param plot_full_file_name: the file name of the plot to be saved
    """
    logger = logging.getLogger()
    try:
        list_count = 1  # count for appending to file names (necessary for split plots)
        plot_file_name = plot_full_file_name[:-4]  # strip .png off file name so adjustments can be made
        # iterate over lists -- needed if plot is split into multiple
        for list in list_of_lists:
            # add count for split plots
            plot_full_file_name = plot_file_name + '-{}.png'.format(list_count)
            rank_list, name_list, position_list, average_rank_list, standard_deviation_list, k_value = list[0], list[1], list[2], list[3], list[4], list[5]
            # empty list that will be converted into array
            average_rank_array = []
            for n in range(len(average_rank_list)):
                # build list from item and append the list to the list of lists
                item_list = [average_rank_list[n]]
                average_rank_array.append(item_list)
            # convert the list of lists to an array
            X = np.array(average_rank_array)
            # initialize KMeans and fit over the array
            kmeans = KMeans(n_clusters=k_value)
            kmeans.fit(X)
            centroids = kmeans.cluster_centers_  # not used here
            # array of labels where a cluster value is assigned to each item
            labels = kmeans.labels_
            # color list that will automatically generate based on number of clusters
            colors = []
            color_cycle = iter(cm.rainbow(np.linspace(0, 5, len(labels))))
            for i in range(len(labels)):
                c = next(color_cycle)
                colors.append(c)
            # iterate over array and plot values, standard deviation, and color by clusters
            for i in range(len(X)):
                plt.errorbar(X[i][0], rank_list[i], xerr=standard_deviation_list[i], marker='.', markersize=4, color=colors[labels[i]], ecolor=colors[labels[i]])
                position = position_list[i][10:].upper() if len(position_list[i]) > 10 else position_list[i].upper()
                plt.text(X[i][0] + standard_deviation_list[i] + 1, rank_list[i], "{} {} ({})".format(name_list[i], position, rank_list[i]), size=6, color=colors[labels[i]],
                         ha="left", va="center")
            plt.gca().invert_yaxis()  # top-left of graph should start at 1
            # plt.show()
            plt.savefig(plot_full_file_name, bbox_inches='tight')  # save the png file
            plt.clf()  # clear plot after use otherwise subsequent iterations
            list_count += 1
    except Exception as e:
        logger.info("Clustering and plotting failed with: {}".format(e))
开发者ID:borisachen,项目名称:fftiers,代码行数:49,代码来源:joelwhitney.py



注:本文中的matplotlib.pyplot.cm.rainbow函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python rcParams.get函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.yticks函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap