本文整理汇总了Python中matplotlib.interactive函数的典型用法代码示例。如果您正苦于以下问题:Python interactive函数的具体用法?Python interactive怎么用?Python interactive使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了interactive函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_script
def run_script(args):
matplotlib.interactive(False)
Rprop0 = args.Rpp0
Rprop1 = args.Rpp1
theta = np.arange(args.theta[0], args.theta[1], args.theta[2])
warray_amp = create_theta_spike(args.pad,
Rprop0, Rprop1, theta,
args.f, args.points, args.reflectivity_method)
fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.gray()
aspect = float(warray_amp.shape[1]) / warray_amp.shape[0]
ax1.imshow(warray_amp, aspect=aspect, cmap=args.colour)
plt.title(args.title % locals())
plt.ylabel('time (ms)')
plt.xlabel('trace')
fig_path = tempfile.mktemp('.jpeg')
plt.savefig(fig_path)
with open(fig_path, 'rb') as fd:
data = fd.read()
unlink(fig_path)
return data
示例2: dump_match_img
def dump_match_img(qres, ibs, aid, qreq_=None, fnum=None, *args, **kwargs):
import plottool as pt
import matplotlib as mpl
# Pop save kwargs from kwargs
save_keys = ['dpi', 'figsize', 'saveax', 'fpath', 'fpath_strict', 'verbose']
save_vals = ut.dict_take_pop(kwargs, save_keys, None)
savekw = dict(zip(save_keys, save_vals))
fpath = savekw.pop('fpath')
if fpath is None and 'fpath_strict' not in savekw:
savekw['usetitle'] = True
was_interactive = mpl.is_interactive()
if was_interactive:
mpl.interactive(False)
# Make new figure
if fnum is None:
fnum = pt.next_fnum()
#fig = pt.figure(fnum=fnum, doclf=True, docla=True)
fig = pt.plt.figure(fnum)
fig.clf()
# Draw Matches
ax, xywh1, xywh2 = qres.show_matches(ibs, aid, colorbar_=False, qreq_=qreq_, fnum=fnum, **kwargs)
if not kwargs.get('notitle', False):
pt.set_figtitle(qres.make_smaller_title())
# Save Figure
# Setting fig=fig might make the dpi and figsize code not work
img_fpath = pt.save_figure(fpath=fpath, fig=fig, **savekw)
if was_interactive:
mpl.interactive(was_interactive)
pt.plt.close(fig) # Ensure that this figure will not pop up
#if False:
# ut.startfile(img_fpath)
return img_fpath
示例3: test_chinese_restaurant_process
def test_chinese_restaurant_process(self):
print sys.path
from matplotlib import pyplot
import matplotlib
from scipy import stats
alpha = 20
test_size = 1000
tests = 1000
data = [0]
for j in range(0, tests):
cr = ChineseRestaurant(alpha, Numbers())
for i in range(0, test_size):
new_sample = cr.draw()
if new_sample >= len(data):
data.append(0)
data[new_sample] += 1
assert cr.heap[1] == test_size
pyplot.switch_backend('Qt5Agg')
#data=sorted(data, reverse=True)
print len(data)
actual_plot, = pyplot.plot(range(1,len(data)), data[1:], label='actual avg')
expected = [0]
remain = test_size * tests
for i in range(1, len(data)):
break_ = stats.beta.mean(1.0, float(alpha)) * remain
expected.append(break_)
remain -= break_
#print est
expected_plot, = pyplot.plot(range(1,len(data)), expected[1:], 'r', linewidth=1, label='expected')
matplotlib.interactive(True)
pyplot.ylabel("People at Table")
pyplot.xlabel("Table Number")
pyplot.title("Chinese Restaurant Process Unit Test")
pyplot.legend()
pyplot.show(block=True)
示例4: run_script
def run_script(args):
matplotlib.interactive(False)
"""if args.transparent == 'False' or args.transparent == 'No':
transparent = False
else:
transparent = True"""
args.ntraces = 300
args.pad = 150
args.reflectivity_method = zoeppritz
args.title = "Channel - angle gather (AVA)"
args.theta = (0, 50, 0.5)
args.wavelet = ricker
args.wiggle_skips = 10
args.aspect_ratio = 1
args.thickness = 50
args.margin = 1
args.slice = "angle"
transparent = False
# This is a hack to conserve colors
l1 = (150, 110, 110)
l2 = (110, 150, 110)
l3 = (110, 110, 150)
layers = [l1, l2]
colourmap = {rgb(150, 110, 110): args.Rock0, rgb(110, 150, 110): args.Rock1}
if not isinstance(args.Rock2, str):
colourmap[rgb(110, 110, 150)] = args.Rock2
layers.append(l3)
# Get the physical model (an array of rocks)
model = mb.channel(pad=args.pad, thickness=args.thickness, traces=args.ntraces, layers=layers)
return modelr_plot(model, colourmap, args)
示例5: __init__
def __init__( self, path='', codes=None, difficulties=None, df=None, user=None, place_asked=None,
lower_bound = 50,upper_bound = 236, session_numbers=True):
"""Sets matplotlib to be non-interactive. All other defaults are same as in Drawable.
"""
Drawable.__init__(self, path, codes,difficulties, df,user,place_asked,lower_bound,upper_bound,session_numbers)
interactive(False) #disable matplotlib interactivity
示例6: test_matplotlib
def test_matplotlib():
import matplotlib
import matplotlib.colors
# Override system defaults before importing pylab
matplotlib.use('TkAgg')
#matplotlib.rc('text', usetex=True)
matplotlib.interactive(True)
from matplotlib.font_manager import fontManager, FontProperties
import pylab
print "matplotlib is installed in", os.path.dirname(matplotlib.__file__)
print "matplotlib version", matplotlib.__version__
print "matplotlib.rcParams:"
pprint.pprint(matplotlib.rcParams)
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
pylab.plot(x, y, 'bo-', linewidth=2.0)
pylab.title("Hello Matplotlib!")
pylab.draw()
#pylab.show() # requires manual quit of plot window
time.sleep(0.5)
示例7: activate_matplotlib
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
if backend.startswith('module://'):
# Work around bug in matplotlib: matplotlib.use converts the
# backend_id to lowercase even if a module name is specified!
matplotlib.rcParams['backend'] = backend
else:
matplotlib.use(backend)
matplotlib.interactive(True)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pylab as pylab
# XXX For now leave this commented out, but depending on discussions with
# mpl-dev, we may be able to allow interactive switching...
#import matplotlib.pyplot
#matplotlib.pyplot.switch_backend(backend)
pylab.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
示例8: plot_sphere_func
def plot_sphere_func(f, grid='Clenshaw-Curtis', theta=None, phi=None, colormap='jet', fignum=0):
# Note: all grids except Clenshaw-Curtis have holes at the poles
import matplotlib
matplotlib.use('WxAgg')
matplotlib.interactive(True)
from mayavi import mlab
if grid == 'Driscoll-Healy':
b = f.shape[0] / 2
elif grid == 'Clenshaw-Curtis':
b = (f.shape[0] - 2) / 2
elif grid == 'SOFT':
b = f.shape[0] / 2
elif grid == 'Gauss-Legendre':
b = (f.shape[0] - 2) / 2
if theta is None or phi is None:
theta, phi = meshgrid(b=b, convention=grid)
phi = np.r_[phi, phi[0, :][None, :]]
theta = np.r_[theta, theta[0, :][None, :]]
f = np.r_[f, f[0, :][None, :]]
x = np.sin(theta) * np.cos(phi)
y = np.sin(theta) * np.sin(phi)
z = np.cos(theta)
mlab.figure(fignum, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 400))
mlab.clf()
mlab.mesh(x, y, z, scalars=f, colormap=colormap)
# mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
mlab.show()
示例9: run_script
def run_script(args):
matplotlib.interactive(False)
array_amp = np.zeros([args.time])
array_time = np.arange(args.time)
Rpp = args.reflectivity_model(args.Rpp0, args.Rpp1, args.theta1)
array_amp[args.time // 2] = Rpp
r = ricker_alg(1,128, args.f)
warray_amp = np.convolve(array_amp, r, mode='same')
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(warray_amp, array_time)
plt.title(args.title % locals())
plt.ylabel('time (ms)')
plt.xlabel('amplitude')
ax = plt.gca()
ax.set_ylim(ax.get_ylim()[::-1])
ax.set_xlim(args.xlim)
return return_current_figure()
示例10: visualize
def visualize(M_pri, C_pri, E, lps, nug):
"""
Shows the EP algorithm's approximate posterior superimposed on the true posterior.
Requires a fitted EP object as an input.
"""
import matplotlib
matplotlib.interactive(True)
k=0
x = linspace(E.M_pri[k] - 4.*np.sqrt(E.C_pri[k,k]), E.M_pri[k] + 4.*np.sqrt(E.C_pri[k,k]), 500)
pri_real = norm_dens(x, M_pri[k], C_pri[k,k])
norms = np.random.normal(size=10000)*np.sqrt(nug[k])
def this_lp(x, k=k, norms=norms):
return np.array([pm.flib.logsum(lps[k](xi + norms)) - np.log((len(norms))) for xi in x])
like_real = this_lp(x)
where_real_notnan = np.where(1-np.isnan(like_real))
x_realplot = x[where_real_notnan]
like_real = like_real[where_real_notnan]
like_real = np.exp(like_real - like_real.max())
like_approx = norm_dens(x, E.mu[k], E.V[k] + nug[k])
post_real = like_real * pri_real[where_real_notnan]
smoove_mat = np.asarray(pm.gp.cov_funs.gaussian.euclidean(x_realplot,x_realplot,amp=1,scale=.1))
smoove_mat /= np.sum(smoove_mat, axis=0)
# like_real = np.dot(smoove_mat, like_real)
# post_real = np.dot(smoove_mat, post_real)
post_real /= post_real.max()
post_approx = norm_dens(x, E.M[k], E.C[k,k])
post_approx2 = pri_real * like_approx
post_approx2 /= post_approx2.sum()
post_approx /= post_approx.sum()
post_real /= post_real.sum()
like_real *= post_real.max()/like_real.max()
pri_real *= post_real.max()
like_approx *= post_approx.max() / like_approx.max()
# figure(1, figsize=(9,6))
clf()
plot(x, pri_real, 'g:', linewidth=2, label='Prior')
plot(x_realplot, like_real, 'b-.', linewidth=2, label='Likelihood')
plot(x, like_approx, 'r-.', linewidth=2, label='Approx. likelihood')
plot(x_realplot, post_real, 'b-', linewidth=2, label='Posterior')
plot(x, post_approx, 'r-', linewidth=2, label='Approx. posterior')
plot(x, post_approx2, 'g-', linewidth=2, label='Approx. posterior meth 2')
legend(loc=0).legendPatch.set_alpha(0.)
xlabel(r'$f(x)$')
axis('tight')
m1r = sum(x[where_real_notnan]*post_real)/sum(post_real)
m1em2 = sum(x*post_approx2)/sum(post_approx2)
m1em = sum(x*post_approx)/sum(post_approx)
m2r = sum(x[where_real_notnan]**2*post_real)/sum(post_real)
m2em = sum(x**2*post_approx)/sum(post_approx)
m2em2 = sum(x**2*post_approx2)/sum(post_approx2)
print 'Posterior means: real: %s, EM: %s EM2: %s' % (m1r, m1em, m1em2)
print 'Posterior variances: real: %s, EM: %s EM2: %s' % (m2r-m1r**2, m2em-m1em**2, m2em2-m1em2**2)
示例11: pre_interact
def pre_interact(self):
"""Initialize matplotlib before user interaction begins"""
push = self.shell.push
# Code to execute in user's namespace
lines = ["import matplotlib",
"matplotlib.use('GTKAgg')",
"matplotlib.interactive(1)",
"import matplotlib.pylab as pylab",
"from matplotlib.pylab import *\n"]
map(push,lines)
# Execute file if given.
if len(sys.argv)>1:
import matplotlib
matplotlib.interactive(0) # turn off interaction
fname = sys.argv[1]
try:
inFile = file(fname, 'r')
except IOError:
print('*** ERROR *** Could not read file <%s>' % fname)
else:
print('*** Executing file <%s>:' % fname)
for line in inFile:
if line.lstrip().find('show()')==0: continue
print('>>', line)
push(line)
inFile.close()
matplotlib.interactive(1) # turn on interaction
示例12: euclSpaceMapp
def euclSpaceMapp(gDirected,distMat,top100List,top100ListIdxs):
print('extract euclidean space mapping')
allCoordinates = euclideanCoords(gDirected,distMat)
print('Mapped nodes to euclidean space')
xpl=[x[0] for x in allCoordinates]
minXpl = min(xpl)
if minXpl < 0:
aminXpl = abs(minXpl)
xpl = np.array([x+aminXpl+1 for x in xpl])
ypl=[x[1] for x in allCoordinates]
minYpl = min(ypl)
if minYpl < 0:
aminYpl = abs(minYpl)
ypl = np.array([y+aminYpl+1 for y in ypl])
fig = pyplot.figure()
ax = pyplot.gca()
ax.scatter(xpl,ypl)
ax.set_ylim(min(ypl)-1,max(ypl)+1)
ax.set_xlim(min(xpl)-1,max(xpl)+1)
labels = top100List
for label, x, y in zip(labels, xpl[top100ListIdxs], ypl[top100ListIdxs]):
pyplot.annotate(label, xy = (x, y), xytext = (-10, 10),textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
interactive(True)
pyplot.show()
# pyplot.savefig('./images/'+str(year)+'_euclSpaceMapping_via_shortestPaths.jpg', bbox_inches='tight', format='jpg')
pyplot.savefig('./images/'+str(year)+'_euclSpaceMapping_via_distMatrix.jpg', bbox_inches='tight', format='jpg')
pyplot.close()
示例13: show
def show(self):
self.fig.canvas.mpl_connect('motion_notify_event', self.update)
#self.fig.canvas.mpl_connect('button_press_event', self.on_button_press)
self.fig.canvas.mpl_connect('axes_leave_event', self.on_leave_axes)
self.fig.canvas.mpl_connect('resize_event', self.on_resize)
matplotlib.interactive(False) # Need this or there is not sys.exit
pylab.show()
示例14: mpl_execfile
def mpl_execfile(fname,*where,**kw):
"""matplotlib-aware wrapper around safe_execfile.
Its interface is identical to that of the :func:`execfile` builtin.
This is ultimately a call to execfile(), but wrapped in safeties to
properly handle interactive rendering."""
import matplotlib
import matplotlib.pyplot as plt
#print '*** Matplotlib runner ***' # dbg
# turn off rendering until end of script
is_interactive = matplotlib.rcParams['interactive']
matplotlib.interactive(False)
safe_execfile(fname,*where,**kw)
matplotlib.interactive(is_interactive)
# make rendering call now, if the user tried to do it
if plt.draw_if_interactive.called:
plt.draw()
plt.draw_if_interactive.called = False
# re-draw everything that is stale
try:
da = plt.draw_all
except AttributeError:
pass
else:
da()
示例15: matplotlib_interactive
def matplotlib_interactive(interactive=False):
import matplotlib
if not interactive:
matplotlib.use("Agg") # allows running without X11 on compute nodes
matplotlib.interactive(interactive)
return interactive