From b3c04a005cde85c883b2a9fc27e6bfbb30756e0e Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sun, 16 Feb 2020 03:29:22 +0100 Subject: [PATCH] Don't import rcParams but rather use mpl.rcParams (part 2) --- lib/matplotlib/artist.py | 12 ++--- lib/matplotlib/axis.py | 61 ++++++++++++----------- lib/matplotlib/backend_tools.py | 34 ++++++------- lib/matplotlib/backends/_backend_tk.py | 20 ++++---- lib/matplotlib/backends/backend_agg.py | 14 +++--- lib/matplotlib/backends/backend_gtk3.py | 23 ++++----- lib/matplotlib/backends/backend_macosx.py | 8 +-- lib/matplotlib/backends/backend_pdf.py | 32 ++++++------ lib/matplotlib/backends/backend_pgf.py | 24 ++++----- lib/matplotlib/backends/backend_ps.py | 50 +++++++++---------- lib/matplotlib/backends/backend_svg.py | 15 +++--- lib/matplotlib/backends/backend_webagg.py | 12 +++-- lib/matplotlib/backends/backend_wx.py | 22 ++++---- 13 files changed, 168 insertions(+), 159 deletions(-) diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index eef6608421db..222da2b5b4bb 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -8,8 +8,8 @@ import numpy as np -import matplotlib -from . import cbook, docstring, rcParams +import matplotlib as mpl +from . import cbook, docstring from .path import Path from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox, TransformedPatchPath, TransformedPath) @@ -99,8 +99,8 @@ def __init__(self): self._url = None self._gid = None self._snap = None - self._sketch = rcParams['path.sketch'] - self._path_effects = rcParams['path.effects'] + self._sketch = mpl.rcParams['path.sketch'] + self._path_effects = mpl.rcParams['path.effects'] self._sticky_edges = _XYPair([], []) self._in_layout = True @@ -588,7 +588,7 @@ def get_snap(self): See `.set_snap` for details. """ - if rcParams['path.snap']: + if mpl.rcParams['path.snap']: return self._snap else: return False @@ -1602,7 +1602,7 @@ def kwdoc(artist): """ ai = ArtistInspector(artist) return ('\n'.join(ai.pprint_setters_rest(leadingspace=4)) - if matplotlib.rcParams['docstring.hardcopy'] else + if mpl.rcParams['docstring.hardcopy'] else 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4))) diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index fcf13d0ce752..13d6be38870d 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -7,7 +7,7 @@ import numpy as np -from matplotlib import rcParams +import matplotlib as mpl import matplotlib.artist as martist import matplotlib.cbook as cbook import matplotlib.lines as mlines @@ -84,11 +84,12 @@ def __init__(self, axes, loc, label=None, martist.Artist.__init__(self) if gridOn is None: - if major and (rcParams['axes.grid.which'] in ('both', 'major')): - gridOn = rcParams['axes.grid'] - elif (not major) and (rcParams['axes.grid.which'] + if major and (mpl.rcParams['axes.grid.which'] + in ('both', 'major')): + gridOn = mpl.rcParams['axes.grid'] + elif (not major) and (mpl.rcParams['axes.grid.which'] in ('both', 'minor')): - gridOn = rcParams['axes.grid'] + gridOn = mpl.rcParams['axes.grid'] else: gridOn = False @@ -102,25 +103,25 @@ def __init__(self, axes, loc, label=None, major_minor = "major" if major else "minor" if size is None: - size = rcParams[f"{name}.{major_minor}.size"] + size = mpl.rcParams[f"{name}.{major_minor}.size"] self._size = size if width is None: - width = rcParams[f"{name}.{major_minor}.width"] + width = mpl.rcParams[f"{name}.{major_minor}.width"] self._width = width if color is None: - color = rcParams[f"{name}.color"] + color = mpl.rcParams[f"{name}.color"] if pad is None: - pad = rcParams[f"{name}.{major_minor}.pad"] + pad = mpl.rcParams[f"{name}.{major_minor}.pad"] self._base_pad = pad if labelcolor is None: - labelcolor = rcParams[f"{name}.color"] + labelcolor = mpl.rcParams[f"{name}.color"] if labelsize is None: - labelsize = rcParams[f"{name}.labelsize"] + labelsize = mpl.rcParams[f"{name}.labelsize"] self._set_labelrotation(labelrotation) @@ -132,13 +133,13 @@ def __init__(self, axes, loc, label=None, self._zorder = zorder if grid_color is None: - grid_color = rcParams["grid.color"] + grid_color = mpl.rcParams["grid.color"] if grid_linestyle is None: - grid_linestyle = rcParams["grid.linestyle"] + grid_linestyle = mpl.rcParams["grid.linestyle"] if grid_linewidth is None: - grid_linewidth = rcParams["grid.linewidth"] + grid_linewidth = mpl.rcParams["grid.linewidth"] if grid_alpha is None: - grid_alpha = rcParams["grid.alpha"] + grid_alpha = mpl.rcParams["grid.alpha"] grid_kw = {k[5:]: v for k, v in kw.items()} self.apply_tickdir(tickdir) @@ -453,7 +454,7 @@ def _get_text2_transform(self): def apply_tickdir(self, tickdir): if tickdir is None: - tickdir = rcParams['%s.direction' % self.__name__.lower()] + tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()] self._tickdir = tickdir if self._tickdir == 'in': @@ -524,7 +525,7 @@ def _get_text2_transform(self): def apply_tickdir(self, tickdir): if tickdir is None: - tickdir = rcParams['%s.direction' % self.__name__.lower()] + tickdir = mpl.rcParams['%s.direction' % self.__name__.lower()] self._tickdir = tickdir if self._tickdir == 'in': @@ -689,15 +690,15 @@ def __init__(self, axes, pickradius=15): self.label = mtext.Text( np.nan, np.nan, - fontsize=rcParams['axes.labelsize'], - fontweight=rcParams['axes.labelweight'], - color=rcParams['axes.labelcolor'], + fontsize=mpl.rcParams['axes.labelsize'], + fontweight=mpl.rcParams['axes.labelweight'], + color=mpl.rcParams['axes.labelcolor'], ) self._set_artist_props(self.label) self.offsetText = mtext.Text(np.nan, np.nan) self._set_artist_props(self.offsetText) - self.labelpad = rcParams['axes.labelpad'] + self.labelpad = mpl.rcParams['axes.labelpad'] self.pickradius = pickradius @@ -778,10 +779,12 @@ def cla(self): self.callbacks = cbook.CallbackRegistry() # whether the grids are on - self._gridOnMajor = (rcParams['axes.grid'] and - rcParams['axes.grid.which'] in ('both', 'major')) - self._gridOnMinor = (rcParams['axes.grid'] and - rcParams['axes.grid.which'] in ('both', 'minor')) + self._gridOnMajor = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'major')) + self._gridOnMinor = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'minor')) self.reset_ticks() @@ -1842,8 +1845,8 @@ def __init__(self, *args, **kwargs): verticalalignment='top', horizontalalignment='right', transform=mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform()), - fontsize=rcParams['xtick.labelsize'], - color=rcParams['xtick.color'], + fontsize=mpl.rcParams['xtick.labelsize'], + color=mpl.rcParams['xtick.color'], ) self.offset_text_position = 'bottom' @@ -2135,8 +2138,8 @@ def __init__(self, *args, **kwargs): verticalalignment='baseline', horizontalalignment='left', transform=mtransforms.blended_transform_factory( self.axes.transAxes, mtransforms.IdentityTransform()), - fontsize=rcParams['ytick.labelsize'], - color=rcParams['ytick.color'], + fontsize=mpl.rcParams['ytick.labelsize'], + color=mpl.rcParams['ytick.color'], ) self.offset_text_position = 'left' diff --git a/lib/matplotlib/backend_tools.py b/lib/matplotlib/backend_tools.py index 19f7e088d6d7..114d75231c2f 100644 --- a/lib/matplotlib/backend_tools.py +++ b/lib/matplotlib/backend_tools.py @@ -20,7 +20,7 @@ import numpy as np -from matplotlib import rcParams +import matplotlib as mpl from matplotlib._pylab_helpers import Gcf import matplotlib.cbook as cbook @@ -394,7 +394,7 @@ class ToolQuit(ToolBase): """Tool to call the figure manager destroy method""" description = 'Quit the figure' - default_keymap = rcParams['keymap.quit'] + default_keymap = mpl.rcParams['keymap.quit'] def trigger(self, sender, event, data=None): Gcf.destroy_fig(self.figure) @@ -404,7 +404,7 @@ class ToolQuitAll(ToolBase): """Tool to call the figure manager destroy method""" description = 'Quit all figures' - default_keymap = rcParams['keymap.quit_all'] + default_keymap = mpl.rcParams['keymap.quit_all'] def trigger(self, sender, event, data=None): Gcf.destroy_all() @@ -414,7 +414,7 @@ class ToolEnableAllNavigation(ToolBase): """Tool to enable all axes for toolmanager interaction""" description = 'Enable all axes toolmanager' - default_keymap = rcParams['keymap.all_axes'] + default_keymap = mpl.rcParams['keymap.all_axes'] def trigger(self, sender, event, data=None): if event.inaxes is None: @@ -482,7 +482,7 @@ class ToolGrid(_ToolGridBase): """Tool to toggle the major grids of the figure""" description = 'Toggle major grids' - default_keymap = rcParams['keymap.grid'] + default_keymap = mpl.rcParams['keymap.grid'] def _get_next_grid_states(self, ax): if None in map(self._get_uniform_grid_state, @@ -503,7 +503,7 @@ class ToolMinorGrid(_ToolGridBase): """Tool to toggle the major and minor grids of the figure""" description = 'Toggle major and minor grids' - default_keymap = rcParams['keymap.grid_minor'] + default_keymap = mpl.rcParams['keymap.grid_minor'] def _get_next_grid_states(self, ax): if None in map(self._get_uniform_grid_state, @@ -523,7 +523,7 @@ class ToolFullScreen(ToolToggleBase): """Tool to toggle full screen""" description = 'Toggle fullscreen mode' - default_keymap = rcParams['keymap.fullscreen'] + default_keymap = mpl.rcParams['keymap.fullscreen'] def enable(self, event): self.figure.canvas.manager.full_screen_toggle() @@ -553,7 +553,7 @@ class ToolYScale(AxisScaleBase): """Tool to toggle between linear and logarithmic scales on the Y axis""" description = 'Toggle scale Y axis' - default_keymap = rcParams['keymap.yscale'] + default_keymap = mpl.rcParams['keymap.yscale'] def set_scale(self, ax, scale): ax.set_yscale(scale) @@ -563,7 +563,7 @@ class ToolXScale(AxisScaleBase): """Tool to toggle between linear and logarithmic scales on the X axis""" description = 'Toggle scale X axis' - default_keymap = rcParams['keymap.xscale'] + default_keymap = mpl.rcParams['keymap.xscale'] def set_scale(self, ax, scale): ax.set_xscale(scale) @@ -738,7 +738,7 @@ class ToolHome(ViewsPositionsBase): description = 'Reset original view' image = 'home' - default_keymap = rcParams['keymap.home'] + default_keymap = mpl.rcParams['keymap.home'] _on_trigger = 'home' @@ -747,7 +747,7 @@ class ToolBack(ViewsPositionsBase): description = 'Back to previous view' image = 'back' - default_keymap = rcParams['keymap.back'] + default_keymap = mpl.rcParams['keymap.back'] _on_trigger = 'back' @@ -756,7 +756,7 @@ class ToolForward(ViewsPositionsBase): description = 'Forward to next view' image = 'forward' - default_keymap = rcParams['keymap.forward'] + default_keymap = mpl.rcParams['keymap.forward'] _on_trigger = 'forward' @@ -772,7 +772,7 @@ class SaveFigureBase(ToolBase): description = 'Save the figure' image = 'filesave' - default_keymap = rcParams['keymap.save'] + default_keymap = mpl.rcParams['keymap.save'] class ZoomPanBase(ToolToggleBase): @@ -844,7 +844,7 @@ class ToolZoom(ZoomPanBase): description = 'Zoom to rectangle' image = 'zoom_to_rect' - default_keymap = rcParams['keymap.zoom'] + default_keymap = mpl.rcParams['keymap.zoom'] cursor = cursors.SELECT_REGION radio_group = 'default' @@ -968,7 +968,7 @@ def _release(self, event): class ToolPan(ZoomPanBase): """Pan axes with left mouse, zoom with right""" - default_keymap = rcParams['keymap.pan'] + default_keymap = mpl.rcParams['keymap.pan'] description = 'Pan axes with left mouse, zoom with right' image = 'move' cursor = cursors.MOVE @@ -1033,7 +1033,7 @@ def _mouse_move(self, event): class ToolHelpBase(ToolBase): description = 'Print tool list, shortcuts and description' - default_keymap = rcParams['keymap.help'] + default_keymap = mpl.rcParams['keymap.help'] image = 'help.png' @staticmethod @@ -1073,7 +1073,7 @@ class ToolCopyToClipboardBase(ToolBase): """Tool to copy the figure to the clipboard""" description = 'Copy the canvas figure to clipboard' - default_keymap = rcParams['keymap.copy'] + default_keymap = mpl.rcParams['keymap.copy'] def trigger(self, *args, **kwargs): message = "Copy tool is not available" diff --git a/lib/matplotlib/backends/_backend_tk.py b/lib/matplotlib/backends/_backend_tk.py index b9df92ec6402..6556d104f382 100644 --- a/lib/matplotlib/backends/_backend_tk.py +++ b/lib/matplotlib/backends/_backend_tk.py @@ -10,8 +10,8 @@ import numpy as np -import matplotlib -from matplotlib import backend_tools, cbook, rcParams +import matplotlib as mpl +from matplotlib import backend_tools, cbook from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, StatusbarBase, TimerBase, ToolContainerBase, cursors) @@ -34,7 +34,7 @@ def _restore_foreground_window_at_end(): try: yield finally: - if rcParams['tk.window_focus']: + if mpl.rcParams['tk.window_focus']: Win32_SetForegroundWindow(foreground) @@ -430,16 +430,16 @@ def __init__(self, canvas, num, window): self._shown = False def _get_toolbar(self): - if matplotlib.rcParams['toolbar'] == 'toolbar2': + if mpl.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2Tk(self.canvas, self.window) - elif matplotlib.rcParams['toolbar'] == 'toolmanager': + elif mpl.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarTk(self.toolmanager, self.window) else: toolbar = None return toolbar def _get_toolmanager(self): - if rcParams['toolbar'] == 'toolmanager': + if mpl.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None @@ -461,7 +461,7 @@ def destroy(*args): self.window.deiconify() else: self.canvas.draw_idle() - if matplotlib.rcParams['figure.raise_window']: + if mpl.rcParams['figure.raise_window']: self.canvas.manager.window.attributes('-topmost', 1) self.canvas.manager.window.attributes('-topmost', 0) self._shown = True @@ -602,7 +602,7 @@ def save_figure(self, *args): # work - JDH! #defaultextension = self.canvas.get_default_filetype() defaultextension = '' - initialdir = os.path.expanduser(rcParams['savefig.directory']) + initialdir = os.path.expanduser(mpl.rcParams['savefig.directory']) initialfile = self.canvas.get_default_filename() fname = tkinter.filedialog.asksaveasfilename( master=self.canvas.get_tk_widget().master, @@ -617,7 +617,7 @@ def save_figure(self, *args): return # Save dir for next time, unless empty str (i.e., use cwd). if initialdir != "": - rcParams['savefig.directory'] = ( + mpl.rcParams['savefig.directory'] = ( os.path.dirname(str(fname))) try: # This method will handle the delegation to the correct type @@ -877,7 +877,7 @@ def new_figure_manager_given_figure(cls, num, figure): canvas = cls.FigureCanvas(figure, master=window) manager = cls.FigureManager(canvas, num, window) - if matplotlib.is_interactive(): + if mpl.is_interactive(): manager.show() canvas.draw_idle() return manager diff --git a/lib/matplotlib/backends/backend_agg.py b/lib/matplotlib/backends/backend_agg.py index 48ecd20939a7..b6cae5b80732 100644 --- a/lib/matplotlib/backends/backend_agg.py +++ b/lib/matplotlib/backends/backend_agg.py @@ -35,7 +35,8 @@ from PIL import Image from PIL.PngImagePlugin import PngInfo -from matplotlib import cbook, rcParams, __version__ +import matplotlib as mpl +from matplotlib import cbook from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) from matplotlib.font_manager import findfont, get_font @@ -59,7 +60,7 @@ def get_hinting_flag(): 'auto': LOAD_FORCE_AUTOHINT, 'none': LOAD_NO_HINTING } - return mapping[rcParams['text.hinting']] + return mapping[mpl.rcParams['text.hinting']] class RendererAgg(RendererBase): @@ -122,7 +123,7 @@ def tostring_rgba_minimized(self): def draw_path(self, gc, path, transform, rgbFace=None): # docstring inherited - nmax = rcParams['agg.path.chunksize'] # here at least for testing + nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing npts = path.vertices.shape[0] if (npts > nmax > 100 and path.should_simplify and @@ -177,7 +178,8 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). font.set_text(s, 0, flags=flags) - font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased']) + font.draw_glyphs_to_bitmap( + antialiased=mpl.rcParams['text.antialiased']) d = font.get_descent() / 64.0 # The descent needs to be adjusted for the angle. xo, yo = font.get_bitmap_offset() @@ -483,7 +485,7 @@ def print_png(self, filename_or_obj, *args, pil_kwargs = {} metadata = { "Software": - f"matplotlib version{__version__}, http://matplotlib.org/", + f"matplotlib version{mpl.__version__}, http://matplotlib.org/", **metadata, } FigureCanvasAgg.draw(self) @@ -552,7 +554,7 @@ def print_jpg(self, filename_or_obj, *args, dryrun=False, pil_kwargs=None, for k in ["quality", "optimize", "progressive"]: if k in kwargs: pil_kwargs.setdefault(k, kwargs[k]) - pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"]) + pil_kwargs.setdefault("quality", mpl.rcParams["savefig.jpeg_quality"]) pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi)) return background.save( filename_or_obj, format='jpeg', **pil_kwargs) diff --git a/lib/matplotlib/backends/backend_gtk3.py b/lib/matplotlib/backends/backend_gtk3.py index 7fd0a3fe4d0b..8cbe35e8001d 100644 --- a/lib/matplotlib/backends/backend_gtk3.py +++ b/lib/matplotlib/backends/backend_gtk3.py @@ -4,8 +4,8 @@ from pathlib import Path import sys -import matplotlib -from matplotlib import backend_tools, cbook, rcParams +import matplotlib as mpl +from matplotlib import backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, @@ -371,7 +371,7 @@ def destroy(*args): Gcf.destroy(num) self.window.connect("destroy", destroy) self.window.connect("delete_event", destroy) - if matplotlib.is_interactive(): + if mpl.is_interactive(): self.window.show() self.canvas.draw_idle() @@ -384,8 +384,7 @@ def destroy(self, *args): if self.toolbar: self.toolbar.destroy() - if (Gcf.get_num_fig_managers() == 0 and - not matplotlib.is_interactive() and + if (Gcf.get_num_fig_managers() == 0 and not mpl.is_interactive() and Gtk.main_level() >= 1): Gtk.main_quit() @@ -393,7 +392,7 @@ def show(self): # show the figure window self.window.show() self.canvas.draw() - if matplotlib.rcParams['figure.raise_window']: + if mpl.rcParams['figure.raise_window']: self.window.present() def full_screen_toggle(self): @@ -407,9 +406,9 @@ def full_screen_toggle(self): def _get_toolbar(self): # must be inited after the window, drawingArea and figure # attrs are set - if rcParams['toolbar'] == 'toolbar2': + if mpl.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2GTK3(self.canvas, self.window) - elif rcParams['toolbar'] == 'toolmanager': + elif mpl.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarGTK3(self.toolmanager) else: toolbar = None @@ -417,7 +416,7 @@ def _get_toolbar(self): def _get_toolmanager(self): # must be initialised after toolbar has been set - if rcParams['toolbar'] == 'toolmanager': + if mpl.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None @@ -547,7 +546,7 @@ def on_notify_filter(*args): dialog.set_current_name( str(Path(dialog.get_current_name()).with_suffix("." + fmt))) - dialog.set_current_folder(rcParams["savefig.directory"]) + dialog.set_current_folder(mpl.rcParams["savefig.directory"]) dialog.set_current_name(self.canvas.get_default_filename()) dialog.set_do_overwrite_confirmation(True) @@ -559,8 +558,8 @@ def on_notify_filter(*args): if response == Gtk.ResponseType.CANCEL: return # Save dir for next time, unless empty str (which means use cwd). - if rcParams['savefig.directory']: - rcParams['savefig.directory'] = os.path.dirname(fname) + if mpl.rcParams['savefig.directory']: + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) try: self.canvas.figure.savefig(fname, format=fmt) except Exception as e: diff --git a/lib/matplotlib/backends/backend_macosx.py b/lib/matplotlib/backends/backend_macosx.py index b8b66bfd08f5..31bf8a4cb947 100644 --- a/lib/matplotlib/backends/backend_macosx.py +++ b/lib/matplotlib/backends/backend_macosx.py @@ -1,5 +1,5 @@ -import matplotlib -from matplotlib import cbook, rcParams +import matplotlib as mpl +from matplotlib import cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backends import _macosx from matplotlib.backends.backend_agg import FigureCanvasAgg @@ -94,14 +94,14 @@ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) title = "Figure %d" % num _macosx.FigureManager.__init__(self, canvas, title) - if rcParams['toolbar'] == 'toolbar2': + if mpl.rcParams['toolbar'] == 'toolbar2': self.toolbar = NavigationToolbar2Mac(canvas) else: self.toolbar = None if self.toolbar is not None: self.toolbar.update() - if matplotlib.is_interactive(): + if mpl.is_interactive(): self.show() self.canvas.draw_idle() diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 2d20145c38fb..61c33f9f5c50 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -22,7 +22,8 @@ import numpy as np from PIL import Image -from matplotlib import _text_layout, cbook, __version__, rcParams +import matplotlib as mpl +from matplotlib import _text_layout, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, @@ -376,8 +377,9 @@ def __init__(self, id, len, file, extra=None, png=None): 'DecodeParms': png}) self.pdfFile.recordXref(self.id) - if rcParams['pdf.compression'] and not png: - self.compressobj = zlib.compressobj(rcParams['pdf.compression']) + if mpl.rcParams['pdf.compression'] and not png: + self.compressobj = zlib.compressobj( + mpl.rcParams['pdf.compression']) if self.len is None: self.file = BytesIO() else: @@ -389,7 +391,7 @@ def _writeHeader(self): write(b"%d 0 obj\n" % self.id) dict = self.extra dict['Length'] = self.len - if rcParams['pdf.compression']: + if mpl.rcParams['pdf.compression']: dict['Filter'] = Name('FlateDecode') write(pdfRepr(dict)) @@ -499,8 +501,8 @@ def __init__(self, filename, metadata=None): source_date = datetime.today() self.infoDict = { - 'Creator': 'matplotlib %s, http://matplotlib.org' % __version__, - 'Producer': 'matplotlib pdf backend %s' % __version__, + 'Creator': f'matplotlib {mpl.__version__}, http://matplotlib.org', + 'Producer': f'matplotlib pdf backend {mpl.__version__}', 'CreationDate': source_date } if metadata is not None: @@ -665,7 +667,7 @@ def fontName(self, fontprop): if isinstance(fontprop, str): filename = fontprop - elif rcParams['pdf.use14corefonts']: + elif mpl.rcParams['pdf.use14corefonts']: filename = findfont( fontprop, fontext='afm', directory=RendererPdf._afm_font_dir) else: @@ -899,7 +901,7 @@ def embedTTF(self, filename, characters): """Embed the TTF font from the named file into the document.""" font = get_font(filename) - fonttype = rcParams['pdf.fonttype'] + fonttype = mpl.rcParams['pdf.fonttype'] def cvt(length, upe=font.units_per_EM, nearest=True): """Convert font coordinates to PDF glyph coordinates.""" @@ -1323,7 +1325,7 @@ def writeHatches(self): 0, 0, sidelen, sidelen, Op.rectangle, Op.fill) - self.output(rcParams['hatch.linewidth'], Op.setlinewidth) + self.output(mpl.rcParams['hatch.linewidth'], Op.setlinewidth) self.output(*self.pathOperations( Path.hatch(path), @@ -1474,7 +1476,7 @@ def _writeImg(self, data, id, smask=None): 'BitsPerComponent': 8} if smask: obj['SMask'] = smask - if rcParams['pdf.compression']: + if mpl.rcParams['pdf.compression']: png = {'Predictor': 10, 'Colors': colors, 'Columns': width} else: png = None @@ -1930,7 +1932,7 @@ def draw_mathtext(self, gc, x, y, s, prop, angle): # When using Type 3 fonts, we can't use character codes higher # than 255, so we use the "Do" command to render those # instead. - global_fonttype = rcParams['pdf.fonttype'] + global_fonttype = mpl.rcParams['pdf.fonttype'] # Set up a global transformation matrix for the whole math expression a = math.radians(angle) @@ -2083,13 +2085,13 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): fontsize = prop.get_size_in_points() - if rcParams['pdf.use14corefonts']: + if mpl.rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) fonttype = 1 else: font = self._get_font_ttf(prop) self.file._character_tracker.track(font, s) - fonttype = rcParams['pdf.fonttype'] + fonttype = mpl.rcParams['pdf.fonttype'] # We can't subset all OpenType fonts, so switch to Type 42 # in that case. if is_opentype_cff_font(font.fname): @@ -2248,7 +2250,7 @@ def hatch_cmd(self, hatch, hatch_color): name, Op.setcolor_nonstroke] def rgb_cmd(self, rgb): - if rcParams['pdf.inheritcolor']: + if mpl.rcParams['pdf.inheritcolor']: return [] if rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_stroke] @@ -2256,7 +2258,7 @@ def rgb_cmd(self, rgb): return [*rgb[:3], Op.setrgb_stroke] def fillcolor_cmd(self, rgb): - if rgb is None or rcParams['pdf.inheritcolor']: + if rgb is None or mpl.rcParams['pdf.inheritcolor']: return [] elif rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_nonstroke] diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index 773246bb3ba7..4c38522277cc 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -15,7 +15,7 @@ from PIL import Image import matplotlib as mpl -from matplotlib import cbook, font_manager as fm, __version__, rcParams +from matplotlib import cbook, font_manager as fm from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase) @@ -35,12 +35,12 @@ def get_fontspec(): """Build fontspec preamble from rc.""" latex_fontspec = [] - texcommand = rcParams["pgf.texsystem"] + texcommand = mpl.rcParams["pgf.texsystem"] if texcommand != "pdflatex": latex_fontspec.append("\\usepackage{fontspec}") - if texcommand != "pdflatex" and rcParams["pgf.rcfonts"]: + if texcommand != "pdflatex" and mpl.rcParams["pgf.rcfonts"]: families = ["serif", "sans\\-serif", "monospace"] commands = ["setmainfont", "setsansfont", "setmonofont"] for family, command in zip(families, commands): @@ -55,7 +55,7 @@ def get_fontspec(): def get_preamble(): """Get LaTeX preamble from rc.""" - return rcParams["pgf.preamble"] + return mpl.rcParams["pgf.preamble"] ############################################################################### @@ -131,7 +131,7 @@ def _font_properties_str(prop): if family in families: commands.append(families[family]) elif (any(font.name == family for font in fm.fontManager.ttflist) - and rcParams["pgf.texsystem"] != "pdflatex"): + and mpl.rcParams["pgf.texsystem"] != "pdflatex"): commands.append(r"\setmainfont{%s}\rmfamily" % family) else: pass # print warning? @@ -201,7 +201,7 @@ def _build_latex_header(): r"\documentclass{minimal}", # Include TeX program name as a comment for cache invalidation. # TeX does not allow this to be the first line. - r"% !TeX program = {}".format(rcParams["pgf.texsystem"]), + rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}", # Test whether \includegraphics supports interpolate option. r"\usepackage{graphicx}", latex_preamble, @@ -265,7 +265,7 @@ def __init__(self): LatexManager._unclean_instances.add(self) # test the LaTeX setup to ensure a clean startup of the subprocess - self.texcommand = rcParams["pgf.texsystem"] + self.texcommand = mpl.rcParams["pgf.texsystem"] self.latex_header = LatexManager._build_latex_header() latex_end = "\n\\makeatletter\n\\@@end\n" try: @@ -636,7 +636,7 @@ def option_scale_image(self): def option_image_nocomposite(self): # docstring inherited - return not rcParams['image.composite_image'] + return not mpl.rcParams['image.composite_image'] def draw_image(self, gc, x, y, im, transform=None): # docstring inherited @@ -897,7 +897,7 @@ def _print_pdf_to_fh(self, fh, *args, **kwargs): \\end{document}""" % (w, h, latex_preamble, latex_fontspec) pathlib.Path(fname_tex).write_text(latexcode, encoding="utf-8") - texcommand = rcParams["pgf.texsystem"] + texcommand = mpl.rcParams["pgf.texsystem"] cbook._check_and_log_subprocess( [texcommand, "-interaction=nonstopmode", "-halt-on-error", "figure.tex"], _log, cwd=tmpdir) @@ -1036,8 +1036,8 @@ def _write_header(self, width_inches, height_inches): 'producer', 'trapped' } infoDict = { - 'creator': 'matplotlib %s, https://matplotlib.org' % __version__, - 'producer': 'matplotlib pgf backend %s' % __version__, + 'creator': f'matplotlib {mpl.__version__}, https://matplotlib.org', + 'producer': f'matplotlib pgf backend {mpl.__version__}', } metadata = {k.lower(): v for k, v in self.metadata.items()} infoDict.update(metadata) @@ -1102,7 +1102,7 @@ def close(self): open(self._outputfile, 'wb').close() def _run_latex(self): - texcommand = rcParams["pgf.texsystem"] + texcommand = mpl.rcParams["pgf.texsystem"] cbook._check_and_log_subprocess( [texcommand, "-interaction=nonstopmode", "-halt-on-error", os.path.basename(self._fname_tex)], diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 38fe1c189dbc..e1ef94010c06 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -18,7 +18,7 @@ import numpy as np import matplotlib as mpl -from matplotlib import cbook, _path, __version__, rcParams +from matplotlib import cbook, _path from matplotlib import _text_layout from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, @@ -148,7 +148,7 @@ def __init__(self, width, height, pswriter, imagedpi=72): # and them scale them before embedding them. super().__init__(width, height) self._pswriter = pswriter - if rcParams['text.usetex']: + if mpl.rcParams['text.usetex']: self.textcnt = 0 self.psfrag = [] self.imagedpi = imagedpi @@ -227,7 +227,7 @@ def set_linedash(self, offset, seq, store=True): self.linedash = (offset, seq) def set_font(self, fontname, fontsize, store=True): - if rcParams['ps.useafm']: + if mpl.rcParams['ps.useafm']: return if (fontname, fontsize) != (self.fontname, self.fontsize): out = ("/%s findfont\n" @@ -243,7 +243,7 @@ def create_hatch(self, hatch): if hatch in self._hatches: return self._hatches[hatch] name = 'H%d' % len(self._hatches) - linewidth = rcParams['hatch.linewidth'] + linewidth = mpl.rcParams['hatch.linewidth'] pageheight = self.height * 72 self._pswriter.write(f"""\ << /PatternType 1 @@ -472,12 +472,12 @@ def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None): color = '%1.3f,%1.3f,%1.3f' % gc.get_rgb()[:3] fontcmd = {'sans-serif': r'{\sffamily %s}', 'monospace': r'{\ttfamily %s}'}.get( - rcParams['font.family'][0], r'{\rmfamily %s}') + mpl.rcParams['font.family'][0], r'{\rmfamily %s}') s = fontcmd % s tex = r'\color[rgb]{%s} %s' % (color, s) corr = 0 # w/2*(fontsize-10)/10 - if rcParams['text.latex.preview']: + if mpl.rcParams['text.latex.preview']: # use baseline alignment! pos = _nums_to_str(x-corr, y) self.psfrag.append( @@ -517,7 +517,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): elif ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) - elif rcParams['ps.useafm']: + elif mpl.rcParams['ps.useafm']: self.set_color(*gc.get_rgb()) font = self._get_font_afm(prop) @@ -769,7 +769,7 @@ def _print_ps(self, outfile, format, *args, orientation='portrait', **kwargs): if papertype is None: - papertype = rcParams['ps.papersize'] + papertype = mpl.rcParams['ps.papersize'] papertype = papertype.lower() cbook._check_in_list(['auto', *papersize], papertype=papertype) @@ -779,7 +779,7 @@ def _print_ps(self, outfile, format, *args, self.figure.set_dpi(72) # Override the dpi kwarg printer = (self._print_figure_tex - if rcParams['text.usetex'] else + if mpl.rcParams['text.usetex'] else self._print_figure) printer(outfile, format, dpi, facecolor, edgecolor, orientation, papertype, **kwargs) @@ -824,7 +824,7 @@ def _print_figure( paper_width, paper_height = orientation.swap_if_landscape( papersize[papertype]) - if rcParams['ps.usedistiller']: + if mpl.rcParams['ps.usedistiller']: # distillers improperly clip eps files if pagesize is too small if width > paper_width or height > paper_height: papertype = _get_papertype( @@ -881,8 +881,8 @@ def write(self, *args, **kwargs): if metadata is not None and 'Creator' in metadata: creator_str = metadata['Creator'] else: - creator_str = "matplotlib version " + __version__ + \ - ", http://matplotlib.org/" + creator_str = \ + f"matplotlib version {mpl.__version__}, http://matplotlib.org/" def print_figure_impl(fh): # write the PostScript headers @@ -912,7 +912,7 @@ def print_figure_impl(fh): Ndict = len(psDefs) print("%%BeginProlog", file=fh) - if not rcParams['ps.useafm']: + if not mpl.rcParams['ps.useafm']: Ndict += len(ps_renderer._character_tracker.used) print("/mpldict %d dict def" % Ndict, file=fh) print("mpldict begin", file=fh) @@ -920,14 +920,14 @@ def print_figure_impl(fh): d = d.strip() for l in d.split('\n'): print(l.strip(), file=fh) - if not rcParams['ps.useafm']: + if not mpl.rcParams['ps.useafm']: for font_path, chars \ in ps_renderer._character_tracker.used.items(): if not chars: continue font = get_font(font_path) glyph_ids = [font.get_char_index(c) for c in chars] - fonttype = rcParams['ps.fonttype'] + fonttype = mpl.rcParams['ps.fonttype'] # Can't use more than 255 chars from a single Type 3 font. if len(glyph_ids) > 255: fonttype = 42 @@ -973,16 +973,16 @@ def print_figure_impl(fh): print("%%EOF", file=fh) fh.flush() - if rcParams['ps.usedistiller']: + if mpl.rcParams['ps.usedistiller']: # We are going to use an external program to process the output. # Write to a temporary file. with TemporaryDirectory() as tmpdir: tmpfile = os.path.join(tmpdir, "tmp.ps") with open(tmpfile, 'w', encoding='latin-1') as fh: print_figure_impl(fh) - if rcParams['ps.usedistiller'] == 'ghostscript': + if mpl.rcParams['ps.usedistiller'] == 'ghostscript': gs_distill(tmpfile, is_eps, ptype=papertype, bbox=bbox) - elif rcParams['ps.usedistiller'] == 'xpdf': + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, is_eps, ptype=papertype, bbox=bbox) _move_path_to_path_or_stream(tmpfile, outfile) @@ -1072,8 +1072,8 @@ def write(self, *args, **kwargs): if metadata is not None and 'Creator' in metadata: creator_str = metadata['Creator'] else: - creator_str = "matplotlib version " + __version__ + \ - ", http://matplotlib.org/" + creator_str = \ + f"matplotlib version {mpl.__version__}, http://matplotlib.org/" # write to a temp file, we'll move it to outfile when done @@ -1139,11 +1139,11 @@ def write(self, *args, **kwargs): paper_height, orientation.name) - if (rcParams['ps.usedistiller'] == 'ghostscript' - or rcParams['text.usetex']): + if (mpl.rcParams['ps.usedistiller'] == 'ghostscript' + or mpl.rcParams['text.usetex']): gs_distill(tmpfile, is_eps, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) - elif rcParams['ps.usedistiller'] == 'xpdf': + elif mpl.rcParams['ps.usedistiller'] == 'xpdf': xpdf_distill(tmpfile, is_eps, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) @@ -1161,7 +1161,7 @@ def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble, """ with mpl.rc_context({ "text.latex.preamble": - rcParams["text.latex.preamble"] + + mpl.rcParams["text.latex.preamble"] + r"\usepackage{psfrag,color}" r"\usepackage[dvips]{graphicx}" r"\PassOptionsToPackage{dvips}{geometry}"}): @@ -1211,7 +1211,7 @@ def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): paper_option = "-sPAPERSIZE=%s" % ptype psfile = tmpfile + '.ps' - dpi = rcParams['ps.distiller.res'] + dpi = mpl.rcParams['ps.distiller.res'] cbook._check_and_log_subprocess( [mpl._get_executable_info("gs").executable, diff --git a/lib/matplotlib/backends/backend_svg.py b/lib/matplotlib/backends/backend_svg.py index eaa0f9e0c58b..30930c4d702e 100644 --- a/lib/matplotlib/backends/backend_svg.py +++ b/lib/matplotlib/backends/backend_svg.py @@ -11,7 +11,8 @@ import numpy as np from PIL import Image -from matplotlib import cbook, __version__, rcParams +import matplotlib as mpl +from matplotlib import cbook from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) from matplotlib.backends.backend_mixed import MixedModeRenderer @@ -25,7 +26,7 @@ _log = logging.getLogger(__name__) -backend_version = __version__ +backend_version = mpl.__version__ # ---------------------------------------------------------------------- # SimpleXMLWriter class @@ -323,7 +324,7 @@ def _write_default_style(self): writer.end('defs') def _make_id(self, type, content): - salt = rcParams['svg.hashsalt'] + salt = mpl.rcParams['svg.hashsalt'] if salt is None: salt = str(uuid.uuid4()) m = hashlib.md5() @@ -396,7 +397,7 @@ def _write_hatches(self): style=generate_css({ 'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), - 'stroke-width': str(rcParams['hatch.linewidth']), + 'stroke-width': str(mpl.rcParams['hatch.linewidth']), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' }) @@ -513,7 +514,7 @@ def close_group(self, s): def option_image_nocomposite(self): # docstring inherited - return not rcParams['image.composite_image'] + return not mpl.rcParams['image.composite_image'] def _convert_path(self, path, transform=None, clip=None, simplify=None, sketch=None): @@ -823,7 +824,7 @@ def draw_image(self, gc, x, y, im, transform=None): url = gc.get_url() if url is not None: self.writer.start('a', attrib={'xlink:href': url}) - if rcParams['svg.image_inline']: + if mpl.rcParams['svg.image_inline']: buf = BytesIO() Image.fromarray(im).save(buf, format="png") oid = oid or self._make_id('image', buf.getvalue()) @@ -1154,7 +1155,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if gc.get_url() is not None: self.writer.start('a', {'xlink:href': gc.get_url()}) - if rcParams['svg.fonttype'] == 'path': + if mpl.rcParams['svg.fonttype'] == 'path': self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext) else: self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext) diff --git a/lib/matplotlib/backends/backend_webagg.py b/lib/matplotlib/backends/backend_webagg.py index c0f5cb9d01a1..545d7ff9098e 100644 --- a/lib/matplotlib/backends/backend_webagg.py +++ b/lib/matplotlib/backends/backend_webagg.py @@ -32,7 +32,8 @@ import tornado.ioloop import tornado.websocket -from matplotlib import cbook, rcParams +import matplotlib as mpl +from matplotlib import cbook from matplotlib.backend_bases import _Backend from matplotlib._pylab_helpers import Gcf from . import backend_webagg_core as core @@ -217,11 +218,12 @@ def random_ports(port, n): yield port + random.randint(-2 * n, 2 * n) if address is None: - cls.address = rcParams['webagg.address'] + cls.address = mpl.rcParams['webagg.address'] else: cls.address = address - cls.port = rcParams['webagg.port'] - for port in random_ports(cls.port, rcParams['webagg.port_retries']): + cls.port = mpl.rcParams['webagg.port'] + for port in random_ports(cls.port, + mpl.rcParams['webagg.port_retries']): try: app.listen(port, cls.address) except socket.error as e: @@ -313,7 +315,7 @@ def show(): port=WebAggApplication.port, prefix=WebAggApplication.url_prefix) - if rcParams['webagg.open_in_browser']: + if mpl.rcParams['webagg.open_in_browser']: import webbrowser if not webbrowser.open(url): print("To view figure, visit {0}".format(url)) diff --git a/lib/matplotlib/backends/backend_wx.py b/lib/matplotlib/backends/backend_wx.py index 088789985944..d23961099740 100644 --- a/lib/matplotlib/backends/backend_wx.py +++ b/lib/matplotlib/backends/backend_wx.py @@ -13,13 +13,13 @@ import sys import weakref -import matplotlib +import matplotlib as mpl from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase, StatusbarBase, TimerBase, ToolContainerBase, cursors) -from matplotlib import cbook, rcParams, backend_tools +from matplotlib import cbook, backend_tools from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.figure import Figure @@ -886,7 +886,7 @@ def _print_image(self, filename, filetype, *args, **kwargs): # and set the quality. if filetype == wx.BITMAP_TYPE_JPEG: jpeg_quality = kwargs.get('quality', - rcParams['savefig.jpeg_quality']) + mpl.rcParams['savefig.jpeg_quality']) image = self.bitmap.ConvertToImage() image.SetOption(wx.IMAGE_OPTION_QUALITY, str(jpeg_quality)) @@ -981,16 +981,16 @@ def statusbar(self): return self.GetStatusBar() def _get_toolbar(self): - if rcParams['toolbar'] == 'toolbar2': + if mpl.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2Wx(self.canvas) - elif matplotlib.rcParams['toolbar'] == 'toolmanager': + elif mpl.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarWx(self.toolmanager, self) else: toolbar = None return toolbar def _get_toolmanager(self): - if matplotlib.rcParams['toolbar'] == 'toolmanager': + if mpl.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None @@ -1061,7 +1061,7 @@ def __init__(self, canvas, num, frame): def show(self): self.frame.Show() self.canvas.draw() - if matplotlib.rcParams['figure.raise_window']: + if mpl.rcParams['figure.raise_window']: self.frame.Raise() def destroy(self, *args): @@ -1193,7 +1193,7 @@ def save_figure(self, *args): default_file = self.canvas.get_default_filename() dlg = wx.FileDialog( self.canvas.GetParent(), "Save to file", - rcParams["savefig.directory"], default_file, filetypes, + mpl.rcParams["savefig.directory"], default_file, filetypes, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() == wx.ID_OK: @@ -1209,8 +1209,8 @@ def save_figure(self, *args): ext, fmt, ext) fmt = ext # Save dir for next time, unless empty str (which means use cwd). - if rcParams["savefig.directory"]: - rcParams["savefig.directory"] = str(path.parent) + if mpl.rcParams["savefig.directory"]: + mpl.rcParams["savefig.directory"] = str(path.parent) try: self.canvas.figure.savefig(str(path), format=fmt) except Exception as e: @@ -1641,7 +1641,7 @@ def new_figure_manager(cls, num, *args, **kwargs): def new_figure_manager_given_figure(cls, num, figure): frame = cls._frame_class(num, figure) figmgr = frame.get_figure_manager() - if matplotlib.is_interactive(): + if mpl.is_interactive(): figmgr.frame.Show() figure.canvas.draw_idle() return figmgr