本文整理汇总了Python中matplotlib.pylab.gcf函数的典型用法代码示例。如果您正苦于以下问题:Python gcf函数的具体用法?Python gcf怎么用?Python gcf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gcf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_one_box
def test_one_box(box,tree,graphics=False,callback=None):#,f):
print 'box',box[0],box[1],':',
s = tree.search(box)
print ""
print "box search:", s
print "len(s):", len( s )
boxes = tree.boxes()
if graphics:
plt.close()
gfx.show_uboxes(boxes)
gfx.show_uboxes(boxes, S=s, col='r')
if len(s) < ((tree.dim**tree.depth)/2): # dim^depth/2
t = tree.insert(box)
if graphics:
boxes = tree.boxes()
gfx.show_uboxes(boxes, S=t, col='c')
print 'ins:',t
else:
t = tree.remove(s)
print 'rem:',t
if graphics:
gfx.show_box(box,col='g',alpha=0.5)
if callback:
plt.gcf().canvas.mpl_connect('button_press_event', callback)
plt.show()
示例2: channel_transform
def channel_transform(fitsfiles, h5file, iref= None):
"""
Channel Transformation
Take a list of k2 pixel files (must be from the same
channel). Find the centroids of each image and solve for the
linear transformation that takes one scene to another
"""
nstars = len(fitsfiles)
# Pull the first file to get length and data type
fitsfile0 = fitsfiles[0]
cent0 = fits_to_chip_centroid(fitsfile0)
channel = get_channel(fitsfile0)
print "Using channel = %i" % channel
# Determine the refence frame
if iref==None:
dfcent0 = pd.DataFrame(LE(cent0))
ncad = len(dfcent0)
med = dfcent0.median()
dfcent0['dist'] = (
(dfcent0['centx'] - med['centx'])**2 +
(dfcent0['centy'] - med['centy'])**2
)
dfcent0 = dfcent0.iloc[ncad/4:-ncad/4]
dfcent0 = dfcent0.dropna(subset=['centx','centy'])
iref = dfcent0['dist'].idxmin()
print "using reference frame %i" % iref
assert np.isnan(cent0['centx'][iref])==False,\
"Must select a valid reference cadence. No nans"
cent = np.zeros((nstars,cent0.shape[0]), cent0.dtype)
for i,fitsfile in enumerate(fitsfiles):
if (i%10)==0:
print i
cent[i] = fits_to_chip_centroid(fitsfile)
channel_i = get_channel(fitsfile)
assert channel==channel_i,"%i != %i" % (channel, channel_i)
trans,pnts = imtran.linear_transform(cent['centx'],cent['centy'],iref)
trans = pd.DataFrame(trans)
trans = pd.concat([trans,pd.DataFrame(LE(cent0))[['t','cad']]],axis=1)
trans = trans.to_records(index=False)
keys = cent.dtype.names
pnts = mlab.rec_append_fields(pnts,keys,[cent[k] for k in keys])
if h5file!=None:
with h5plus.File(h5file) as h5:
h5['trans'] = trans
h5['pnts'] = pnts
trans,pnts = read_channel_transform(h5file)
plot_trans(trans, pnts)
figpath = h5file[:-3] + '.png'
plt.gcf().savefig(figpath)
print "saving %s " % figpath
return cent
示例3: make_report
def make_report(event, dataframes, sequence, scores, part, n_iter, report_dir_base):
# Run through the sequence of decisions.
df = evaluate_sequence(sequence, dataframes)
df = pd.concat([df, scores], axis=1)
ns = ['a', 'b', 'c', 'd', 'e', 'f']
l_ns = map(lambda x: "l_" + x, ns)
o_ns = map(lambda x: "o_" + x, ns)
cols = [u'acc', u'rec', u'avg. gain', u'action', u'gain',
u'max gain', #u'num nuggets', u'max nuggets',
u'min select score', u'next score',] + l_ns + o_ns
print df[cols]
report_dir = os.path.join(
report_dir_base, "iter-{}".format(n_iter + 1), part)
if not os.path.exists(report_dir): os.makedirs(report_dir)
results_path = os.path.join(report_dir, event.fs_name() + ".tsv")
with open(results_path, "w") as f:
df.to_csv(f, index=False, sep="\t")
df["timestamp"] = df["timestamp"].apply(datetime.utcfromtimestamp)
df.set_index("timestamp")[["acc", "rec", "avg. gain"]].plot()
plt.gcf().suptitle(event.title+ " " + learner + " iter-{}".format(n_iter + 1))
plt.gcf().savefig(os.path.join(report_dir, "{}.png".format(event.fs_name())))
示例4: set_axis_0
def set_axis_0():
pylab.xlabel('time (days)')
pylab.gcf().subplots_adjust(top=1.0-0.13, bottom=0.2, right=1-0.02,
left=0.2)
a = list(pylab.axis())
na = [a[0], a[1], 0, a[3]*1.05]
pylab.axis(na)
示例5: plotStateSeq
def plotStateSeq(jobname, showELBOInTitle=1, **kwargs):
global dataName, StateColorMap
if 'cmap' not in kwargs:
kwargs['cmap'] = StateColorMap
axes, zBySeq = bnpy.viz.SequenceViz.plotSingleJob(dataName, jobname,
showELBOInTitle=showELBOInTitle, **kwargs)
pylab.gcf().set_size_inches(ZW, ZH);
return axes
示例6: plot_sun_image
def plot_sun_image(img, filename, wavelength=193, title = ''):
#cmap = plt.get_cmap('sdoaia{}'.format(wavelength))
cmap = plt.get_cmap('sohoeit195')
plt.title(title)
cax = plt.imshow(img,cmap=cmap,origin='lower',vmin=0, vmax=3000)#,vmin=vmin, vmax=vmax)
plt.gcf().colorbar(cax)
plt.savefig(filename)
plt.close("all")
示例7: XGB_native
def XGB_native(train,test,features,features_non_numeric):
depth = 13
eta = 0.01
ntrees = 8000
mcw = 3
params = {"objective": "reg:linear",
"booster": "gbtree",
"eta": eta,
"max_depth": depth,
"min_child_weight": mcw,
"subsample": 0.9,
"colsample_bytree": 0.7,
"silent": 1
}
print "Running with params: " + str(params)
print "Running with ntrees: " + str(ntrees)
print "Running with features: " + str(features)
# Train model with local split
tsize = 0.05
X_train, X_test = cross_validation.train_test_split(train, test_size=tsize)
dtrain = xgb.DMatrix(X_train[features], np.log(X_train[goal] + 1))
dvalid = xgb.DMatrix(X_test[features], np.log(X_test[goal] + 1))
watchlist = [(dvalid, 'eval'), (dtrain, 'train')]
gbm = xgb.train(params, dtrain, ntrees, evals=watchlist, early_stopping_rounds=100, feval=rmspe_xg, verbose_eval=True)
train_probs = gbm.predict(xgb.DMatrix(X_test[features]))
indices = train_probs < 0
train_probs[indices] = 0
error = rmspe(np.exp(train_probs) - 1, X_test[goal].values)
print error
# Predict and Export
test_probs = gbm.predict(xgb.DMatrix(test[features]))
indices = test_probs < 0
test_probs[indices] = 0
submission = pd.DataFrame({myid: test[myid], goal: np.exp(test_probs) - 1})
if not os.path.exists('result/'):
os.makedirs('result/')
submission.to_csv("./result/dat-xgb_d%s_eta%s_ntree%s_mcw%s_tsize%s.csv" % (str(depth),str(eta),str(ntrees),str(mcw),str(tsize)) , index=False)
# Feature importance
if plot:
outfile = open('xgb.fmap', 'w')
i = 0
for feat in features:
outfile.write('{0}\t{1}\tq\n'.format(i, feat))
i = i + 1
outfile.close()
importance = gbm.get_fscore(fmap='xgb.fmap')
importance = sorted(importance.items(), key=operator.itemgetter(1))
df = pd.DataFrame(importance, columns=['feature', 'fscore'])
df['fscore'] = df['fscore'] / df['fscore'].sum()
# Plotitup
plt.figure()
df.plot()
df.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(25, 15))
plt.title('XGBoost Feature Importance')
plt.xlabel('relative importance')
plt.gcf().savefig('Feature_Importance_xgb_d%s_eta%s_ntree%s_mcw%s_tsize%s.png' % (str(depth),str(eta),str(ntrees),str(mcw),str(tsize)))
示例8: plot_series
def plot_series(x, y_array, labels):
for y_arr, label in zip(y_array, labels):
plt.plot(x, y_arr, label=label)
plt.xlabel('Datetime')
plt.ylabel('Demand')
plt.title('Models of demand using trends and ARMA')
plt.gcf().set_size_inches(26,20)
plt.legend()
plt.show()
示例9: plotK
def plotK(JDict, xscale='linear', n='', **kwargs):
paths = JDict.values()
names = JDict.keys()
bnpy.viz.PlotTrace.plotJobs(MakePaths(paths,n), names, MakeStyles(names),
yvar='K', tickfontsize=tickfontsize,
density=1, **kwargs)
set_xscale(xscale)
pylab.ylim(Klims); pylab.yticks(Kticks);
pylab.gca().yaxis.grid() # horizontal lines
pylab.gcf().set_size_inches(W, H);
示例10: plotHammingDistVsELBO
def plotHammingDistVsELBO(JDict, n='', **kwargs):
names, paths = filterJDictForRunsWithELBO(JDict)
bnpy.viz.PlotTrace.plotJobs(MakePaths(paths, n), names, MakeStyles(names),
yvar='hamming-distance',
xvar='evidence',
tickfontsize=tickfontsize,
density=1, **kwargs)
pylab.ylim(Hlims);
pylab.yticks(Hticks);
pylab.gcf().set_size_inches(W, H);
示例11: draw
def draw(x, y, title='K value for kNN'):
plt.plot(x, y, label='k value')
plt.title(title)
plt.xlabel('k')
plt.ylabel('Score')
plt.grid(True)
plt.legend(loc='best', framealpha=0.5, prop={'size':'small'})
plt.tight_layout(pad=1)
plt.gcf().set_size_inches(8,4)
plt.show()
示例12: plotELBO
def plotELBO(JDict, xscale='linear', n='', **kwargs):
names, paths = filterJDictForRunsWithELBO(JDict)
bnpy.viz.PlotTrace.plotJobs(MakePaths(paths,n), names, MakeStyles(names),
yvar='evidence', tickfontsize=tickfontsize,
density=1, **kwargs)
set_xscale(xscale)
if ELBOlims is not None:
pylab.ylim(ELBOlims);
if ELBOticks is not None:
pylab.yticks(ELBOticks);
pylab.gca().yaxis.grid() # horizontal lines
pylab.gcf().set_size_inches(W, H);
示例13: matplotlib_make_figure
def matplotlib_make_figure(figsize=(10,7), style='seaborn-dark'):
try:
plt.style.use(style)
except ValueError:
warning(" matplotlib style %s not found." % style)
pass
fig=plt.figure('scatter3d', figsize)
plt.gcf().set_tight_layout(True)
ax=fig.add_subplot(111,projection='3d')
return fig, ax
示例14: plotStateSeq
def plotStateSeq(jobname, showELBOInTitle=1, xticks=None, **kwargs):
global dataName, StateColorMap
if 'cmap' not in kwargs:
kwargs['cmap'] = StateColorMap
axes, zBySeq = bnpy.viz.SequenceViz.plotSingleJob(dataName, jobname,
showELBOInTitle=showELBOInTitle, **kwargs)
pylab.subplots_adjust(top=0.85, bottom=0.1);
axes[-1].tick_params(axis='both', which='major', labelsize=20)
if xticks is not None:
axes[-1].set_xticks(xticks);
pylab.gcf().set_size_inches(ZW, ZH);
pylab.draw();
return axes
示例15: plot_episode
def plot_episode(args):
"""Plot an episode plucked from the large h5 database"""
print "plot_episode"
# load the data file
tblfilename = "bf_optimize_mavlink.h5"
h5file = tb.open_file(tblfilename, mode = "a")
# get the table handle
table = h5file.root.v2.evaluations
# selected episode
episode_row = table.read_coordinates([int(args.epinum)])
# compare episodes
episode_row_1 = table.read_coordinates([2, 3, 22, 46]) # bad episodes
print "row_1", episode_row_1.shape
# episode_row = table.read_coordinates([3, 87])
episode_target = episode_row["alt_target"]
episode_target_1 = [row["alt_target"] for row in episode_row_1]
print "episode_target_1.shape", episode_target_1
episode_timeseries = episode_row["timeseries"][0]
episode_timeseries_1 = [row["timeseries"] for row in episode_row_1]
print "row", episode_timeseries.shape
print "row_1", episode_timeseries_1
sl_start = 0
sl_end = 2500
sl_len = sl_end - sl_start
sl = slice(sl_start, sl_end)
pl.plot(episode_timeseries[sl,1], "k-", label="alt", lw=2.)
print np.array(episode_timeseries_1)[:,:,1]
pl.plot(np.array(episode_timeseries_1)[:,:,1].T, "k-", alpha=0.2)
# alt_hold = episode_timeseries[:,0] > 4
alt_hold_act = np.where(episode_timeseries[sl,0] == 11)
print "alt_hold_act", alt_hold_act[0].shape, sl_len
alt_hold_act_min = np.min(alt_hold_act)
alt_hold_act_max = np.max(alt_hold_act)
print "min, max", alt_hold_act_min, alt_hold_act_max, alt_hold_act_min/float(sl_len), alt_hold_act_max/float(sl_len),
# pl.plot(episode_timeseries[sl,0] * 10, label="mode")
pl.axhspan(-100., 1000,
alt_hold_act_min/float(sl_len),
alt_hold_act_max/float(sl_len),
facecolor='0.5', alpha=0.25)
pl.axhline(episode_target, label="target")
pl.xlim((0, sl_len))
pl.xlabel("Time steps [1/50 s]")
pl.ylabel("Alt [cm]")
pl.legend()
if args.plotsave:
pl.gcf().set_size_inches((10, 3))
pl.gcf().savefig("%s.pdf" % (sys.argv[0][:-3]), dpi=300, bbox_inches="tight")
pl.show()