我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用matplotlib.get_backend()。
def _set_canvas(self): self.interactivity = get_interactivity() if self.interactivity: backend = str(matplotlib.get_backend()) else: backend = 'agg' for key in backend_dict.keys(): if key == backend: mod = __import__('matplotlib.backends', globals(), locals(), [backend_dict[key][0]], 0) submod = getattr(mod, backend_dict[key][0]) FigureCanvas = getattr(submod, backend_dict[key][1]) if len(backend_dict[key]) > 2: FigureManager = getattr(submod, backend_dict[key][2]) return [FigureCanvas, FigureManager] else: return [FigureCanvas]
def plot(self): """ Plots result """ mng = plt.get_current_fig_manager() # Open directly in full window if mpl.get_backend() == 'Qt4Agg': # 'Qt4' backend mng.window.showMaximized() elif mpl.get_backend() == 'WxAgg': # 'WxAgg' backend mng.frame.Maximize(True) elif mpl.get_backend() == 'TKAgg': # 'TKAgg' backend mng.frame.Maximize(True) plt.show(all) # Show all plots
def phase1_plot_setup(): # Set up a 1x2 plot f, (ax1, ax2) = plt.subplots(1,2) f.suptitle('Phase 1 - Rise Times', fontsize=18, fontweight='bold') # Choose a colour palette and font size/style colours = sns.color_palette("muted") sns.set_context('poster') # Maximise the plotting window plot_backend = matplotlib.get_backend() mng = plt.get_current_fig_manager() if plot_backend == 'TkAgg': mng.resize(*mng.window.maxsize()) elif plot_backend == 'wxAgg': mng.frame.Maximize(True) elif plot_backend == 'Qt4Agg': mng.window.showMaximized() return f, ax1, ax2
def phase2_plot_setup(): # Set up a 1x1 plot f, ax1 = plt.subplots(1,1) f.suptitle('Phase 2 - Line Width', fontsize=18, fontweight='bold') # Choose a colour palette and font size/style colours = sns.color_palette("muted") sns.set_context('poster') # Maximise the plotting window plot_backend = matplotlib.get_backend() mng = plt.get_current_fig_manager() if plot_backend == 'TkAgg': mng.resize(*mng.window.maxsize()) elif plot_backend == 'wxAgg': mng.frame.Maximize(True) elif plot_backend == 'Qt4Agg': mng.window.showMaximized() return f, ax1
def move_figure(f, x, y): """Move figure's upper left corner to pixel (x, y)""" backend = matplotlib.get_backend() if backend == 'TkAgg': f.canvas.manager.window.wm_geometry("+%d+%d" % (x, y)) elif backend == 'WXAgg': f.canvas.manager.window.SetPosition((x, y)) else: # This works for QT and GTK # You can also use window.setGeometry f.canvas.manager.window.move(x, y)
def _setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. try: locale.setlocale(locale.LC_ALL, str('en_US.UTF-8')) except locale.Error: try: locale.setlocale(locale.LC_ALL, str('English_United States.1252')) except locale.Error: warnings.warn( "Could not set locale to English/United States. " "Some date-related tests may fail") plt.switch_backend('Agg') # use Agg backend for these test if mpl.get_backend().lower() != "agg": msg = ("Using a wrong matplotlib backend ({0}), " "which will not produce proper images") raise Exception(msg.format(mpl.get_backend())) # These settings *must* be hardcoded for running the comparison # tests mpl.rcdefaults() # Start with all defaults mpl.rcParams['text.hinting'] = True mpl.rcParams['text.antialiased'] = True mpl.rcParams['text.hinting_factor'] = 8 # make sure we don't carry over bad plots from former tests msg = ("no of open figs: {} -> find the last test with ' " "python tests.py -v' and add a '@cleanup' decorator.") assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
def __plot_scatter(prl, max_points=None, fileout="PR_scatter.png", title="Precision Recall Scatter Plot"): """ :param prl: list of tuples (precision, recall) :param max_points: max number of tuples to plot :param fileout: output filename :param title: plot title """ prs = [i[0] for i in prl] recs = [i[1] for i in prl] if max_points is not None: prs = prs[:max_points] recs = recs[:max_points] xy = np.vstack([prs, recs]) z = gaussian_kde(xy)(xy) x = np.array(prs) y = np.array(recs) base = min(z) rg = max(z) - base z = np.array(z) idx = z.argsort() x, y, z = x[idx], y[idx], (z[idx] - base) / rg fig, ax = plt.subplots() sca = ax.scatter(x, y, c=z, s=50, edgecolor='', cmap=plt.cm.jet) fig.colorbar(sca) plt.ylabel("Recall", fontsize=20, labelpad=15) plt.xlabel("Precision", fontsize=20) plt.ylim([-0.01, 1.01]) plt.xlim([-0.01, 1.01]) plt.title(title) if matplotlib.get_backend().lower() in ['agg', 'macosx']: fig.set_tight_layout(True) else: fig.tight_layout() plt.savefig("%s" % fileout)
def __init__(self, show_backend=False): if show_backend: import matplotlib print(matplotlib.get_backend())
def tight_layout(): from matplotlib import get_backend from pylab import gcf if get_backend().lower() in ['agg', 'macosx']: gcf().set_tight_layout(True) else: plt.tight_layout()
def setUpClass(klass): """ In order for tests to pass on Travis-CI we must use the 'Agg' matplotlib backend. This setup function ensures that all tests that do visual work setup the backend correctly. Note: """ klass._backend = mpl.get_backend() super(VisualTestCase, klass).setUpClass()
def plt_show(show=True, **kwargs): """Helper to show a figure while suppressing warnings""" import matplotlib import matplotlib.pyplot as plt if show and matplotlib.get_backend() != 'agg': plt.show(**kwargs)
def __init__(self, fig_dispatch, text_dispatch): self.fig_dispatch = fig_dispatch self.text_dispatch = text_dispatch self._tabs = QtWidgets.QTabWidget() self.widget = QtWidgets.QWidget() self._text_summary = QtWidgets.QLabel() self._tree = QtWidgets.QTreeWidget() self._tree.setAlternatingRowColors(True) self._figures = OrderedDict() self._overplot = {} tree_container = QtWidgets.QVBoxLayout() layout = QtWidgets.QHBoxLayout() tree_container.addWidget(self._text_summary) tree_container.addWidget(QtWidgets.QLabel("View Header (metadata):")) tree_container.addWidget(self._tree) tree_container.addWidget(QtWidgets.QLabel("Export Events (data):")) self.export_widget = Placeholder() # placeholder tree_container.addWidget(self.export_widget.widget) layout.addLayout(tree_container) layout.addWidget(self._tabs) self.widget.setLayout(layout) self.tree_container = tree_container backend = matplotlib.get_backend() if backend == 'Qt5Agg': from matplotlib.backends.backend_qt5agg import ( FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar) elif backend == 'Qt4Agg': from matplotlib.backends.backend_qt4agg import ( FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar) else: raise Exception("matplotlib backend is {!r} but it expected to be" "one of ('Qt4Agg', 'Qt5Agg')".format(backend)) # Stash them on the instance to avoid needing to re-import. self.FigureCanvas = FigureCanvas self.NavigationToolbar = NavigationToolbar
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 select_figure_formats(shell, formats, **kwargs): """Select figure formats for the inline backend. Parameters ========== shell : InteractiveShell The main IPython instance. formats : str or set One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs : any Extra keyword arguments to be passed to fig.canvas.print_figure. """ import matplotlib from matplotlib.figure import Figure svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] jpg_formatter = shell.display_formatter.formatters['image/jpeg'] pdf_formatter = shell.display_formatter.formatters['application/pdf'] if isinstance(formats, str): formats = {formats} # cast in case of list / tuple formats = set(formats) [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] mplbackend = matplotlib.get_backend().lower() if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg': formatter = shell.display_formatter.ipython_display_formatter formatter.for_type(Figure, _reshow_nbagg_figure) supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'} bad = formats.difference(supported) if bad: bs = "%s" % ','.join([repr(f) for f in bad]) gs = "%s" % ','.join([repr(f) for f in supported]) raise ValueError("supported formats are: %s not %s" % (gs, bs)) if 'png' in formats: png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) if 'retina' in formats or 'png2x' in formats: png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) if 'jpg' in formats or 'jpeg' in formats: jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs)) if 'svg' in formats: svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs)) if 'pdf' in formats: pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs)) #----------------------------------------------------------------------------- # Code for initializing matplotlib and importing pylab #-----------------------------------------------------------------------------
def select_figure_formats(shell, formats, **kwargs): """Select figure formats for the inline backend. Parameters ========== shell : InteractiveShell The main IPython instance. formats : str or set One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs : any Extra keyword arguments to be passed to fig.canvas.print_figure. """ import matplotlib from matplotlib.figure import Figure svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] jpg_formatter = shell.display_formatter.formatters['image/jpeg'] pdf_formatter = shell.display_formatter.formatters['application/pdf'] if isinstance(formats, py3compat.string_types): formats = {formats} # cast in case of list / tuple formats = set(formats) [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] mplbackend = matplotlib.get_backend().lower() if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg': formatter = shell.display_formatter.ipython_display_formatter formatter.for_type(Figure, _reshow_nbagg_figure) supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'} bad = formats.difference(supported) if bad: bs = "%s" % ','.join([repr(f) for f in bad]) gs = "%s" % ','.join([repr(f) for f in supported]) raise ValueError("supported formats are: %s not %s" % (gs, bs)) if 'png' in formats: png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) if 'retina' in formats or 'png2x' in formats: png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) if 'jpg' in formats or 'jpeg' in formats: jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs)) if 'svg' in formats: svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs)) if 'pdf' in formats: pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs)) #----------------------------------------------------------------------------- # Code for initializing matplotlib and importing pylab #-----------------------------------------------------------------------------
def ipython_cell_executed(self): user_ns = self.kernel.shell.user_ns ip_keys = set(['In', 'Out', '_', '__', '___', '__builtin__', '_dh', '_ih', '_oh', '_sh', '_i', '_ii', '_iii', 'exit', 'get_ipython', 'quit']) # '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', clean_ns_keys = set([k for k, v in user_ns.items() if not history_vars_pattern.match(k)]) - ip_keys clean_ns = {k: v for k, v in user_ns.items() if k in clean_ns_keys} # user_ns['_i'] is not updated yet (refers to the -2 item) # 'In' and '_ih' point to the same object (but '_ih' is supposed to be the non-overridden one) cur_input_num = len(user_ns['_ih']) - 1 last_input = user_ns['_ih'][-1] if setitem_pattern.match(last_input): m = setitem_pattern.match(last_input) varname = m.group(1) # otherwise it should have failed at this point, but let us be sure if varname in clean_ns: if self._display_in_grid(varname, clean_ns[varname]): # XXX: this completely refreshes the array, including detecting scientific & ndigits, which might # not be what we want in this case self.select_list_item(varname) else: # not setitem => assume expr or normal assignment if last_input in clean_ns: # the name exists in the session (variable) if self._display_in_grid('', self.data[last_input]): # select and display it self.select_list_item(last_input) else: # any statement can contain a call to a function which updates globals # this will select (or refresh) the "first" changed array self.update_mapping(clean_ns) # if the statement produced any output (probably because it is a simple expression), display it. # _oh and Out are supposed to be synonyms but "_ih" is supposed to be the non-overridden one. # It would be easier to use '_' instead but that refers to the last output, not the output of the # last command. Which means that if the last command did not produce any output, _ is not modified. cur_output = user_ns['_oh'].get(cur_input_num) if cur_output is not None: if self._display_in_grid('_', cur_output): self.view_expr(cur_output) if isinstance(cur_output, matplotlib.axes.Subplot) and 'inline' not in matplotlib.get_backend(): show_figure(self, cur_output.figure)
def select_figure_formats(shell, formats, **kwargs): """Select figure formats for the inline backend. Parameters ========== shell : InteractiveShell The main IPython instance. formats : str or set One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs : any Extra keyword arguments to be passed to fig.canvas.print_figure. """ import matplotlib from matplotlib.figure import Figure svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] jpg_formatter = shell.display_formatter.formatters['image/jpeg'] pdf_formatter = shell.display_formatter.formatters['application/pdf'] if isinstance(formats, py3compat.string_types): formats = {formats} # cast in case of list / tuple formats = set(formats) [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] if matplotlib.get_backend().lower() == 'nbagg': formatter = shell.display_formatter.ipython_display_formatter formatter.for_type(Figure, _reshow_nbagg_figure) supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'} bad = formats.difference(supported) if bad: bs = "%s" % ','.join([repr(f) for f in bad]) gs = "%s" % ','.join([repr(f) for f in supported]) raise ValueError("supported formats are: %s not %s" % (gs, bs)) if 'png' in formats: png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) if 'retina' in formats or 'png2x' in formats: png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) if 'jpg' in formats or 'jpeg' in formats: jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs)) if 'svg' in formats: svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs)) if 'pdf' in formats: pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs)) #----------------------------------------------------------------------------- # Code for initializing matplotlib and importing pylab #-----------------------------------------------------------------------------