本文整理汇总了Python中matplotlib.pyplot.draw_if_interactive函数的典型用法代码示例。如果您正苦于以下问题:Python draw_if_interactive函数的具体用法?Python draw_if_interactive怎么用?Python draw_if_interactive使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了draw_if_interactive函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_figure
def _init_figure(self, **kwargs):
from matplotlib import pyplot
# add new attributes
self.colorbars = []
self._coloraxes = []
# create Figure
num = kwargs.pop('num', max(pyplot.get_fignums() or {0}) + 1)
self._parse_subplotpars(kwargs)
super(Plot, self).__init__(**kwargs)
self.number = num
# add interactivity (scraped from pyplot.figure())
backend_mod = get_backend_mod()
try:
manager = backend_mod.new_figure_manager_given_figure(num, self)
except AttributeError:
upstream_mod = importlib.import_module(
pyplot.new_figure_manager.__module__)
canvas = upstream_mod.FigureCanvasBase(self)
manager = upstream_mod.FigureManagerBase(canvas, 1)
manager._cidgcf = manager.canvas.mpl_connect(
'button_press_event',
lambda ev: _pylab_helpers.Gcf.set_active(manager))
_pylab_helpers.Gcf.set_active(manager)
pyplot.draw_if_interactive()
示例2: legend
def legend(*args, **kwargs):
"""
Overwrites the pylab legend function.
It adds another location identifier 'outer right'
which locates the legend on the right side of the plot
The args and kwargs are forwarded to the pylab legend function
"""
if kwargs.has_key('loc'):
loc = kwargs['loc']
if (loc == 'outer'):
global new
kwargs.pop('loc')
leg = plt.legend(loc=(0,0), *args, **kwargs)
frame = leg.get_frame()
currentAxes = plt.gca()
barray = currentAxes.get_position().get_points()
currentAxesPos = [barray[0][0], barray[0][1], barray[1][0], barray[1][1]]
currentAxes.set_position([currentAxesPos[0]-0.02, currentAxesPos[1], currentAxesPos[2] - 0.2, currentAxesPos[3]-currentAxesPos[1]])
version = mpl.__version__.split(".")
#if map(int, version) < [0, 98]:
# leg._loc = (1 + leg.axespad, 0.0)
#else:
leg._loc = (1.03, -0.05) # + leg.borderaxespad, 0.0)
plt.draw_if_interactive()
return leg
return plt.legend(*args, **kwargs)
示例3: csplot
def csplot(series, *args, **kwargs):
"""
Plots the series to the current :class:`ClimateSeriesPlot` subplot.
If the current plot is not a :class:`ClimateSeriesPlot`,
a new :class:`ClimateFigure` is created.
"""
# allow callers to override the hold state by passing hold=True|False
b = pyplot.ishold()
h = kwargs.pop('hold', None)
if h is not None:
pyplot.hold(h)
# Get the current figure, or create one
figManager = _pylab_helpers.Gcf.get_active()
if figManager is not None :
fig = figManager.canvas.figure
if not isinstance(fig, ClimateFigure):
fig = csfigure(series=series)
else:
fig = csfigure(series=series)
# Get the current axe, or create one
sub = fig._axstack()
if sub is None:
sub = fig.add_csplot(111, series=series, **kwargs)
try:
ret = sub.csplot(series, *args, **kwargs)
pyplot.draw_if_interactive()
except:
pyplot.hold(b)
raise
pyplot.hold(b)
return ret
示例4: add_contours
def add_contours(self, img, filled=False, **kwargs):
""" Contour a 3D map in all the views.
Parameters
-----------
img: Niimg-like object
See http://nilearn.github.io/manipulating_visualizing/manipulating_images.html#niimg.
Provides image to plot.
filled: boolean, optional
If filled=True, contours are displayed with color fillings.
kwargs:
Extra keyword arguments are passed to contour, see the
documentation of pylab.contour
Useful, arguments are typical "levels", which is a
list of values to use for plotting a contour, and
"colors", which is one color or a list of colors for
these contours.
"""
self._map_show(img, type='contour', **kwargs)
if filled:
colors = kwargs['colors']
levels = kwargs['levels']
# contour fillings levels should be given as (lower, upper).
levels.append(np.inf)
alpha = kwargs['alpha']
self._map_show(img, type='contourf', levels=levels, alpha=alpha,
colors=colors[:3])
plt.draw_if_interactive()
示例5: add_overlay
def add_overlay(self, img, threshold=1e-6, colorbar=False, **kwargs):
""" Plot a 3D map in all the views.
Parameters
-----------
img: Niimg-like object
See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg.
If it is a masked array, only the non-masked part will be
plotted.
threshold : a number, None
If None is given, the maps are not thresholded.
If a number is given, it is used to threshold the maps:
values below the threshold (in absolute value) are
plotted as transparent.
colorbar: boolean, optional
If True, display a colorbar on the right of the plots.
kwargs:
Extra keyword arguments are passed to imshow.
"""
if colorbar and self._colorbar:
raise ValueError("This figure already has an overlay with a " "colorbar.")
else:
self._colorbar = colorbar
img = _utils.check_niimg_3d(img)
# Make sure that add_overlay shows consistent default behavior
# with plot_stat_map
kwargs.setdefault("interpolation", "nearest")
ims = self._map_show(img, type="imshow", threshold=threshold, **kwargs)
if colorbar:
self._colorbar_show(ims[0], threshold)
plt.draw_if_interactive()
示例6: add_edges
def add_edges(self, img, color='r'):
""" Plot the edges of a 3D map in all the views.
Parameters
-----------
map: 3D ndarray
The 3D map to be plotted. If it is a masked array, only
the non-masked part will be plotted.
affine: 4x4 ndarray
The affine matrix giving the transformation from voxel
indices to world space.
color: matplotlib color: string or (r, g, b) value
The color used to display the edge map
"""
img = reorder_img(img)
data = img.get_data()
affine = img.get_affine()
single_color_cmap = colors.ListedColormap([color])
data_bounds = get_bounds(data.shape, img.get_affine())
# For each ax, cut the data and plot it
for display_ax in self.axes.values():
try:
data_2d = display_ax.transform_to_2d(data, affine)
edge_mask = _edge_map(data_2d)
except IndexError:
# We are cutting outside the indices of the data
continue
display_ax.draw_2d(edge_mask, data_bounds, data_bounds,
type='imshow', cmap=single_color_cmap)
plt.draw_if_interactive()
示例7: plot
def plot(self,axes=None,xlabel=True,ylabel=True,frameon=True,xticks=None,
yticks=None,**kwargs):
if axes==None:
axes = gca()
blend = kwargs.pop('blend',1)
maxspikes = kwargs.pop('maxspikes',None)
extents = [self.starttime_float,self.endtime_float,
self.n_trials+.5,.5]
im = axes.imshow(repeat(self.data,blend,axis=0),
aspect='auto', cmap=cm.bone_r,
interpolation='bilinear',extent=extents,
origin='upper')
axes.yaxis.set_major_locator(MultipleLocator(1))
if maxspikes is not None:
im.set_clim([0,maxspikes])
if xlabel:
axes.set_xlabel('Time [s]')
if ylabel:
axes.set_ylabel('Trial')
axes.set_frame_on(frameon)
if xticks is not None:
axes.set_xticks(xticks)
if yticks is not None:
axes.set_yticks(yticks)
draw_if_interactive()
return axes
示例8: correlationPlot
def correlationPlot(x,y,name=None,xlabel='PAR0',ylabel='PAR1',order=1,NptsStat=21,NptsPlotfit=500,usemad=True):
p = np.polyfit(x,y,order)
statedges = np.linspace(np.min(x),np.max(x),NptsStat)
statbins = np.digitize(x,statedges)
stato = np.zeros(NptsStat-1)
for n in xrange(NptsStat-1):
if usemad:
stato[n]= toolsDistrAndHist.mad(y[n+1==statbins])
else:
stato[n]= np.std(y[n+1==statbins])
statx = toolsDistrAndHist.histVecCenter(statedges)
xf = np.linspace(np.min(x),np.max(x),NptsPlotfit)
yf = np.polyval(p,xf)
fig,axs = subplots(3,1,sharex=True,figname=name,figsize=(14,6),hspace=0)
axs[0].plot(x,y,'.k',ms=2)
axs[0].plot(xf,yf,'r-',lw=2)
axs[0].errorbar(statx,np.polyval(p,statx),yerr=stato,fmt='r.',lw=2,capthick=2)
axs[0].set_ylabel(ylabel)
axs[1].plot(x,y-np.polyval(p,x),'.k',ms=2)
axs[1].plot(xf,np.zeros_like(xf),'r',lw=2)
axs[1].errorbar(statx,np.zeros_like(statx),yerr=stato,fmt='r.',lw=2,capthick=2)
axs[1].set_ylabel('%s - $<$%s$>$'%(ylabel,ylabel))
axs[2].step(statx,stato/np.polyval(np.polyder(p),statx),where='mid',color='k',lw=2)
axs[2].axhline(0,color='r')
axs[2].set_ylabel('$\sigma_{%s} / \\frac{d<%s>}{d%s}$'%(ylabel,ylabel,xlabel))
axs[2].set_xlabel(xlabel)
plt.draw_if_interactive()
return p
示例9: plot_forecast
def plot_forecast(self, steps=1, figsize=(10, 10)):
"""
Plot h-step ahead forecasts against actual realizations of time
series. Note that forecasts are lined up with their respective
realizations.
Parameters
----------
steps :
"""
fig, axes = plt.subplots(figsize=figsize, nrows=self.neqs,
sharex=True)
forc = self.forecast(steps=steps)
dates = forc.index
y_overlay = self.y.reindex(dates)
for i, col in enumerate(forc.columns):
ax = axes[i]
y_ts = y_overlay[col]
forc_ts = forc[col]
y_handle = ax.plot(dates, y_ts.values, 'k.', ms=2)
forc_handle = ax.plot(dates, forc_ts.values, 'k-')
fig.legend((y_handle, forc_handle), ('Y', 'Forecast'))
fig.autofmt_xdate()
fig.suptitle('Dynamic %d-step forecast' % steps)
# pretty things up a bit
plotting.adjust_subplots(bottom=0.15, left=0.10)
plt.draw_if_interactive()
示例10: Fct_RangeY
def Fct_RangeY(self,y=None,f=1.0):
'''
yrange=RangeY(y=None,f=1.0)
If y is given then it is treated as a range with a min and
max value. The y-limits of the active plot are set to this range multiplied
by f. If f is a list of two values then f[0] is used for the lower limit and
f[1] is used for the upper limit.
The function returns the y-range of the active plot.
'''
ax=plt.gca()
ch=False
f1=f2=f
if not isFloat(f):
f1=f[0]
f2=f[1]
if not (y is None):
yi=min(y)
ya=max(y)
ym=(ya+yi)/2
yi=f1*(yi-ym)+ym
ya=f2*(ya-ym)+ym
ax=plt.gca()
ax.set_ylim(yi,ya)
ch=True
if ch:
plt.draw_if_interactive()
return ax.get_ylim()
示例11: Fct_RangeX
def Fct_RangeX(self,x=None,f=1.0):
'''
xrange=RangeX(x=None,f=1.0)
If x is given then it is treated as a range with a min and
max value. The x-limits of the active plot are set to this range multiplied
by f. If f is a list of two values then f[0] is used for the lower limit and
f[1] is used for the upper limit.
The function returns the x-range of the active plot.
'''
ax=plt.gca()
ch=False
f1=f2=f
if not isFloat(f):
f1=f[0]
f2=f[1]
if not (x is None):
xi=min(x)
xa=max(x)
xm=(xa+xi)/2
xi=f1*(xi-xm)+xm
xa=f2*(xa-xm)+xm
ax.set_xlim(xi,xa)
ch=True
if ch:
plt.draw_if_interactive()
return ax.get_xlim()
示例12: Fct_Range
def Fct_Range(self,x=None,y=None,f=1.0):
'''
xrange,yrange=Range(x=None,y=None,f=1.0)
If x or y are given then they are treated as a range with a min and
max value. The limits of the active plot are set to these ranges multiplied
by f. If f is a list of two values then f[0] is used for the lower limit and
f[1] is used for the upper limit.
The function returns the x- and y-range of the active plot.
'''
ax=plt.gca()
ch=False
f1=f2=f
if not isFloat(f):
f1=f[0]
f2=f[1]
if not (x is None):
xi=min(x)
xa=max(x)
xm=(xa+xi)/2
xi=1.*f1*(xi-xm)+xm
xa=1.*f2*(xa-xm)+xm
ax.set_xlim(xi,xa)
ch=True
if not (y is None):
yi=min(y)
ya=max(y)
ym=(ya+yi)/2
yi=f1*(yi-ym)+ym
ya=f2*(ya-ym)+ym
ax.set_ylim(yi,ya)
ch=True
if ch:
plt.draw_if_interactive()
return (ax.get_xlim(),ax.get_ylim())
示例13: _draw_span
def _draw_span(self):
if not (self._ax and self.op.low and self.op.high):
return
if self._low_line and self._low_line in self._ax.lines:
self._low_line.remove()
if self._high_line and self._high_line in self._ax.lines:
self._high_line.remove()
if self._hline and self._hline in self._ax.lines:
self._hline.remove()
self._low_line = plt.axvline(self.op.low, linewidth=3, color='blue')
self._high_line = plt.axvline(self.op.high, linewidth=3, color='blue')
ymin, ymax = plt.ylim()
y = (ymin + ymax) / 2.0
self._hline = plt.plot([self.op.low, self.op.high],
[y, y],
color='blue',
linewidth = 2)[0]
plt.draw_if_interactive()
示例14: onscroll
def onscroll(event):
if event.button == "up":
for origline, legline in lined2.items():
toggle_visibility(origline, legline, True)
elif event.button == "down":
for origline, legline in lined2.items():
toggle_visibility(origline, legline, False)
pyplot.draw_if_interactive()
示例15: drawFigure
def drawFigure(self, title=None, **kw):
"""Draw the figure.
Extra arguments are forwarded to self.makeFigure()"""
import matplotlib.pyplot as plt
fig = self.makeFigure(**kw)
if title is not None:
fig.suptitle(title)
plt.draw_if_interactive()