我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用matplotlib.interactive()。
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib matplotlib.interactive(True) # Matplotlib had a bug where even switch_backend could not force # the rcParam to update. This needs to be set *before* the module # magic of switch_backend(). matplotlib.rcParams['backend'] = backend import matplotlib.pyplot matplotlib.pyplot.switch_backend(backend) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pyplot as plt plt.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. plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
def plotdata(obsmode,spectrum,val,odict,sdict, instr,fieldname,outdir,outname): isetting=P.isinteractive() P.ioff() P.clf() P.plot(obsmode,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('obsmode') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_obsmode.ps')) P.clf() P.plot(spectrum,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('spectrum') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_spectrum.ps')) matplotlib.interactive(isetting)
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib matplotlib.interactive(True) # Matplotlib had a bug where even switch_backend could not force # the rcParam to update. This needs to be set *before* the module # magic of switch_backend(). matplotlib.rcParams['backend'] = backend import matplotlib.pyplot matplotlib.pyplot.switch_backend(backend) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pylab as pylab 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)
def test(self): nr_observations = sum(self.histogram) observed_frequencies = [] expected_frequencies = [] frequencies_of = [] thresh = 10 for i in range(0, len(self.histogram)): observed = self.histogram[i] expected = stats.poisson.pmf(i, self.lambda_) * nr_observations if ( (observed >= thresh) and (expected >= thresh)): observed_frequencies.append(observed) expected_frequencies.append(expected) frequencies_of.append(i) results = stats.chisquare(observed_frequencies, expected_frequencies) print("expected: mean %f variance %f" % ( self.expected_mean(), self.expected_variance())) print("actual: mean %f variance %f" % ( self.mean(), self.variance())) print(len(expected_frequencies)) print(results) from matplotlib import pyplot import matplotlib pyplot.switch_backend('Qt5Agg') actual_plot, = pyplot.plot(frequencies_of, observed_frequencies, label='actual') expected_plot, = pyplot.plot(frequencies_of, expected_frequencies, '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) return results
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)
def toggle_interactivity(): global interactivity interactivity = not interactivity if interactivity is True: if '__IPYTHON__' in dir(builtins): import IPython shell = IPython.get_ipython() shell.magic('matplotlib') else: import matplotlib matplotlib.interactive(True)
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ 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.pylab as pylab #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 pylab.draw_if_interactive.called: pylab.draw() pylab.draw_if_interactive.called = False return mpl_execfile
def set_matplotlib_backend(backend=None, batch=None, silent=True): """Set Matplotlib backend :param str backend: backend to set :param bool batch: require backend to be non-interactive :param bool silent: do not raise exception if backend cannot be set :raises: RuntimeError """ # determine if batch mode is required display = get_env_var('display') run_batch = bool(batch) or display is None or not display.startswith(':') or not display[1].isdigit() if run_batch: matplotlib.interactive(False) # check if batch mode can be set if it is requested if not batch and batch is not None and run_batch: if not silent: raise RuntimeError('interactive Matplotlib mode requested, but no display found') log.warning('Matplotlib cannot be used interactively; no display found') # get Matplotlib backends curr_backend = matplotlib.get_backend().lower() ni_backends = [nib.lower() for nib in matplotlib.rcsetup.non_interactive_bk] # determine backend to be set if not backend: # try to use current backend backend = curr_backend if not run_batch or curr_backend in ni_backends else ni_backends[0] backend = str(backend).lower() # check if backend is compatible with mode if run_batch and backend not in ni_backends: if not silent: raise RuntimeError('non-interactive Matplotlib backend required, but "{}" requested'.format(str(backend))) log.warning('Set Matplotlib backend to "%s"; non-interactive backend required, but "%s" requested', ni_backends[0], backend) backend = ni_backends[0] # check if backend has to change if backend == curr_backend: return # check if backend can still be set if 'matplotlib.pyplot' in sys.modules: if not silent: raise RuntimeError('cannot set Matplotlib backend: pyplot module already loaded') return # set backend matplotlib.use(backend)
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ 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() return mpl_execfile