本文整理汇总了Python中matplotlib.pyplot.subplots_adjust函数的典型用法代码示例。如果您正苦于以下问题:Python subplots_adjust函数的具体用法?Python subplots_adjust怎么用?Python subplots_adjust使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了subplots_adjust函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: visualize_type
def visualize_type():
# grab our parsed data
data_file = parse.parse(MY_FILE,",")
# make a new variable, 'counter', from iterating through each line
# of data in the parsed data, and count how many incidents happen
# by category
counter = Counter(item["Category"]for item in data_file)
# Set the labels which are based on the keys of our counter.
# Since order doesn't matter, we can just used counter.keys()
labels = tuple(counter.keys())
# Set exactly where the labels hit the x-axis
# numpy.arange() creates evenly spaced numbers
xlocations = np.arange(len(labels)) + 0.5
# Width of each bar that will be plotted
width = 0.5
# Assign data to a bar plot (similar to plt.plot()!)
plt.bar(xlocations, counter.values(),width=width)
# Assign labels and tick location to x-axis
plt.xticks(xlocations + width /2, labels, rotation = 90)
# Give some more room so the x-axis labels aren't cut off in the
# graph
plt.subplots_adjust(bottom=0.5)
# Make the overall graph/figure is larger
plt.rcParams['figure.figsize'] = 12,12
# Save the graph!
plt.savefig("Type.png")
# Close plot figure
plt.clf()
开发者ID:yanniey,项目名称:DataVisualization_Python,代码行数:28,代码来源:graph.py
示例2: plot_images
def plot_images(data_list, data_shape="auto", fig_shape="auto"):
"""
plotting data on current plt object.
In default,data_shape and fig_shape are auto.
It means considered the data as a sqare structure.
"""
n_data = len(data_list)
if data_shape == "auto":
sqr = int(n_data ** 0.5)
if sqr * sqr != n_data:
data_shape = (sqr + 1, sqr + 1)
else:
data_shape = (sqr, sqr)
plt.figure(figsize=data_shape)
for i, data in enumerate(data_list):
plt.subplot(data_shape[0], data_shape[1], i + 1)
plt.gray()
if fig_shape == "auto":
fig_size = int(len(data) ** 0.5)
if fig_size ** 2 != len(data):
fig_shape = (fig_size + 1, fig_size + 1)
else:
fig_shape = (fig_size, fig_size)
Z = data.reshape(fig_shape[0], fig_shape[1])
plt.imshow(Z, interpolation="nearest")
plt.tick_params(labelleft="off", labelbottom="off")
plt.tick_params(axis="both", which="both", left="off", bottom="off", right="off", top="off")
plt.subplots_adjust(hspace=0.05)
plt.subplots_adjust(wspace=0.05)
开发者ID:Nyker510,项目名称:Chainer,代码行数:30,代码来源:save_mnist_digit_fig.py
示例3: build_graph
def build_graph(self):
""" Update the plot area with loss values and cycle through to
animate """
self.ax1.set_xlabel('Iterations')
self.ax1.set_ylabel('Loss')
self.ax1.set_ylim(0.00, 0.01)
self.ax1.set_xlim(0, 1)
losslbls = [lbl.replace('_', ' ').title() for lbl in self.losskeys]
for idx, linecol in enumerate(['blue', 'red']):
self.losslines.extend(self.ax1.plot(0, 0,
color=linecol,
linewidth=1,
label=losslbls[idx]))
for idx, linecol in enumerate(['navy', 'firebrick']):
lbl = losslbls[idx]
lbl = 'Trend{}'.format(lbl[lbl.rfind(' '):])
self.trndlines.extend(self.ax1.plot(0, 0,
color=linecol,
linewidth=2,
label=lbl))
self.ax1.legend(loc='upper right')
plt.subplots_adjust(left=0.075, bottom=0.075, right=0.95, top=0.95,
wspace=0.2, hspace=0.2)
plotcanvas = FigureCanvasTkAgg(self.fig, self.frame)
plotcanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
ani = animation.FuncAnimation(self.fig, self.animate, interval=2000, blit=False)
plotcanvas.draw()
开发者ID:huangjiancong1,项目名称:faceswap-huang,代码行数:31,代码来源:gui.py
示例4: make_lick_individual
def make_lick_individual(targetSN, w1, w2):
""" Make maps for the kinematics. """
filename = "lick_corr_sn{0}.tsv".format(targetSN)
binimg = pf.getdata("voronoi_sn{0}_w{1}_{2}.fits".format(targetSN, w1, w2))
intens = "collapsed_w{0}_{1}.fits".format(w1, w2)
extent = calc_extent(intens)
bins = np.loadtxt(filename, usecols=(0,), dtype=str).tolist()
bins = np.array([x.split("bin")[1] for x in bins]).astype(int)
data = np.loadtxt(filename, usecols=np.arange(25)+1).T
labels = [r'Hd$_A$', r'Hd$_F$', r'CN$_1$', r'CN$_2$', r'Ca4227', r'G4300',
r'Hg$_A$', r'Hg$_F$', r'Fe4383', r'Ca4455', r'Fe4531', r'C4668',
r'H$_\beta$', r'Fe5015', r'Mg$_1$', r'Mg$_2$', r'Mg$_b$', r'Fe5270',
r'Fe5335', r'Fe5406', r'Fe5709', r'Fe5782', r'Na$_D$', r'TiO$_1$',
r'TiO$_2$']
mag = "[mag]"
ang = "[\AA]"
units = [ang, ang, mag, mag, ang, ang,
ang, ang, ang, ang, ang, ang,
ang, ang, mag, mag, ang, ang,
ang, ang, ang, ang, ang, mag,
mag]
lims = [[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None]]
pdf = PdfPages("figs/lick_sn{0}.pdf".format(targetSN))
fig = plt.figure(1, figsize=(6.25,5))
plt.subplots_adjust(bottom=0.12, right=0.97, left=0.09, top=0.96)
plt.minorticks_on()
ax = plt.subplot(111)
ax.minorticks_on()
plot_indices = np.arange(12,22)
for i, vector in enumerate(data):
if i not in plot_indices:
continue
print "Making plot for {0}...".format(labels[i])
kmap = np.zeros_like(binimg)
kmap[:] = np.nan
for bin,v in zip(bins, vector):
idx = np.where(binimg == bin)
kmap[idx] = v
vmin = lims[i][0] if lims[i][0] else np.median(vector) - 2 * vector.std()
vmax = lims[i][1] if lims[i][1] else np.median(vector) + 2 * vector.std()
m = plt.imshow(kmap, cmap="inferno", origin="bottom", vmin=vmin,
vmax=vmax, extent=extent, aspect="equal")
make_contours()
plt.minorticks_on()
plt.xlabel("X [kpc]")
plt.ylabel("Y [kpc]")
plt.xlim(extent[0], extent[1])
plt.ylim(extent[2], extent[3])
cbar = plt.colorbar(m)
cbar.set_label("{0} {1}".format(labels[i], units[i]))
pdf.savefig()
plt.clf()
pdf.close()
return
开发者ID:kadubarbosa,项目名称:hydramuse,代码行数:60,代码来源:maps.py
示例5: plot_flux
def plot_flux(f, q_left, q_right, plot_zero=True):
qvals = np.linspace(q_right, q_left, 200)
fvals = f(qvals)
dfdq = np.diff(fvals) / (qvals[1]-qvals[0]) # approximate df/dq
qmid = 0.5*(qvals[:-1] + qvals[1:]) # midpoints for plotting dfdq
#plt.figure(figsize=(12,4))
plt.subplot(131)
plt.plot(qvals,fvals)
plt.xlabel('q')
plt.ylabel('f(q)')
plt.title('flux function f(q)')
plt.subplot(132)
plt.plot(qmid, dfdq)
plt.xlabel('q')
plt.ylabel('df/dq')
plt.title('characteristic speed df/dq')
plt.subplot(133)
plt.plot(dfdq, qmid)
plt.xlabel('df/dq')
plt.ylabel('q')
plt.title('q vs. df/dq')
if plot_zero:
plt.plot([0,0],[qmid.min(), qmid.max()],'k--')
plt.subplots_adjust(left=0.)
plt.tight_layout()
开发者ID:maojrs,项目名称:riemann_book,代码行数:29,代码来源:nonconvex_demos.py
示例6: fit_and_plot
def fit_and_plot(cand, spd):
data = cand.profile
n = len(data)
rms = np.std(data[(n/2):])
xs = np.linspace(0.0, 1.0, n, endpoint=False)
G = gauss._compute_data(cand)
print " Reduced chi-squared: %f" % (G.get_chisqr(data) / G.get_dof(n))
print " Baseline rms: %f" % rms
print " %s" % G.components[0]
fig1 = plt.figure(figsize=(10,10))
plt.subplots_adjust(wspace=0, hspace=0)
# upper
ax1 = plt.subplot2grid((3,1), (0,0), rowspan=2, colspan=1)
ax1.plot(xs, data/rms, color="black", label="data")
ax1.plot(xs, G.components[0].make_gaussian(n), color="red", label="best fit")
# lower
ax2 = plt.subplot2grid((3,1), (2,0), sharex=ax1)
ax2.plot(xs, data/rms - G.components[0].make_gaussian(n), color="black", label="residuals")
ax2.set_xlabel("Fraction of pulse window")
plt.figure()
plt.pcolormesh(xs, spd.waterfall_freq_axis(), spd.data_zerodm_dedisp, cmap=Greys)
plt.xlabel("Fraction of pulse window")
plt.ylabel("Frequency (MHz)")
plt.xlim(0, 1)
plt.ylim(spd.min_freq, spd.max_freq)
plt.show()
开发者ID:pscholz,项目名称:Ratings2.0,代码行数:31,代码来源:test_sp_gaussian.py
示例7: test_twin_axes_empty_and_removed
def test_twin_axes_empty_and_removed():
# Purely cosmetic font changes (avoid overlap)
matplotlib.rcParams.update({"font.size": 8})
matplotlib.rcParams.update({"xtick.labelsize": 8})
matplotlib.rcParams.update({"ytick.labelsize": 8})
generators = [ "twinx", "twiny", "twin" ]
modifiers = [ "", "host invisible", "twin removed", "twin invisible",
"twin removed\nhost invisible" ]
# Unmodified host subplot at the beginning for reference
h = host_subplot(len(modifiers)+1, len(generators), 2)
h.text(0.5, 0.5, "host_subplot", horizontalalignment="center",
verticalalignment="center")
# Host subplots with various modifications (twin*, visibility) applied
for i, (mod, gen) in enumerate(product(modifiers, generators),
len(generators)+1):
h = host_subplot(len(modifiers)+1, len(generators), i)
t = getattr(h, gen)()
if "twin invisible" in mod:
t.axis[:].set_visible(False)
if "twin removed" in mod:
t.remove()
if "host invisible" in mod:
h.axis[:].set_visible(False)
h.text(0.5, 0.5, gen + ("\n" + mod if mod else ""),
horizontalalignment="center", verticalalignment="center")
plt.subplots_adjust(wspace=0.5, hspace=1)
开发者ID:Acanthostega,项目名称:matplotlib,代码行数:26,代码来源:test_axes_grid1.py
示例8: dose_plot
def dose_plot(df,err,cols,scale='linear'):
n_rows = int(np.ceil(len(cols)/3.0))
plt.figure(figsize=(20,4 * n_rows))
subs = gridspec.GridSpec(n_rows, 3)
plt.subplots_adjust(hspace=0.54,wspace=0.27)
for col,sub in zip(cols,subs):
plt.subplot(sub)
for base in df['Base'].unique():
for drug in get_drugs_with_multiple_doses(filter_rows(df,'Base',base)):
data = thread_first(df,
(filter_rows,'Drug',drug),
(filter_rows,'Base',base),
(DF.sort, 'Dose'))
error = thread_first(err,
(filter_rows,'Drug',drug),
(filter_rows,'Base',base),
(DF.sort, 'Dose'))
if scale == 'linear':
plt.errorbar(data['Dose'],data[col],yerr=error[col])
title = "{} vs. Dose".format(col)
else:
plt.errorbar(data['Dose'],data[col],yerr=error[col])
plt.xscale('log')
title = "{} vs. Dose (Log Scale)".format(col)
plt.xticks(data['Dose'].values,data['Dose'].values)
plt.xlim(0.06,15)
label('Dose ({})'.format(data.Unit.values[0]), col,title,fontsize = 15)
plt.legend(df['Base'].unique(), loc = 0)
开发者ID:dela3499,项目名称:assay-explorer,代码行数:30,代码来源:view.py
示例9: begin
def begin():
m = Measurement()
sample_count = 0
try:
fifo = open("npipe","r")
add_data = AddData()
f1 = plt.figure(figsize=(15,8))
[sp1, sp2, sp3, sp4, sp5] = [f1.add_subplot(231), f1.add_subplot(232), f1.add_subplot(233), f1.add_subplot(234), f1.add_subplot(235)]
h1, = sp1.plot([],[])
h2, = sp2.plot([],[])
h3, = sp3.plot([],[])
h4, = sp4.plot([],[])
plt.subplots_adjust(hspace = 0.3)
plt.show(block=False)
while True:
if sample_count == 1024*5:
estimate_tf(m,[h1,h2,h3,h4],f1,[sp1, sp2, sp3, sp4, sp5])
sample_count = 0
m = Measurement()
add_data = AddData()
sample = get_data(fifo)
add_data(m,sample)
sample_count = sample_count + 1
except KeyboardInterrupt:
fifo.close()
exit(0)
开发者ID:wilseypa,项目名称:eis,代码行数:29,代码来源:Processor.py
示例10: prepare_plot
def prepare_plot(data):
# rearranging data into 4 arrays (just for clarity)
dataX = list(data[:, 0])
dataY = list(data[:, 1])
dataZ = list(data[:, 2])
dataC = list(data[:, 3])
# creating colormap according to present data
cm = plt.get_cmap('brg')
cNorm = matplotlib.colors.Normalize(vmin=min(dataC), vmax=max(dataC))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
# plotting
fig = plt.figure()
fig.set_facecolor('black')
ax = fig.add_subplot(111, projection='3d', axisbg='k')
ax.axis('off')
ax.w_xaxis.set_pane_color((0, 0, 0))
ax.w_yaxis.set_pane_color((0, 0, 0))
ax.w_zaxis.set_pane_color((0, 0, 0))
ax.grid(False)
ax.scatter(dataX, dataY, dataZ, c=scalarMap.to_rgba(dataC), edgecolors=scalarMap.to_rgba(dataC), marker='.', s=5)
scalarMap.set_array(dataC)
plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
return ax
开发者ID:cogtepsum,项目名称:3DBinaryData,代码行数:25,代码来源:visualisation.py
示例11: plotTestSet
def plotTestSet(self):
plt.figure(figsize=(12,6), facecolor='white')
# Plot test set currents
plt.subplot(3,1,1)
for tr in self.testset_traces :
plt.plot(tr.getTime(), tr.I, 'gray')
plt.ylabel("I (nA)")
plt.title('Experiment ' + self.name + " - Test Set")
# Plot test set voltage
plt.subplot(3,1,2)
for tr in self.testset_traces :
plt.plot(tr.getTime(), tr.V, 'black')
plt.ylabel("Voltage (mV)")
# Plot test set raster
plt.subplot(3,1,3)
cnt = 0
for tr in self.testset_traces :
cnt += 1
if tr.spks_flag :
plt.plot(tr.getSpikeTimes(), cnt*np.ones(tr.getSpikeNb()), '|', color='black', ms=5, mew=2)
plt.yticks([])
plt.ylim([0, cnt+1])
plt.xlabel("Time (ms)")
plt.subplots_adjust(left=0.10, bottom=0.07, right=0.95, top=0.92, wspace=0.25, hspace=0.25)
plt.show()
开发者ID:apdavison,项目名称:GIFFittingToolbox,代码行数:33,代码来源:Experiment.py
示例12: eval_mean_error_functions
def eval_mean_error_functions(act,ang,n_vec,toy_aa,timeseries,withplot=False):
""" Calculates sqrt(mean(E)) and sqrt(mean(F)) """
Err = np.zeros(6)
NT = len(timeseries)
size = len(ang[6:])/3
UA = ua(toy_aa.T[3:].T,np.ones(3))
fig,axis=None,None
if(withplot):
fig,axis=plt.subplots(3,2)
plt.subplots_adjust(wspace=0.3)
for K in range(3):
ErrJ = np.array([(i[K]-act[K]-2.*np.sum(n_vec.T[K]*act[3:]*np.cos(np.dot(n_vec,i[3:]))))**2 for i in toy_aa])
Err[K] = np.sum(ErrJ)
ErrT = np.array(((ang[K]+timeseries*ang[K+3]-UA.T[K]-2.*np.array([np.sum(ang[6+K*size:6+(K+1)*size]*np.sin(np.sum(n_vec*i,axis=1))) for i in toy_aa.T[3:].T])))**2)
Err[K+3] = np.sum(ErrT)
if(withplot):
axis[K][0].plot(ErrJ,'.')
axis[K][0].set_ylabel(r'$E$'+str(K+1))
axis[K][1].plot(ErrT,'.')
axis[K][1].set_ylabel(r'$F$'+str(K+1))
if(withplot):
for i in range(3):
axis[i][0].set_xlabel(r'$t$')
axis[i][1].set_xlabel(r'$t$')
plt.show()
EJ = np.sqrt(Err[:3]/NT)
ET = np.sqrt(Err[3:]/NT)
return np.array([EJ,ET])
开发者ID:jlsanders,项目名称:genfunc,代码行数:32,代码来源:genfunc_3d.py
示例13: plot_tfidf_classfeats
def plot_tfidf_classfeats(dfs):
fig = plt.figure(figsize=(12, 9), facecolor="w")
for i, df in enumerate(dfs):
ax = fig.add_subplot(len(dfs), 1, i+1)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.set_frame_on(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
if i == len(dfs)-1:
ax.set_xlabel("Feature name", labelpad=14, fontsize=14)
ax.set_ylabel("Tf-Idf score", labelpad=16, fontsize=14)
#if i == 0:
ax.set_title("Mean Tf-Idf scores for label = " + str(df.label), fontsize=16)
x = range(1, len(df)+1)
ax.bar(x, df.tfidf, align='center', color='#3F5D7D')
#ax.lines[0].set_visible(False)
ax.set_xticks(x)
ax.set_xlim([0,len(df)+1])
xticks = ax.set_xticklabels(df.feature)
#plt.ylim(0, len(df)+2)
plt.setp(xticks, rotation='vertical') #, ha='right', va='top')
plt.subplots_adjust(bottom=0.24, right=1, top=0.97, hspace=0.9)
plt.show()
开发者ID:amitsingh2783,项目名称:kaggle,代码行数:27,代码来源:analyze.py
示例14: plot_rolling_auto_home
def plot_rolling_auto_home(df_attack=None,df_defence=None, window=5, nstd=1,
detected_events_home=None,
detected_events_away=None, sky_events=None):
sns.set_context("notebook", font_scale=1.8 ,rc={"lines.linewidth": 3.5, "figure.figsize":(18,12) })
plt.subplots_adjust(bottom=0.85)
mean = pd.rolling_mean(df_attack, center=True, window=window)
std = pd.rolling_std(df_attack, center=True, window=window)
detected_plot_extrema = df_attack.ix[argrelextrema(df_attack.values, np.greater)]
df_filt_noise = df_attack[(df_attack > mean-std) & (df_attack < mean+std)]
df_filt_noise = df_filt_noise.ix[detected_plot_extrema.index].dropna()
df_filt_keep = df_attack[~((df_attack > mean-std) & (df_attack < mean+std))]
df_filt_keep = df_filt_keep.ix[detected_plot_extrema.index].dropna()
plt.plot(df_attack, color='#4CA64C', label='{} Attack'.format(all_matches[0]['home_team'].title()))
plt.fill_between(df_attack.index, (mean-nstd*std), (mean+nstd*std), interpolate=False, alpha=0.4, color='#B2B2B2', label='$\mu + {} \\times \sigma$'.format(nstd))
plt.scatter(df_filt_keep.index, df_filt_keep.values, marker='*', s=120, color='#000000', zorder=10, label='Selected maxima post-filtering')
plt.scatter(df_filt_noise.index, df_filt_noise.values, marker='x', s=120, color='#000000', zorder=10, label='Unselected maxima post-filtering')
df_defence.apply(lambda x: -1*x).plot(color='#000000', label='{} Defence'.format(all_matches[0]['home_team'].title()))
if(len(detected_events_home) > 0):
classifier_events_df_home= pd.DataFrame(detected_events_home)
classifier_events_df_home[classifier_events_df_home.category == 'GOAL']
if(len(detected_events_away) > 0):
classifier_events_df_away= pd.DataFrame(detected_events_away)
classifier_events_df_away[classifier_events_df_away.category == 'GOAL']
font0 = FontProperties(family='arial', weight='bold',style='italic', size=16)
for i, row in classifier_events_df_home.iterrows():
if row.category == 'OTHER':
continue
plt.text(row.event, df_attack.max(), "{} {} {}".format(all_matches[0]['home_team'].upper(), row.category, row.event), rotation='vertical', color='black', bbox=dict(facecolor='green', alpha=0.2))#, transform=transform)
for i, row in classifier_events_df_away.iterrows():
if row.category == 'OTHER':
continue
plt.text(row.event, (df_attack.max()), "{} {} {}".format(all_matches[0]['away_team'].upper(), row.category, row.event), rotation='vertical', color='black', bbox=dict(facecolor='red', alpha=0.2))
high_peak_position = 0;
if(df_attack.max() > df_defence.max()): high_peak_position = -(df_defence.max() * 2.0)
else: high_peak_position = -(df_defence.max() * 1.25)
# Functionality to include Sky Sports text commentary updates on plot for goal events.
# for i, row in pd.DataFrame(sky_events).iterrows():
# dedented_text = textwrap.dedent(row.text).strip()
# plt.text(row.event, high_peak_position, "@SkySports {} AT {}:\n{}:\n{}".format(row.category, row.event.time(), row.title, textwrap.fill(dedented_text, width=40)), color='black', bbox=dict(facecolor='blue', alpha=0.2))
plt.legend(loc=4)
ax = plt.gca()
label = ax.set_xlabel('time')
plt.ylabel('Tweet frequency')
plt.title('{} vs. {} (WK {}) - rolling averages window={} mins'.format(all_matches[0]['home_team'].title(), all_matches[0]['away_team'].title(), all_matches[0]['dbname'], window))
plt.savefig('{}attack_{}_plain.pdf'.format(all_matches[0]['home_team'].upper(), all_matches[0]['away_team'].upper()))
return detected_plot_extrema
开发者ID:RyanDRKane,项目名称:RK_FYP,代码行数:60,代码来源:SocialMediaAnalyticsSportsEvents_RyanKane_ProjectCode.py
示例15: plot_TP
def plot_TP():
with open ('p_files/ROC_table_' + str(seg) + '_pc' + str(p) + '_k' + str(k) + '.p', 'rb') as f:
ROC_table = pickle.load(f)
with open ('p_files/species_stats.p', 'rb') as f:
species_table = pickle.load(f)
with open ('p_files/species.p', 'rb') as f:
species_name = pickle.load(f)
xes = []#[item['number'] for item in ROC_table.values()]
yes = []#[item['fp'] for item in ROC_table.values()]
label = []
low_TP = []
for specie in ROC_table:
xes.append(species_table[specie])
yes.append(ROC_table[specie]['tp_rate'])
label.append(specie)
if float(ROC_table[specie]['tp_rate']) < 0.3 and species_table[specie] > 100:
#print(ROC_table[specie]['tp_rate'])
low_TP.append((specie, ROC_table[specie]['tp']))
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.1)
ax.plot([0,max(xes)],[0.3,0.3], ls="--")
ax.scatter(xes, yes, marker = '.')
for i, txt in enumerate(label):
if txt in interesting:
#if float(yes[i]) < 0.3 and xes[i] > 100 :
#print(txt)
#ax.annotate(parser.get_specie_name('../data/train/', str(species_name[txt][0]) + '.xml'), (xes[i],yes[i]))
ax.annotate(txt, (xes[i],yes[i]))
plt.suptitle('False Positive', fontsize = 14)
# ax.set_xlabel('Principal Components')
# ax.set_ylabel('Percentage of Variance')
plt.show()
开发者ID:HelenaBach,项目名称:bachelor,代码行数:35,代码来源:test_knn.py
示例16: gen_graph
def gen_graph(kind, xvals, yvals, xlabel, ylabel):
if len(xvals) > 10:
xvals = xvals[:10]
if len(yvals) > 10:
yvals = yvals[:10]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(yvals))
if kind == 'line':
ax.plot(ind, yvals[::-1])
elif kind == 'bar':
ax.bar(ind, yvals[::-1])
plt.xticks(ind + .3 / 2, xvals[::-1])
plt.xlabel(xlabel, labelpad=20)
plt.ylabel(ylabel)
plt.margins(xmargin=0.05)
plt.xticks(range(0, len(xvals)))
plt.subplots_adjust(bottom=0.3, right=0.9)
ax.set_xticklabels(xvals[::-1], rotation=45)
io = StringIO()
fig.savefig(io, format='png')
graph = io.getvalue().encode('base64')
return graph
开发者ID:bpospichil,项目名称:gerredes,代码行数:26,代码来源:manager.py
示例17: main
def main():
infileName = input("Enter the name of the input .wav file: ")
# Next, get all the samples as an array of short, and the parameters as a
# tuple (numChannels, sampleWidth, sampleRate, numFrames, not-used, not-used)
data, params = readwav(infileName)
# Example: find the maximum value in the samples
y = []
n = 1000 #initialize
x = np.arange(0,n//2,1)
for j in x:
s = 0
for i in range(j,n):
s += (data[i]*data[i-j])
s = s/(n-j)
y +=[s]
''' graph template'''
plt.plot(x, y, 'k')
plt.title('Autocorrelation', fontdict=font)
plt.xlabel('Lag time', fontdict=font)
plt.ylabel('Correlation', fontdict=font)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()
开发者ID:fffionaa,项目名称:school-project,代码行数:31,代码来源:pitchTrack.py
示例18: pylot_show
def pylot_show():
sql = 'select * from douban;'
cur.execute(sql)
rows = cur.fetchall() # 把表中所有字段读取出来
count = [] # 每个分类的数量
category = [] # 分类
for row in rows:
count.append(int(row[2]))
category.append(row[1])
y_pos = np.arange(len(category)) # 定义y轴坐标数
#color = cm.jet(np.array(2)/max(count))
plt.barh(y_pos, count, color='y', align='center', alpha=0.4) # alpha图表的填充不透明度(0~1)之间
plt.yticks(y_pos, category) # 在y轴上做分类名的标记
plt.grid(axis = 'x')
for count, y_pos in zip(count, y_pos):
# 分类个数在图中显示的位置,就是那些数字在柱状图尾部显示的数字
plt.text(count+3, y_pos, count, horizontalalignment='center', verticalalignment='center', weight='bold')
plt.ylim(+28.0, -2.0) # 可视化范围,相当于规定y轴范围
plt.title('douban_top250') # 图表的标题 fontproperties='simhei'
plt.ylabel('movie category') # 图表y轴的标记
plt.subplots_adjust(bottom = 0.15)
plt.xlabel('count') # 图表x轴的标记
#plt.savefig('douban.png') # 保存图片
plt.show()
开发者ID:AllenMao,项目名称:graduate,代码行数:28,代码来源:douban_movie_top250.py
示例19: plot_data
def plot_data(l):
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(l,30,facecolor='yellow', edgecolor='gray')
# Set the ticks to be at the edges of the bins.
#ax.set_xticks(bins)
# Set the xaxis's tick labels to be formatted with 1 decimal place...
#ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))
# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
# Label the raw counts
ax.annotate(str(int(count)), xy=(x, 0), xycoords=('data', 'axes fraction'),
xytext=(0, -40), textcoords='offset points', va='top', ha='center')
# Label the percentages
percent = '%0.0f%%' % (100 * float(count) / counts.sum())
ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
xytext=(0, -50), textcoords='offset points', va='top', ha='center')
# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.15)
plt.grid(True)
plt.xlabel("total reply")
plt.ylabel("pages")
plt.title("2014/10/21-2014/10/22 sina new pages")
plt.show()
开发者ID:lxserenade,项目名称:crawler,代码行数:30,代码来源:data_process.py
示例20: plotRPKMfor2strains
def plotRPKMfor2strains(sgrfileW_WT,sgrfileC_WT,sgrfileW_MUT,sgrfileC_MUT,chromosome,strains):
# Convert Watson sgr file to a watson sgrlist for a chromosome for WT
sgrlistforchromW_WT = ps.getSgrList(sgrfileW_WT,chromosome)
# Convert Crick sgr file to a crick sgrlist for a chromosome for WT
sgrlistforchromC_WT = ps.getSgrList(sgrfileC_WT,chromosome)
# Convert Watson sgr file to a watson sgrlist for a chromosome for MUT
sgrlistforchromW_MUT = ps.getSgrList(sgrfileW_MUT,chromosome)
# Convert Crick sgr file to a crick sgrlist for a chromosome for MUT
sgrlistforchromC_MUT = ps.getSgrList(sgrfileC_MUT,chromosome)
# Plot RPKM for Watson and Crick strands for the wild type species
rpkm.plotRPKM(sgrlistforchromW_WT,sgrlistforchromC_WT,strains[0],chromosome,211)
# Create some space between the subplots
plt.subplots_adjust(hspace=0.5)
# Plot RPKM for Watson and Crick strands for the knock out species
rpkm.plotRPKM(sgrlistforchromW_MUT,sgrlistforchromC_MUT,strains[1],chromosome,212)
# Show plot
plt.show()
开发者ID:JayKu4418,项目名称:ForkConvergenceComparison,代码行数:25,代码来源:importantfunctions.py
注:本文中的matplotlib.pyplot.subplots_adjust函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论