本文整理汇总了Python中matplotlib.pyplot.cm.rainbow函数的典型用法代码示例。如果您正苦于以下问题:Python rainbow函数的具体用法?Python rainbow怎么用?Python rainbow使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rainbow函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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()
示例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
示例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())
示例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()
示例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')
示例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
示例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()
示例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()
示例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
示例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
示例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()
示例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))
示例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
示例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')