Question: import matplotlib as mplfrom matplotlib.backends.backend_webagg_core import (from matplotlib.backends.backend_webagg import (     FigureManagerWebAgg, new_figure_manager_given_figure) from matplotlib.figure import Figure diff --git a/lib/matplotlib/backends/backend_webagg_core.py b/lib/matplotlib/backends/backend_webagg_core.py-- a/lib/matplotlib/backends/backend_webagg_core.py++ b/lib/matplotlib/backends/backend_webagg_core.py

[Bug]: Bug with toolbar instantiation in notebook In MNE-Python we have an abstraction layer for widgets+toolbars. Until today's latest install it was working fine. Now it fails with: See I'll work on boiling it down to a MWE tomorrow hopefully. Could also be a bug with traitlets. But the code that runs on the CIs is essentially this in a notebook I think: <details<summaryFull traceback</summary</detailsNo error EDIT: ipympl 0.9.2 Ubuntu (GH actions), or macOS M1 (locally) 0rc1 Notebook 10 EDIT: 6.4.11 pip


Question: class FigureManagerWebAgg(backend_bases.FigureManagerBase):    _toolbar2_class = ToolbarCls = NavigationToolbar2WebAgg    # This must be None to not break ipympl    _toolbar2_class = None    ToolbarCls = NavigationToolbar2WebAgg      def __init__(self, canvas, num):         self.web_sockets = set()


Question: The custom dictionary mapping instances or types to a legend     handler. This *handler_map* updates the default handler map     found at `matplotlib.legend.Legend.get_legend_handler_map`.<ins>draggable : bool, default: False    Whether the legend can be dragged with the mouse.</ins> """)

legend draggable as keyword <!--To help us understand and resolve your issue, please fill out the form to the best of your ability.--<!--You can feel free to delete the sections that do not apply.--There is not keyword to make legend draggable at creation <!--A short 1-2 sentences that succinctly describes the bug--Is there a code reason why one can not add a "draggable=True" keyword to the init function for Legend? This would be more handy than having to call it after legend creation. And, naively, it would seem simple to do. But maybe there is a reason why it would not work?


Question: title_fontproperties=None,  # properties for the legend title         alignment="center",       # control the alignment within the legend box         *,        ncol=1  # synonym for ncols (backward compatibility)        ncol=1,  # synonym for ncols (backward compatibility)        draggable=False  # whether the legend can be dragged with the mouse     ):         """         Parameters


Question: title_prop_fp.set_size(title_fontsize)          self.set_title(title, prop=title_prop_fp)         self._draggable = None        self.set_draggable(state=draggable)          # set the text color


Question: curr_stream[1].append(                     (item.x, item.ft_object.get_glyph_name(item.glyph_idx))                 )            # append the last entry            stream.append(curr_stream)            # append the last entry if exists            if curr_stream:                stream.append(curr_stream)          self.set_color(*gc.get_rgb())

[Bug]: Text label with empty line causes a "TypeError: cannot unpack non-iterable NoneType object" in PostScript backend When saving a figure with the PostScript backend, a happens if the figure contains a multi-line text label with an empty line (see example). $ ./venv/Scripts/python Traceback (most recent call last): File "C:\temp\matplotlibsaveps\", line 7, in <modulefigure.savefig('') File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 3272, in savefig (fname, kwargs) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 2338, in printfigure result = printmethod( File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 2204, in <lambdaprintmethod = (meth)(lambda args, kwargs: meth( File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\api\", line 410, in wrapper return func(innerargs, innerkwargs) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\backends\", line 869, in printps printer(fmt, outfile, dpi=dpi, dsccomments=dsccomments, File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\backends\", line 927, in printfigure (renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 74, in drawwrapper result = draw(artist, renderer, args, kwargs) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 51, in drawwrapper return draw(artist, renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 3069, in draw mimage.drawlistcompositingimages( File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 131, in drawlistcompositingimages a.draw(renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 51, in drawwrapper return draw(artist,


Question: curr_stream[1].append(                     (item.x, item.ft_object.get_glyph_name(item.glyph_idx))                 )            # append the last entry            stream.append(curr_stream)            # append the last entry if exists            if curr_stream:                stream.append(curr_stream)          self.set_color(*gc.get_rgb())

renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\axes\", line 3106, in draw mimage.drawlistcompositingimages( File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 131, in drawlistcompositingimages a.draw(renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 51, in drawwrapper return draw(artist, renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 1995, in draw (self, renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 51, in drawwrapper return draw(artist, renderer) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\", line 736, in draw textrenderer.drawtext(gc, x, y, cleanline, File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\backends\", line 248, in wrapper return meth(self, args, **kwargs) File "C:\temp\matplotlibsaveps\venv\lib\site-packages\matplotlib\backends\", line 673, in drawtext for psname, xsnames in stream: TypeError: cannot unpack non-iterable NoneType object The figure can be saved as without error. seems to happen if a text label or title contains a linebreak with an empty line works without error for other backends such as PNG, PDF, SVG, Qt works with matplotlib<=3.5.3 adding before line 669 of seems to fix the bug Windows 0 No response 13 No response pip


Question: if isinstance(tight_layout, dict):                 self.get_layout_engine().set(**tight_layout)         elif constrained_layout is not None:            self.set_layout_engine(layout='constrained')             if isinstance(constrained_layout, dict):                self.set_layout_engine(layout='constrained')                 self.get_layout_engine().set(**constrained_layout)            elif constrained_layout:                self.set_layout_engine(layout='constrained')         else:             # everything is None, so use default:             self.set_layout_engine(layout=layout)

[Bug]: Constrained layout UserWarning even when False When using layout settings such as or , a UserWarning is produced due to incompatibility with constrainedlayout, even if constrainedlayout = False. This was not the case in previous versions. The plot works fine but the warning is generated UserWarning: This figure was using a layout engine that is incompatible with subplotsadjust and/or tightlayout; not calling subplotsadjust. plt.subplotsadjust(wspace=0) no warning Warning disappears when constrainedlayout=False is removed OS/X 0 No response No response No response conda


Question: (https://stackoverflow.com/users/66549/doug) """ <ins>import itertools</ins> import numpy as np  from matplotlib import _api

stackplot should not change Axes cycler Usecase: I am producing various types of plots (some use rectangle collections, some regular plot-lines, some stacked plots) and wish to keep the colors synchronized across plot types for consistency and ease of comparison. While and support supplying a alias, stackplot throws a ValueError. For example: Originally posted by in


Question: labels = iter(labels)     if colors is not None:        axes.set_prop_cycle(color=colors)        colors = itertools.cycle(colors)    else:        colors = (axes._get_lines.get_next_color() for _ in y)      # Assume data passed has not been 'stacked', so stack it here.     # We'll need a float buffer for the upcoming calculations.


Question: stack += first_line      # Color between x = 0 and the first array.    color = axes._get_lines.get_next_color()     coll = axes.fill_between(x, first_line, stack[0, :],                             facecolor=color, label=next(labels, None),                             facecolor=next(colors), label=next(labels, None),                              **kwargs)     coll.sticky_edges.y[:] = [0]     r = [coll]      # Color between array i-1 and array i     for i in range(len(y) - 1):        color = axes._get_lines.get_next_color()         r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],                                   facecolor=color, label=next(labels, None),                                   facecolor=next(colors),                                   label=next(labels, None),                                    **kwargs))     return r


Question: # Store the value of gca so that we can set it back later on.         if cax is None:             if ax is None:                raise ValueError(                _api.warn_deprecated("3.6", message=(                     'Unable to determine Axes to steal space for Colorbar. '                    'Using gca(), but will raise in the future. '                     'Either provide the *cax* argument to use as the Axes for '                     'the Colorbar, provide the *ax* argument to steal space '                    'from it, or add *mappable* to an Axes.')                    'from it, or add *mappable* to an Axes.'))                ax = self.gca()             current_ax = self.gca()             userax = False             if (use_gridspec and isinstance(ax, SubplotBase)):

[Bug]: ValueError: Unable to determine Axes to steal space for Colorbar. started raising an error when trying to add a colorbar to : ValueError: Unable to determine Axes to steal space for Colorbar. Either provide the cax argument to use as the Axes for the Colorbar, provide the ax argument to steal space from it, or add mappable to an Axes. In : ! In : ! macOS 12.6 0 10 pip


Question: r"""     Container for colormaps that are known to Matplotlib by name. <del>    .. admonition:: Experimental       While we expect the API to be final, we formally mark it as       experimental for 3.5 because we want to keep the option to still adapt       the API for 3.6 should the need arise.</del>     The universal registry instance is `matplotlib.colormaps`. There should be     no need for users to instantiate `.ColormapRegistry` themselves.

[ENH]: Default to call ? While addressing the deprecation in 3.6: I noticed that isn't directly migrate-able It appears from the source that defaults to so it would be nice if could default to that as well. Otherwise, it would be nice if this was better documented.


Question: "colormap.")         self._cmaps.pop(name, None) <ins>    def get_cmap(self, cmap):        """        Return a color map specified through *cmap*.        Parameters        ----------        cmap : str or `~matplotlib.colors.Colormap` or None            - if a `.Colormap`, return it            - if a string, look it up in ``mpl.colormaps``            - if None, return the Colormap defined in :rc:`image.cmap`        Returns        -------        Colormap        """        # get the default color map        if cmap is None:            return self[mpl.rcParams["image.cmap"]]        # if the user passed in a Colormap, simply return it        if isinstance(cmap, colors.Colormap):            return cmap        if isinstance(cmap, str):            _api.check_in_list(sorted(_colormaps), cmap=cmap)            # otherwise, it must be a string so look it up            return self[cmap]        raise TypeError(            'get_cmap expects None or an instance of a str or Colormap . ' +            f'you passed {cmap!r} of type {type(cmap)}'        )</ins>  # public access to the colormaps should be via `matplotlib.colormaps`. For now, # we still create the registry here, but that should stay an implementation


Question: # pyplot. get_cmap = _api.deprecated(     '3.6',    name='get_cmap', pending=True, alternative="``matplotlib.colormaps[name]``"    name='get_cmap',    pending=True,    alternative=(        "``matplotlib.colormaps[name]`` " +        "or ``matplotlib.colormaps.get_cmap(obj)``"    ) )(_get_cmap)


Question: """     Ensure that we have a `.Colormap` object. <ins>    For internal use to preserve type stability of errors.</ins>     Parameters     ----------     cmap : None, str, Colormap


Question: Returns     -------     Colormap<ins></ins>     """     if isinstance(cmap, colors.Colormap):         return cmap


Question: x0 = cbook._safe_first_finite(x0)             except (TypeError, IndexError, KeyError):                 pass            except StopIteration:                # this means we found no finite element, fall back to first                # element unconditionally                x0 = cbook.safe_first_element(x0)              try:                 x = cbook._safe_first_finite(xconv)             except (TypeError, IndexError, KeyError):                 x = xconv            except StopIteration:                # this means we found no finite element, fall back to first                # element unconditionally                x = cbook.safe_first_element(xconv)              delist = False             if not np.iterable(dx):

[Bug]: raises for all-nan data on matplotlib 3.6.1 raises an exception in 3.6.1 when passed only nan data. This irrevocably breaks seaborn's histogram function (which draws and then removes a "phantom" bar to trip the color cycle). On 3.6.0 this returns a with one Rectangle, having for and . I assume it's related to this bullet in the release notes: Fix barplot being empty when first element is NaN But I don't know the context for it to investigate further (could these link to PRs?) Further debugging: So it's about the x position specifically. Macos 1 No response No response No response pip


Question: # Get all vertices on the path         # Loop through each segment to get extrema for Bezier curve sections         vertices = []        for curve, code in p.iter_bezier():        for curve, code in p.iter_bezier(simplify=False):             # Get distance along the curve of any extrema             _, dzeros = curve.axis_aligned_extrema()             # Calculate vertices of start, end and any extrema in between

[Bug]: density not auto-scaled when using histtype='step' I need to plot a histogram of some data (generated by in binary format) from my work using the function. I noted that the histogram's density axis (when setting ) is not automatically adjusted to fit the whole histogram. I played with different combinations of parameters, and noted that the densities changes if you rescale the whole data array, which is counterintuitive as rescaling the data should only affect the x-axis values. I noted that if you set , the issue will occur, but is otherwise okay for other s. I started a github repo for testing this issue . The file is the data generated from my program. Here's the histograms generated using some simulated data. You can play with the and parameters in the code to see the differences. When , I got ! When , sometimes the randomised array would lead to identical left and right panel ... ! No response OS/X 0 No response 10.4 No response pip


Question: Defines the relative widths of the columns. Each column gets a             relative width of ``width_ratios[i] / sum(width_ratios)``.             If not given, all columns will have the same width.  Equivalent            to ``gridspec_kw={'width_ratios': [...]}``.            to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested            layouts, this argument applies only to the outer layout.          height_ratios : array-like of length *nrows*, optional             Defines the relative heights of the rows. Each row gets a             relative height of ``height_ratios[i] / sum(height_ratios)``.             If not given, all rows will have the same height. Equivalent            to ``gridspec_kw={'height_ratios': [...]}``.            to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested            layouts, this argument applies only to the outer layout.          subplot_kw : dict, optional             Dictionary with keywords passed to the `.Figure.add_subplot` call

[Bug]: Error using widthratios with nested mosaic in subplotmosaic() plt.subplotmosaic() fails with a confusing error message when passing widthratios (or heightratios) with a nested list mosaic, unless all outer and inner mosaics have the same number of columns (or rows). ! From what I can tell, this happens because the layout is built recursively, passing the same gridspeckw to subgridspec() at each level of nesting. I realize that the use of widthratios / heightratios / gridspeckw with nested list mosaics could get complicated, but it would be nice to be able to at least specify them for the outer list, or in some other way implement this feature for nested list layouts. If not, maybe include a helpful error message that explains this limitation so the user doesn't think they have specified the wrong number of ratios. Windows 10 0 QtAgg 10 No response_ conda


Question: gridspec_kw : dict, optional             Dictionary with keywords passed to the `.GridSpec` constructor used            to create the grid the subplots are placed on.            to create the grid the subplots are placed on. In the case of            nested layouts, this argument applies only to the outer layout.            For more complex layouts, users should use `.Figure.subfigures`            to create the nesting.          empty_sentinel : object, optional             Entry in the layout to mean "leave this space empty".  Defaults


Question: # recursively add the nested mosaic                     rows, cols = nested_mosaic.shape                     nested_output = _do_layout(                        gs[j, k].subgridspec(rows, cols, **gridspec_kw),                        gs[j, k].subgridspec(rows, cols),                         nested_mosaic,                         *_identify_keys_and_nested(nested_mosaic)                     )


Question: UTC = datetime.timezone.utc  <ins>@_api.caching_module_getattrclass __getattr__:    JULIAN_OFFSET = _api.deprecated("3.7")(property(lambda self: 1721424.5))    # Julian date at 0000-12-31    # note that the Julian day epoch is achievable w/    # np.datetime64('-4713-11-24T12:00:00'); datetime64 is proleptic    # Gregorian and BC has a one-year offset.  So    # np.datetime64('0000-12-31') - np.datetime64('-4713-11-24T12:00') =    # 1721424.5    # Ref: https://en.wikipedia.org/wiki/Julian_day</ins> def _get_tzinfo(tz=None):     """     Generate tzinfo from a string or return tzinfo. If None,

[Doc]: document and ? These two methods have a decent doc-string, but are not in the documentation. They were 2006-08-10 Maybe add them to the documentation? It would make sense to add them towards the end of the page and include those and all functions after the last Locator in a new subsection "Miscellaneous date functions" or something. Edit: looking at the source, it is not really clear why they are not there...


Question: # Time-related constants. EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal()) # EPOCH_OFFSET is not used by matplotlib<del>JULIAN_OFFSET = 1721424.5  # Julian date at 0000-12-31# note that the Julian day epoch is achievable w/# np.datetime64('-4713-11-24T12:00:00'); datetime64 is proleptic# Gregorian and BC has a one-year offset.  So# np.datetime64('0000-12-31') - np.datetime64('-4713-11-24T12:00') = 1721424.5# Ref: https://en.wikipedia.org/wiki/Julian_day</del> MICROSECONDLY = SECONDLY + 1 HOURS_PER_DAY = 24. MIN_PER_HOUR = 60.


Question: return d if iterable else d[0]  <ins>@_api.deprecated("3.7")</ins> def julian2num(j):     """     Convert a Julian date (or sequence) to a Matplotlib date (or sequence).


Question: ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.     # Julian offset defined above is relative to 0000-12-31, but we need     # relative to our current epoch:    dt = JULIAN_OFFSET - ep0 + ep    dt = __getattr__("JULIAN_OFFSET") - ep0 + ep     return np.subtract(j, dt)  # Handles both scalar & nonscalar j.  @_api.deprecated("3.7") def num2julian(n):     """     Convert a Matplotlib date (or sequence) to a Julian date (or sequence).


Question: ep0 = np.datetime64('0000-12-31T00:00:00', 'h').astype(float) / 24.     # Julian offset defined above is relative to 0000-12-31, but we need     # relative to our current epoch:    dt = JULIAN_OFFSET - ep0 + ep    dt = __getattr__("JULIAN_OFFSET") - ep0 + ep     return np.add(n, dt)  # Handles both scalar & nonscalar j.


Question: # pickling.         self._canvas_callbacks = cbook.CallbackRegistry(             signals=FigureCanvasBase.events)<del>        self._button_pick_id = self._canvas_callbacks._connect_picklable(            'button_press_event', self.pick)        self._scroll_pick_id = self._canvas_callbacks._connect_picklable(            'scroll_event', self.pick)</del>         connect = self._canvas_callbacks._connect_picklable         self._mouse_key_ids = [             connect('key_press_event', backend_bases._key_handler),

[Bug]: pick events do not forward mouseevent-key on Linux Somehow on keyboard-buttons are not forwarded with ... on everything works as expected. When clicking on one of the datapoints while pressing the buttons and the following happens: on Windows I get: on CentOS Linux I get: The same output for both OS Windows / Linux CentOS7 1 Qt5Agg 13 conda


Question: connect('scroll_event', backend_bases._mouse_handler),             connect('motion_notify_event', backend_bases._mouse_handler),         ]<ins>        self._button_pick_id = connect('button_press_event', self.pick)        self._scroll_pick_id = connect('scroll_event', self.pick)</ins>          if figsize is None:             figsize = mpl.rcParams['figure.figsize']


Question: import logging import os from pathlib import Pathimport sys import warnings if sys.version_info >= (3, 10):    import importlib.resources as importlib_resourceselse:    # Even though Py3.9 has importlib.resources, it doesn't properly handle    # modules added in sys.path.    import importlib_resources import matplotlib as mplfrom matplotlib import _api, _docstring, rc_params_from_file, rcParamsDefaultfrom matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault  _log = logging.getLogger(__name__)

Document how to distribute style files in python packages <!--To help us understand and resolve your issue, please fill out the form to the best of your ability.--<!--You can feel free to delete the sections that do not apply.--Style files (actually, style dicts) can be distributed as python packages, as discussed e.g. in This has the advantage of being relatively easy to do and that it works "as is" for essentially all versions of matplotlib (if your matplotlib is too old to have (pre 1.5...) you can still use ). In today's call we agreed that this approach should be documented and that a template package (similar to ) could be created. It was also pointed out during the call that this approach makes it easy to distribute colormaps together with the style, or add any additional custom logic; this may be worth documenting too.


Question: "directly use the seaborn API instead.")  <del>def _remove_blacklisted_style_params(d, warn=True):    o = {}    for key in d:  # prevent triggering RcParams.__getitem__('backend')        if key in STYLE_BLACKLIST:            if warn:                _api.warn_external(                    f"Style includes a parameter, {key!r}, that is not "                    "related to style.  Ignoring this parameter.")        else:            o[key] = d[key]    return odef _apply_style(d, warn=True):    mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))</del> @_docstring.Substitution(     "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower))) )


Question: Parameters     ----------     style : str, dict, Path or list        A style specification. Valid options are:         +------+-------------------------------------------------------------+        | str  | The name of a style or a path/URL to a style file. For a    |        |      | list of available style names, see `.style.available`.      |        +------+-------------------------------------------------------------+        | dict | Dictionary with valid key/value pairs for                   |        |      | `matplotlib.rcParams`.                                      |        +------+-------------------------------------------------------------+        | Path | A path-like object which is a path to a style file.         |        +------+-------------------------------------------------------------+        | list | A list of style specifiers (str, Path or dict) applied from |        |      | first to last in the list.                                  |        +------+-------------------------------------------------------------+        A style specification.        - If a str, this can be one of the style names in `.style.available`          (a builtin style or a style installed in the user library path).          This can also be a dotted name of the form "package.style_name"; in          that case, "package" should be an importable Python package name,          e.g. at ``/path/to/package/__init__.py``; the loaded style file is          ``/path/to/package/style_name.mplstyle``.  (Style files in          subpackages are likewise supported.)          This can also be the path or URL to a style file, which gets loaded          by `.rc_params_from_file`.        - If a dict, this is a mapping of key/value pairs for `.rcParams`.        - If a Path, this is the path to a style file, which gets loaded by          `.rc_params_from_file`.        - If a list, this is a list of style specifiers (str, Path or dict),          which get applied from first to last in the list.      Notes     -----


Question: style_alias = {'mpl20': 'default', 'mpl15': 'classic'}     def fix_style(s):        if isinstance(s, str):            s = style_alias.get(s, s)            if s in _DEPRECATED_SEABORN_STYLES:    for style in styles:        if isinstance(style, str):            style = style_alias.get(style, style)            if style in _DEPRECATED_SEABORN_STYLES:                 _api.warn_deprecated("3.6", message=_DEPRECATED_SEABORN_MSG)                s = _DEPRECATED_SEABORN_STYLES[s]        return s    for style in map(fix_style, styles):        if not isinstance(style, (str, Path)):            _apply_style(style)        elif style == 'default':            # Deprecation warnings were already handled when creating            # rcParamsDefault, no need to reemit them here.            with _api.suppress_matplotlib_deprecation_warning():                _apply_style(rcParamsDefault, warn=False)        elif style in library:            _apply_style(library[style])        else:                style = _DEPRECATED_SEABORN_STYLES[style]            if style == "default":                # Deprecation warnings were already handled when creating                # rcParamsDefault, no need to reemit them here.                with _api.suppress_matplotlib_deprecation_warning():                    # don't trigger RcParams.__getitem__('backend')                    style = {k: rcParamsDefault[k] for k in rcParamsDefault                             if k not in STYLE_BLACKLIST}            elif style in library:                style = library[style]            elif "." in style:                pkg, _, name = style.rpartition(".")                try:                    path = (importlib_resources.files(pkg)                            / f"{name}.{STYLE_EXTENSION}")                    style = _rc_params_in_file(path)                except (ModuleNotFoundError, IOError) as exc:                    # There is an ambiguity whether a dotted name refers to a                    # package.style_name or to a dotted file path.  Currently,                    # we silently try the first form and then the second one;                    # in the future, we may consider forcing file paths to                    # either use Path objects or be prepended with "./" and use                    # the slash as marker for file paths.                    pass        if isinstance(style, (str, Path)):             try:                rc = rc_params_from_file(style, use_default_template=False)                _apply_style(rc)                style = _rc_params_in_file(style)             except IOError as err:                 raise IOError(                    "{!r} not found in the style library and input is not a "                    "valid URL or path; see `style.available` for list of "                    "available styles".format(style)) from err                    f"{style!r} is not a valid package style, path of style "                    f"file, URL of style file, or library style name (library "                    f"styles are listed in `style.available`)") from err        filtered = {}        for k in style:  # don't trigger RcParams.__getitem__('backend')            if k in STYLE_BLACKLIST:                _api.warn_external(                    f"Style includes a parameter, {k!r}, that is not "                    f"related to style.  Ignoring this parameter.")            else:                filtered[k] = style[k]        mpl.rcParams.update(filtered)   @contextlib.contextmanager


Question: styles = dict()     for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"):         with warnings.catch_warnings(record=True) as warns:            styles[path.stem] = rc_params_from_file(                path, use_default_template=False)            styles[path.stem] = _rc_params_in_file(path)         for w in warns:             _log.warning('In %s: %s', path, w.message)     return stylesdiff --git a/setup.py b/setup.py-- a/setup.py++ b/setup.py


Question: os.environ.get("CIBUILDWHEEL", "0") != "1"         ) else []     ),    extras_require={        ':python_version<"3.10"': [            "importlib-resources>=3.2.0",        ],    },     use_scm_version={         "version_scheme": "release-branch-semver",         "local_scheme": "node-and-date",diff --git a/tutorials/introductory/customizing.py b/tutorials/introductory/customizing.py-- a/tutorials/introductory/customizing.py++ b/tutorials/introductory/customizing.py


Question: There are three ways to customize Matplotlib:     1. :ref:`Setting rcParams at runtime<customizing-with-dynamic-rc-settings>`.    2. :ref:`Using style sheets<customizing-with-style-sheets>`.    3. :ref:`Changing your matplotlibrc file<customizing-with-matplotlibrc-files>`.1. :ref:`Setting rcParams at runtime<customizing-with-dynamic-rc-settings>`.2. :ref:`Using style sheets<customizing-with-style-sheets>`.3. :ref:`Changing your matplotlibrc file<customizing-with-matplotlibrc-files>`.  Setting rcParams at runtime takes precedence over style sheets, style sheets take precedence over :file:`matplotlibrc` files.


Question: #    >>> import matplotlib.pyplot as plt #    >>> plt.style.use('./images/presentation.mplstyle') #<ins>## Distributing styles# -------------------## You can include style sheets into standard importable Python packages (which# can be e.g. distributed on PyPI).  If your package is importable as# ``import mypackage``, with a ``mypackage/__init__.py`` module, and you add# a ``mypackage/presentation.mplstyle`` style sheet, then it can be used as# ``plt.style.use("mypackage.presentation")``.  Subpackages (e.g.# ``dotted.package.name``) are also supported.#</ins> # Alternatively, you can make your style known to Matplotlib by placing # your ``<style-name>.mplstyle`` file into ``mpl_configdir/stylelib``.  You # can then load your custom style sheet with a call to


Question: 'toolbar', 'timezone', 'figure.max_open_warning',     'figure.raise_window', 'savefig.directory', 'tk.window_focus',     'docstring.hardcopy', 'date.epoch'}<ins>_DEPRECATED_SEABORN_STYLES = {    s: s.replace("seaborn", "seaborn-v0_8")    for s in [        "seaborn",        "seaborn-bright",        "seaborn-colorblind",        "seaborn-dark",        "seaborn-darkgrid",        "seaborn-dark-palette",        "seaborn-deep",        "seaborn-muted",        "seaborn-notebook",        "seaborn-paper",        "seaborn-pastel",        "seaborn-poster",        "seaborn-talk",        "seaborn-ticks",        "seaborn-white",        "seaborn-whitegrid",    ]}_DEPRECATED_SEABORN_MSG = (    "The seaborn styles shipped by Matplotlib are deprecated since %(since)s, "    "as they no longer correspond to the styles shipped by seaborn. However, "    "they will remain available as 'seaborn-v0_8-<style>'. Alternatively, "    "directly use the seaborn API instead.")</ins>   def _remove_blacklisted_style_params(d, warn=True):

[Bug]: Setting ['seaborn-colorblind'] result in key error on matplotlib v3.6.1 I have code that executes: Using version 3.4.3 of matplotlib, this works fine. I recently installed my code on a machine with matplotlib version 3.6.1 and upon importing my code, this generated a key error for line saying "seaborn-colorblind" was a bad key. Traceback (most recent call last): KeyError: 'seaborn-colorblind' seaborn-colorblind should be set as the matplotlib library style and I should be able to continue plotting with that style. Bug occurs with matplotlib version 3.6.1 Bug does not occur with matplotlib version 3.4.3 Tested on MacOSX and Ubuntu (same behavior on both) OS/X 1 MacOSX 7 No response_ pip


Question: def fix_style(s):         if isinstance(s, str):             s = style_alias.get(s, s)            if s in [                "seaborn",                "seaborn-bright",                "seaborn-colorblind",                "seaborn-dark",                "seaborn-darkgrid",                "seaborn-dark-palette",                "seaborn-deep",                "seaborn-muted",                "seaborn-notebook",                "seaborn-paper",                "seaborn-pastel",                "seaborn-poster",                "seaborn-talk",                "seaborn-ticks",                "seaborn-white",                "seaborn-whitegrid",            ]:                _api.warn_deprecated(                    "3.6", message="The seaborn styles shipped by Matplotlib "                    "are deprecated since %(since)s, as they no longer "                    "correspond to the styles shipped by seaborn. However, "                    "they will remain available as 'seaborn-v0_8-


Question: return main_dict  class _StyleLibrary(dict):    def __getitem__(self, key):        if key in _DEPRECATED_SEABORN_STYLES:            _api.warn_deprecated("3.6", message=_DEPRECATED_SEABORN_MSG)            key = _DEPRECATED_SEABORN_STYLES[key]        return dict.__getitem__(self, key) # Load style library # ================== _base_library = read_style_directory(BASE_LIBRARY_PATH)library = Nonelibrary = _StyleLibrary() available = []   def reload_library():     """Reload the style library."""    global library    library = update_user_library(_base_library)    library.clear()    library.update(update_user_library(_base_library))     available[:] = sorted(library.keys())


Question: other limits, you should set the limits explicitly after setting the         ticks.         """<ins>        if labels is None and kwargs:            raise ValueError('labels argument cannot be None when '                             'kwargs are passed')</ins>         result = self._set_tick_locations(ticks, minor=minor)         if labels is not None:             self.set_ticklabels(labels, minor=minor, **kwargs)

[ENH]: Axes.setxticks/Axis.setticks only validates kwargs if ticklabels are set, but they should Per the doc of : This means that in e.g. , the incorrect silently do nothing; they are not even validated (because has not been passed). We should at least check that are valid Text properties in all cases; we could even consider making any kwargs an error if is not set.


Question: raise ValueError("GridSpec.subplots() only works for GridSpecs "                              "created with a parent figure")         if isinstance(sharex, bool):        if not isinstance(sharex, str):             sharex = "all" if sharex else "none"        if isinstance(sharey, bool):        if not isinstance(sharey, str):             sharey = "all" if sharey else "none"        # This check was added because it is very easy to type        # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.        # In most cases, no error will ever occur, but mysterious behavior        # will result because what was intended to be the subplot index is        # instead treated as a bool for sharex.  This check should go away        # once sharex becomes kwonly.        if isinstance(sharex, Integral):            _api.warn_external(                "sharex argument to subplots() was an integer.  Did you "                "intend to use subplot() (without 's')?")        _api.check_in_list(["all", "row", "col", "none"],        _api.check_in_list(["all", "row", "col", "none", False, True],                            sharex=sharex, sharey=sharey)         if subplot_kw is None:             subplot_kw = {}

[Bug]: sharex and sharey don't accept 0 and 1 as bool values When using or in place of or in or arguments of an error is raised. We get the following error : Note that using instead of produces the same error (albeit with the following warning : but this is expected and not part of the present issue) I expected values 1 and 0 to be understood as bool. Suggested fix : Maybe not accepting 1 or 0 was done on purpose, but I did not find it very clear from the error message as and are accepted but not listed. I am happy to chat about an other fix, if this one doesn't do the trick. I can also create a PR in case you think this fix is good enough ! Linux 5.10.0-19-amd64 SMP Debian 5.10.149-2 600+g0b6d3703ff TkAgg 10.0 Not applicable git checkout


Question: # severe failure => one may appreciate a verbose feedback.                     raise ValueError(                         f"'c' argument must be a color, a sequence of colors, "                        f"or a sequence of numbers, not {c}") from err                        f"or a sequence of numbers, not {c!r}") from err             else:                 if len(colors) not in (0, 1, xsize):                     # NB: remember that a single color is also acceptable.

[ENH]: Use instead of in the error message I mistakenly supplied as the argument for [matplitlib claimed for illegal color name like this: I was not aware that the argument actually contained a trailing newline so I was very confused. The error message would be nicer if it outputs user's input via . For example, in this case the error message can be easily replced with: so that we may now get an easy-to-troubleshoot error like this: This kind of improvement can be applied to many other places.


Question: "colors", "linestyles"])     @_docstring.dedent_interpd     def eventplot(self, positions, orientation='horizontal', lineoffsets=1,                  linelengths=1, linewidths=None, colors=None,                  linelengths=1, linewidths=None, colors=None, alpha=None,                   linestyles='solid', **kwargs):         """         Plot identical parallel lines at the given positions.

eventplot: allow a list of alpha channels as in the case with colors I'm not sure if it's a bug or a feature. It's both. works while throws an error matplotlib v3.3.3 Python 3.7.6


Question: If *positions* is 2D, this can be a sequence with length matching             the length of *positions*. <ins>        alpha : float or array-like, default: 1            The alpha blending value(s), between 0 (transparent) and 1            (opaque).            If *positions* is 2D, this can be a sequence with length matching            the length of *positions*.</ins>         linestyles : str or tuple or list of such values, default: 'solid'             Default is 'solid'. Valid strings are ['solid', 'dashed',             'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples


Question: Notes         -----        For *linelengths*, *linewidths*, *colors*, and *linestyles*, if only        a single value is given, that value is applied to all lines.  If an        For *linelengths*, *linewidths*, *colors*, *alpha* and *linestyles*, if        only a single value is given, that value is applied to all lines. If an         array-like is given, it must have the same length as *positions*, and         each value will be applied to the corresponding row of the array.


Question: linewidths = [linewidths]         if not np.iterable(colors):             colors = [colors]<ins>        if not np.iterable(alpha):            alpha = [alpha]</ins>         if hasattr(linestyles, 'lower') or not np.iterable(linestyles):             linestyles = [linestyles]


Question: if len(linewidths) == 1:             linewidths = np.tile(linewidths, len(positions))         if len(colors) == 1:            colors = list(colors)            colors = colors * len(positions)            colors = list(colors) * len(positions)        if len(alpha) == 1:            alpha = list(alpha) * len(positions)         if len(linestyles) == 1:             linestyles = [linestyles] * len(positions)


Question: if len(colors) != len(positions):             raise ValueError('colors and positions are unequal sized '                              'sequences')        if len(alpha) != len(positions):            raise ValueError('alpha and positions are unequal sized '                             'sequences')         if len(linestyles) != len(positions):             raise ValueError('linestyles and positions are unequal sized '                              'sequences')          colls = []        for position, lineoffset, linelength, linewidth, color, linestyle in \        for position, lineoffset, linelength, linewidth, color, alpha_, \            linestyle in \                 zip(positions, lineoffsets, linelengths, linewidths,                    colors, linestyles):                    colors, alpha, linestyles):             coll = mcoll.EventCollection(position,                                          orientation=orientation,                                          lineoffset=lineoffset,                                          linelength=linelength,                                          linewidth=linewidth,                                          color=color,                                         alpha=alpha_,                                          linestyle=linestyle)             self.add_collection(coll, autolim=False)             coll._internal_update(kwargs)diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py-- a/lib/matplotlib/pyplot.py++ b/lib/matplotlib/pyplot.py


Question: @_copy_docstring_and_deprecators(Axes.eventplot) def eventplot(         positions, orientation='horizontal', lineoffsets=1,        linelengths=1, linewidths=None, colors=None,        linelengths=1, linewidths=None, colors=None, alpha=None,         linestyles='solid', *, data=None, **kwargs):     return gca().eventplot(         positions, orientation=orientation, lineoffsets=lineoffsets,         linelengths=linelengths, linewidths=linewidths, colors=colors,        linestyles=linestyles,        alpha=alpha, linestyles=linestyles,         **({"data": data} if data is not None else {}), **kwargs)


Question: descent = max(d for h, d in hd_list)         height = height_descent + descent         offsets = [0. for h, d in hd_list]    elif align in ["left", "top"]:    elif align in ["left", "bottom"]:         descent = 0.         offsets = [d for h, d in hd_list]    elif align in ["right", "bottom"]:    elif align in ["right", "top"]:         descent = 0.         offsets = [height - h + d for h, d in hd_list]     elif align == "center":

[Bug]: in is reversed For the parameter in , the options and seems reversed ! ! No response No response 2 No response No response No response No response


Question: if len(args) == 1:             C = np.asanyarray(args[0])            nrows, ncols = C.shape            nrows, ncols = C.shape[:2]             if shading in ['gouraud', 'nearest']:                 X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows))             else:

[Bug]: integer colours for pcolorfast / quadmesh I get an error when passing a byte/integer array to pcolorfast to code the colors as RGBA. It also fails when data type is a plot in in some bluish colour fixes: 1) in , line 321: should be replaced by to allow for unsigned int values as well 2) in line 343: should be replaced by a test including - for 'i' and 'u'. It may be sufficient to comment it out as a quick fix as it is definitively more broken having it in. even with this it does not quite work 5.15.13-200.fc35.x86_64 1 gtk3 10.1 0 pip


Question: X = X.data  # strip mask as downstream doesn't like it...                 if isinstance(Y, np.ma.core.MaskedArray):                     Y = Y.data            nrows, ncols = C.shape            nrows, ncols = C.shape[:2]         else:             raise _api.nargs_error(funcname, takes="1 or 3", given=len(args))


Question: Parameters         ----------        C : 2D array-like            The color-mapped values.  Color-mapping is controlled by *cmap*,            *norm*, *vmin*, and *vmax*.        C : array-like            The mesh data. Supported array shapes are:            - (M, N) or M*N: a mesh with scalar data. The values are mapped to              colors using normalization and a colormap. See parameters *norm*,              *cmap*, *vmin*, *vmax*.            - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).            - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),              i.e. including transparency.            The first two dimensions (M, N) define the rows and columns of            the mesh data.          X, Y : array-like, optional             The coordinates of the corners of quadrilaterals of a pcolormesh::


Question: X, Y, C, shading = self._pcolorargs('pcolormesh', *args,                                             shading=shading, kwargs=kwargs)         coords = np.stack([X, Y], axis=-1)        # convert to one dimensional array        C = C.ravel()        # convert to one dimensional array, except for 3D RGB(A) arrays        if C.ndim != 3:            C = C.ravel()          kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap'])


Question: if style == "quadmesh":             # data point in each cell is value at lower left corner             coords = np.stack([x, y], axis=-1)            if np.ndim(C) == 2:                qm_kwargs = {"array": np.ma.ravel(C)}            elif np.ndim(C) == 3:                qm_kwargs = {"color": np.ma.reshape(C, (-1, C.shape[-1]))}            else:            if np.ndim(C) not in {2, 3}:                 raise ValueError("C must be 2D or 3D")             collection = mcoll.QuadMesh(                coords, **qm_kwargs,                coords, array=C,                 alpha=alpha, cmap=cmap, norm=norm,                 antialiased=False, edgecolors="none")             self.add_collection(collection, autolim=False)diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py-- a/lib/matplotlib/collections.py++ b/lib/matplotlib/collections.py


Question: Parameters         ----------        A : (M, N) array-like or M*N array-like        A : array-like            The mesh data. Supported array shapes are:            - (M, N) or M*N: a mesh with scalar data. The values are mapped to              colors using normalization and a colormap. See parameters *norm*,              *cmap*, *vmin*, *vmax*.            - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).            - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),              i.e. including transparency.             If the values are provided as a 2D grid, the shape must match the             coordinates grid. If the values are 1D, they are reshaped to 2D.             M, N follow from the coordinates grid, where the coordinates grid


Question: if len(shape) == 1:                 if shape[0] != (h*w):                     faulty_data = True            elif shape != (h, w):                if np.prod(shape) == (h * w):            elif shape[:2] != (h, w):                if np.prod(shape[:2]) == (h * w):                     misshapen_data = True                 else:                     faulty_data = True            elif len(shape) == 3 and shape[2] not in {3, 4}:                # 3D data must be RGB(A) (h, w, [3,4])                # the (h, w) check is taken care of above                raise ValueError(                    f"For X ({width}) and Y ({height}) with "                    f"{self._shading} shading, the expected shape of "                    f"A with RGB(A) colors is ({h}, {w}, [3 or 4]), not "                    f"{A.shape}")              if misshapen_data:                 raise ValueError(


Question: self._get_patches_for_fill = _process_plot_var_args(self, 'fill')          self._gridOn = mpl.rcParams['axes.grid']        self._children = []        old_children, self._children = self._children, []        for chld in old_children:            chld.axes = chld.figure = None         self._mouseover_set = _OrderedSet()         self.child_axes = []         self._current_image = None  # strictly for pyplot via _sci, _gci

cla(), clf() should unset the and attributes of deparented artists mpl2.0b3: Removing an artist from its axes unsets its attribute, but clearing the axes does not do so.


Question: self._renderer = renderer         if not self.get_visible() or not self._check_xy(renderer):             return<ins>        renderer.open_group(self.__class__.__name__, gid=self.get_gid())</ins>         self.update_positions(renderer)         if self.arrow_patch is not None:             if self.arrow_patch.figure is None and self.figure is not None:

AnnotationBbox gid not passed to renderer Hi, I'm creating matplotlib figures that contain images using AnnotationBbox (following the examples here ) and my aim is to set the artist gid associated with each image so I can access them later when saved to an svg. I can use setgid but when I save to an svg, the gid label for the images are not included. A similar issue has been discussed here , where a solution was applied for all known instances of missing gid's. Could it be that the AnnotationBbox artist has been missed by this fix? Example code: which prints: but produces an svg file that contains the image with no gid label (attached here as a txt file since svg is not supported): stock image used: ! Versions <!--Please specify your platform and versions of the relevant libraries you are using:--matplotlib version 3.3.4 python version 3.7.7 <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--Thanks, Lauren


Question: self.arrow_patch.draw(renderer)         self.patch.draw(renderer)         self.offsetbox.draw(renderer)<ins>        renderer.close_group(self.__class__.__name__)</ins>         self.stale = False


Question: """=================================Ways to set a color's alpha value=================================Compare setting alpha by the *alpha* keyword argument and by one of the Matplotlib colorformats. Often, the *alpha* keyword is the only tool needed to add transparency to acolor. In some cases, the *(matplotlib_color, alpha)* color format provides an easy wayto fine-tune the appearance of a Figure."""import matplotlib.pyplot as pltimport numpy as np# Fixing random state for reproducibility.np.random.seed(19680801)fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))x_values = [n for n in range(20)]y_values = np.random.randn(20)facecolors = ['green' if y > 0 else 'red' for y in y_values]edgecolors = facecolorsax1.bar(x_values, y_values, color=facecolors, edgecolor=edgecolors, alpha=0.5)ax1.set_title("Explicit 'alpha' keyword value\nshared by all bars and edges")# Normalize y values to get distinct face alpha values.abs_y = [abs(y) for y in y_values]face_alphas = [n / max(abs_y) for n in abs_y]edge_alphas = [1 - alpha for alpha in face_alphas]colors_with_alphas = list(zip(facecolors, face_alphas))edgecolors_with_alphas = list(zip(edgecolors, edge_alphas))ax2.bar(x_values, y_values, color=colors_with_alphas,        edgecolor=edgecolors_with_alphas)ax2.set_title('Normalized alphas for\neach bar and each edge')plt.show()# %%## .. admonition:: References##    The use of the following functions, methods, classes and modules is shown#    in this example:##    - `matplotlib.axes.Axes.bar`#    - `matplotlib.pyplot.subplots`diff --git a/galleries/users_explain/colors/colors.py b/galleries/users_explain/colors/colors.py-- a/galleries/users_explain/colors/colors.py++ b/galleries/users_explain/colors/colors.py

[ENH]: set facecolor and edgecolor alpha separately I like making diagrams where my patch edge is solid but the fill is semi-transparent - in my case usually to fade out the color, but it's also useful to emphasize boundaries ! Since alpha applies to the whole patch, the way I do this now is by converting my HTML colors into RGBs and appending an A ETA: apparently I could also just do Allow alpha to take a tuple for patch methods. As an example of prior art, we allow vectorized/separable alphas in imshow as of


Question: |           to black if cycle does not |                                      | |           include color.             |                                      | +--------------------------------------+--------------------------------------+| Tuple of one of the above color      | - ``('green', 0.3)``                 || formats and an alpha float.          | - ``('#f00', 0.9)``                  |+--------------------------------------+--------------------------------------+  .. _xkcd color survey: https://xkcd.com/color/rgb/ diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py-- a/lib/matplotlib/colors.py++ b/lib/matplotlib/colors.py


Question: *alpha* is ignored for the color value ``"none"`` (case-insensitive),     which always maps to ``(0, 0, 0, 0)``.     """<ins>    if isinstance(c, tuple) and len(c) == 2:        if alpha is None:            c, alpha = c        else:            c = c[0]    if alpha is not None and not 0 <= alpha <= 1:        raise ValueError("'alpha' must be between 0 and 1, inclusive")</ins>     orig_c = c     if c is np.ma.masked:         return (0., 0., 0., 0.)


Question: (n, 4) array of RGBA colors,  where each channel (red, green, blue,         alpha) can assume values between 0 and 1.     """<ins>    if isinstance(c, tuple) and len(c) == 2:        if alpha is None:            c, alpha = c        else:            c = c[0]</ins>     # Special-case inputs that are already arrays, for performance.  (If the     # array has the wrong kind or shape, raise the error during one-at-a-time     # conversion.)


Question: return np.array([to_rgba(c, a) for a in alpha], float)         else:             return np.array([to_rgba(c, alpha)], float)    except (ValueError, TypeError):    except TypeError:         pass    except ValueError as e:        if e.args == ("'alpha' must be between 0 and 1, inclusive", ):            # ValueError is from _to_rgba_no_colorcycle().            raise e     if isinstance(c, str):         raise ValueError(f"{c!r} is not a valid color value.")


Question: """         Process args and kwargs.         """        if isinstance(args[0], QuadContourSet):        if args and isinstance(args[0], QuadContourSet):             if self.levels is None:                 self.levels = args[0].levels             self.zmin = args[0].zmin

[Bug]: contour raises IndexError if Z is specified as keyword argument raises when is specified as . <img width="1675" alt="Screen Shot 2022-12-15 at 8 23 39 PM" src="https://user-"<img width="713" alt="Screen Shot 2022-12-15 at 8 24 46 PM" src="https://user-"No response OS/X 2 module://matplotlibinline.backendinline Python 3.8.15 2 pip


Question: else:             fn = 'contour'         nargs = len(args)        if nargs <= 2:        if 0 < nargs <= 2:             z, *args = args             z = ma.asarray(z)             x, y = self._initialize_x_y(z)        elif nargs <= 4:        elif 2 < nargs <= 4:             x, y, z_orig, *args = args             x, y, z = self._check_xyz(x, y, z_orig, kwargs)         else:             raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)         z = ma.masked_invalid(z, copy=False)


Question: if (rasterization_zorder is not None and                 artists and artists[0].zorder < rasterization_zorder):            renderer.start_rasterizing()            artists_rasterized = [a for a in artists                                  if a.zorder < rasterization_zorder]            artists = [a for a in artists                       if a.zorder >= rasterization_zorder]            split_index = np.searchsorted(                [art.zorder for art in artists],                rasterization_zorder, side='right'            )            artists_rasterized = artists[:split_index]            artists = artists[split_index:]         else:             artists_rasterized = []         # the patch draws the background rectangle -- the frame below        # will draw the edges         if self.axison and self._frameon:            self.patch.draw(renderer)            if artists_rasterized:                artists_rasterized = [self.patch] + artists_rasterized            else:                artists = [self.patch] + artists          if artists_rasterized:            for a in artists_rasterized:                a.draw(renderer)            renderer.stop_rasterizing()            _draw_rasterized(self.figure, artists_rasterized, renderer)          mimage._draw_list_compositing_images(             renderer, self, artists, self.figure.suppressComposite)

[Bug]: pcolormesh(rasterized=True) conflicts with setrasterizationzorder() According to the , a color plot can be rasterized in two ways: The two ways cannot be used together.  The bug appears in version 3.5.1 and commit , but not version 3.1.2. The most immediate cause seems to be reentrance tracking being dropped from and in commit : However, these are probably not the right places to fix this bug. Ubuntu 20.04, 22.04 2, 3.5.1, 3.7.0.dev447+g2d18bba0ea agg 10, 3.10.6 No response_ git checkout


Question: self.yaxis.set_tick_params(which="both", labelright=False)             if self.yaxis.offsetText.get_position()[0] == 1:                 self.yaxis.offsetText.set_visible(False)<ins>def _draw_rasterized(figure, artists, renderer):    """    A helper function for rasterizing the list of artists.    The bookkeeping to track if we are or are not in rasterizing mode    with the mixed-mode backends is relatively complicated and is now    handled in the matplotlib.artist.allow_rasterization decorator.    This helper defines the absolute minimum methods and attributes on a    shim class to be compatible with that decorator and then uses it to    rasterize the list of artists.    This is maybe too-clever, but allows us to re-use the same code that is    used on normal artists to participate in the "are we rasterizing"    accounting.    Please do not use this outside of the "rasterize below a given zorder"    functionality of Axes.    Parameters    ----------    figure : matplotlib.figure.Figure        The figure all of the artists belong to (not checked).  We need this        because we can at the figure level suppress composition and insert each        rasterized artist as its own image.    artists : List[matplotlib.artist.Artist]        The list of Artists to be rasterized.  These are assumed to all        be in the same Figure.    renderer : matplotlib.backendbases.RendererBase        The currently active renderer    Returns    -------    None    """    class _MinimalArtist:        def get_rasterized(self):            return True        def get_agg_filter(self):            return None        def __init__(self, figure, artists):            self.figure = figure            self.artists = artists        @martist.allow_rasterization        def draw(self, renderer):            for a in self.artists:                a.draw(renderer)    return _MinimalArtist(figure, artists).draw(renderer)</ins>


Question: line segments). """ <ins>import itertools</ins> import math from numbers import Number import warnings

[Bug]: gapcolor not supported for LineCollections doesn't have a or , so gapcolor doesn't work in plotting methods that return LineCollections (like vlines or hlines). ! I think the easiest fix is probably add and to LineCollection, modeled on and 1121+g509315008c


Question: # list of unbroadcast/scaled linewidths         self._us_lw = [0]         self._linewidths = [0]<ins>        self._gapcolor = None  # Currently only used by LineCollection.</ins>         # Flags set by _set_mappable_flags: are colors from mapping an array?         self._face_is_mapped = None         self._edge_is_mapped = None


Question: gc, paths[0], combined_transform.frozen(),                 mpath.Path(offsets), offset_trf, tuple(facecolors[0]))         else:<ins>            if self._gapcolor is not None:                # First draw paths within the gaps.                ipaths, ilinestyles = self._get_inverse_paths_linestyles()                renderer.draw_path_collection(                    gc, transform.frozen(), ipaths,                    self.get_transforms(), offsets, offset_trf,                    [mcolors.to_rgba("none")], self._gapcolor,                    self._linewidths, ilinestyles,                    self._antialiaseds, self._urls,                    "screen")</ins>             renderer.draw_path_collection(                 gc, transform.frozen(), paths,                 self.get_transforms(), offsets, offset_trf,


Question: def _get_default_facecolor(self):         return 'none' <ins>    def set_alpha(self, alpha):        # docstring inherited        super().set_alpha(alpha)        if self._gapcolor is not None:            self.set_gapcolor(self._original_gapcolor)</ins>     def set_color(self, c):         """         Set the edgecolor(s) of the LineCollection.


Question: get_colors = get_color  # for compatibility with old versions     def set_gapcolor(self, gapcolor):        """        Set a color to fill the gaps in the dashed line style.        .. note::            Striped lines are created by drawing two interleaved dashed lines.            There can be overlaps between those two, which may result in            artifacts when using transparency.            This functionality is experimental and may change.        Parameters        ----------        gapcolor : color or list of colors or None            The color with which to fill the gaps. If None, the gaps are            unfilled.        """        self._original_gapcolor = gapcolor        self._set_gapcolor(gapcolor)    def _set_gapcolor(self, gapcolor):        if gapcolor is not None:            gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha)        self._gapcolor = gapcolor        self.stale = True    def get_gapcolor(self):        return self._gapcolor    def _get_inverse_paths_linestyles(self):        """        Returns the path and pattern for the gaps in the non-solid lines.        This path and pattern is the inverse of the path and pattern used to        construct the non-solid lines. For solid lines, we set the inverse path        to nans to prevent drawing an inverse line.        """        path_patterns = [            (mpath.Path(np.full((1, 2), np.nan)), ls)            if ls == (0, None) else            (path, mlines._get_inverse_dash_pattern(*ls))            for (path, ls) in            zip(self._paths, itertools.cycle(self._linestyles))]        return zip(*path_patterns)  class EventCollection(LineCollection):     """diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py-- a/lib/matplotlib/lines.py++ b/lib/matplotlib/lines.py


Question: return offset, dashes  <ins>def _get_inverse_dash_pattern(offset, dashes):    """Return the inverse of the given dash pattern, for filling the gaps."""    # Define the inverse pattern by moving the last gap to the start of the    # sequence.    gaps = dashes[-1:] + dashes[:-1]    # Set the offset so that this new first segment is skipped    # (see backend_bases.GraphicsContextBase.set_dashes for offset definition).    offset_gaps = offset + dashes[-1]    return offset_gaps, gaps</ins> def _scale_dashes(offset, dashes, lw):     if not mpl.rcParams['lines.scale_dashes']:         return offset, dashes


Question: lc_rgba = mcolors.to_rgba(self._gapcolor, self._alpha)                     gc.set_foreground(lc_rgba, isRGBA=True)                     # Define the inverse pattern by moving the last gap to the                    # start of the sequence.                    dashes = self._dash_pattern[1]                    gaps = dashes[-1:] + dashes[:-1]                    # Set the offset so that this new first segment is skipped                    # (see backend_bases.GraphicsContextBase.set_dashes for                    # offset definition).                    offset_gaps = self._dash_pattern[0] + dashes[-1]                    offset_gaps, gaps = _get_inverse_dash_pattern(                        *self._dash_pattern)                      gc.set_dashes(offset_gaps, gaps)                     renderer.draw_path(gc, tpath, affine.frozen())


Question: return lev[i0:i1]     def _process_contour_level_args(self, args):    def _process_contour_level_args(self, args, z_dtype):         """         Determine the contour levels and store in self.levels.         """         if self.levels is None:            if len(args) == 0:                levels_arg = 7  # Default, hard-wired.            else:            if args:                 levels_arg = args[0]            elif np.issubdtype(z_dtype, bool):                if self.filled:                    levels_arg = [0, .5, 1]                else:                    levels_arg = [.5]            else:                levels_arg = 7  # Default, hard-wired.         else:             levels_arg = self.levels         if isinstance(levels_arg, Integral):

[ENH]: Auto-detect bool arrays passed to contour()? I find myself fairly regularly calling to draw the boundary line between True and False regions on a boolean 2d array. Without , one gets the default 8 levels which go at 0, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05 resulting in all the contour lines being drawn on top of one another; but clearly(?), for boolean inputs, the only choice that makes sense is to have a single level at 0.5 (or rather, anywhere between 0 and 1). ! Autodetect boolean inputs to contour, and default levels to [0.5] in that case. I guess the closest similar kind of autodetection in the library is for imshow, which auto-switches between 0-1 float RGBA arrays and 0-255 uint8 RGBA arrays (when given a 3D array as input). Thoughts?


Question: fn = 'contour'         nargs = len(args)         if nargs <= 2:            z = ma.asarray(args[0], dtype=np.float64)            z, *args = args            z = ma.asarray(z)             x, y = self._initialize_x_y(z)            args = args[1:]         elif nargs <= 4:            x, y, z = self._check_xyz(args[:3], kwargs)            args = args[3:]            x, y, z_orig, *args = args            x, y, z = self._check_xyz(x, y, z_orig, kwargs)         else:             raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)         z = ma.masked_invalid(z, copy=False)


Question: z = ma.masked_where(z <= 0, z)             _api.warn_external('Log scale: values of z <= 0 have been masked')             self.zmin = float(z.min())        self._process_contour_level_args(args)        self._process_contour_level_args(args, z.dtype)         return (x, y, z)     def _check_xyz(self, args, kwargs):    def _check_xyz(self, x, y, z, kwargs):         """         Check that the shapes of the input arrays match; if x and y are 1D,         convert them to 2D using meshgrid.         """        x, y = args[:2]         x, y = self.axes._process_unit_info([("x", x), ("y", y)], kwargs)          x = np.asarray(x, dtype=np.float64)         y = np.asarray(y, dtype=np.float64)        z = ma.asarray(args[2], dtype=np.float64)        z = ma.asarray(z)          if z.ndim != 2:             raise TypeError(f"Input z must be 2D, not {z.ndim}D")diff --git a/lib/matplotlib/tri/_tricontour.py b/lib/matplotlib/tri/_tricontour.py-- a/lib/matplotlib/tri/_tricontour.py++ b/lib/matplotlib/tri/_tricontour.py


Question: def _contour_args(self, args, kwargs):         tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args,                                                                    **kwargs)        z = np.ma.asarray(args[0])        z, *args = args        z = np.ma.asarray(z)         if z.shape != tri.x.shape:             raise ValueError('z array must have same length as triangulation x'                              ' and y arrays')


Question: if self.logscale and self.zmin <= 0:             func = 'contourf' if self.filled else 'contour'             raise ValueError(f'Cannot {func} log of negative values.')        self._process_contour_level_args(args[1:])        self._process_contour_level_args(args, z.dtype)         return (tri, z)


Question: self.levels = self._autolev(levels_arg)         else:             self.levels = np.asarray(levels_arg, np.float64)        if not self.filled:            inside = (self.levels > self.zmin) & (self.levels < self.zmax)            levels_in = self.levels[inside]            if len(levels_in) == 0:                self.levels = [self.zmin]                _api.warn_external(                    "No contour levels were found within the data range.")         if self.filled and len(self.levels) < 2:             raise ValueError("Filled contours require at least 2 levels.")         if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:             raise ValueError("Contour levels must be increasing")

[ENH]: Allow override of contour level autoscaling In Matplotlib 3, when using a list of values for the argument in , the list of values is overridden in the case that all requested levels fall outside the data range. While this may be desirable for casually browsing data when the user is unfamiliar with the data range, it causes serious problems for batch applications where the user legitimately intends to use their list of levels but does not know whether every input array will produce contours. Example: The above prints when is an array of values ranging from 0 to 50 (i.e., the requested contour level of 100 is outside the data range). As a result, the plot contains erroneous contours around near-zero values, presumably due to floating point precision. This is a consequence of the change described here (): Add a kwarg to that overrides the autoscaling behavior. When the kwarg is set, it would trigger a flag in ():


Question: """         if tight is None:             tight = mpl.rcParams['figure.autolayout']        _tight = 'tight' if bool(tight) else 'none'         _tight_parameters = tight if isinstance(tight, dict) else {}        if bool(tight):            self.set_layout_engine(TightLayoutEngine(**_tight_parameters))        self.set_layout_engine(_tight, **_tight_parameters)         self.stale = True      def get_constrained_layout(self):

[Bug]: Cannot toggle settightlayout As of calling does not disable the tight layout algorithm. AssertionError clean exit I'm pretty sure just needs to set in the falsey case. Attn: No response main No response No response No response No response


Question: """         if constrained is None:             constrained = mpl.rcParams['figure.constrained_layout.use']        _constrained = bool(constrained)        _constrained = 'constrained' if bool(constrained) else 'none'         _parameters = constrained if isinstance(constrained, dict) else {}        if _constrained:            self.set_layout_engine(ConstrainedLayoutEngine(**_parameters))        self.set_layout_engine(_constrained, **_parameters)         self.stale = True      @_api.deprecated(


Question: if not xa.dtype.isnative:             xa = xa.byteswap().newbyteorder()  # Native byteorder is faster.         if xa.dtype.kind == "f":            with np.errstate(invalid="ignore"):                xa *= self.N                # Negative values are out of range, but astype(int) would                # truncate them towards zero.                xa[xa < 0] = -1                # xa == 1 (== N after multiplication) is not out of range.                xa[xa == self.N] = self.N - 1                # Avoid converting large positive values to negative integers.                np.clip(xa, -1, self.N, out=xa)                xa = xa.astype(int)            xa *= self.N            # Negative values are out of range, but astype(int) would            # truncate them towards zero.            xa[xa < 0] = -1            # xa == 1 (== N after multiplication) is not out of range.            xa[xa == self.N] = self.N - 1            # Avoid converting large positive values to negative integers.            np.clip(xa, -1, self.N, out=xa)        with np.errstate(invalid="ignore"):            # We need this cast for unsigned ints as well as floats            xa = xa.astype(int)         # Set the over-range indices before the under-range;         # otherwise the under-range values get converted to over-range.         xa[xa > self.N - 1] = self._i_over

[Bug]: NumPy 1.24 deprecation warnings Starting NumPy 1.24 I observe several deprecation warnings. No warnings. No response ArchLinux 2 QtAgg Python 3.10.9 No response Linux package manager


Question: """     origBbox = fig.bbox     origBboxInches = fig.bbox_inches<del>    orig_layout = fig.get_layout_engine()    fig.set_layout_engine(None)</del>     _boxout = fig.transFigure._boxout      old_aspect = []

[Bug]: compressed layout setting can be forgotten on second save I'm not sure whether this is really a bug or I'm just using an inconsistent combination of options. Under some specific circumstances (see below) compressed layout is not applied the second time a figure is saved. ! ! Both images should look like the first. If I do not set the , all is well. If I do not set in my calls to , the images are identical (but I have too much white space top and bottom). Maybe there is a better option than when using compressed layout? For context, my real example is a script that makes several figures. For most of them I want constrained layout, so I set that once in the for convenience. Only one figure needs "compressed", and I am saving twice because I want both a png and a pdf. Fixed it in my current example by just reverting the setting for the one figure. RHEL7 2 and main QtAgg 9 and 3.11 No response conda


Question: fig.bbox = origBbox         fig.bbox_inches = origBboxInches<del>        fig.set_layout_engine(orig_layout)</del>         fig.transFigure._boxout = _boxout         fig.transFigure.invalidate()         fig.patch.set_bounds(0, 0, 1, 1)


Question: loc : str             The position of the cell with respect to *ax*. This must be one of             the `~.Table.codes`.        bbox : `.Bbox` or None        bbox : `.Bbox` or [xmin, ymin, width, height], optional             A bounding box to draw the table into. If this is not *None*, this             overrides *loc*.

[Doc]: bbox parameter The documentation states that should be an instance of . When I try to use it like this I obtain the following error traceback below using matplotlib v3.6.2, whereas it works if I define it as e.g. which I guess (but just because I tried empirically) is equivalent to the method of Bbox. Either let the parameter be a proper BBox (my suggestion) or specify that the usage is that of


Question: if self._bbox is not None:             # Position according to bbox            rl, rb, rw, rh = self._bbox            if isinstance(self._bbox, Bbox):                rl, rb, rw, rh = self._bbox.bounds            else:                rl, rb, rw, rh = self._bbox             self.scale(rw / w, rh / h)             ox = rl - l             oy = rb - b


Question: The position of the cell with respect to *ax*. This must be one of         the `~.Table.codes`.     bbox : `.Bbox`, optional    bbox : `.Bbox` or [xmin, ymin, width, height], optional         A bounding box to draw the table into. If this is not *None*, this         overrides *loc*.


Question: def autoscale(self, A):         """Set *vmin*, *vmax* to min, max of *A*."""        self.vmin = self.vmax = None        self.autoscale_None(A)        with self.callbacks.blocked():            # Pause callbacks while we are updating so we only get            # a single update signal at the end            self.vmin = self.vmax = None            self.autoscale_None(A)        self._changed()      def autoscale_None(self, A):         """If vmin or vmax are not set, use the min/max of *A* to set them."""

[Bug]: Setting norm with existing colorbar fails with 3.6.3 Setting the norm to a after the colorbar has been created (e.g. in interactive code) fails with an value in matplotlib 3.6.3. The same code worked in previous matplotlib versions. Not that vmin and vmax are explicitly set to values valid for and no negative values (or values == 0) exist in the input data. Works, colorbar and mappable are updated with new norm. No response Linux 3 (works with 3.6.2) Multpiple backends tested, same error in all (Qt5Agg, TkAgg, agg, ...) 15 not in jupyter conda


Question: """         return not self.active <ins>    def _changed_canvas(self):        """        Someone has switched the canvas on us!        This happens if `savefig` needs to save to a format the previous        backend did not support (e.g. saving a figure using an Agg based        backend saved to a vector format).        Returns        -------        bool           True if the canvas has been changed.        """        return self.canvas is not self.ax.figure.canvas</ins>  class AxesWidget(Widget):     """

[Bug]: Widget blitting broken when saving as PDF When running a test doc build for 3.7.0rc1, I build the PDF, which runs everything with the PDF backend. So either the PDF backend does not correctly mark itself as not supporting blitting, or the blitting is not turned off correctly in the button widgets. Docs build without warning. No response Fedora 37 v3.7.x PDF 11.1 No response git checkout


Question: def _clear(self, event):         """Internal event handler to clear the buttons."""        if self.ignore(event):        if self.ignore(event) or self._changed_canvas():             return         self._background = self.canvas.copy_from_bbox(self.ax.bbox)         self.ax.draw_artist(self._checks)


Question: def _clear(self, event):         """Internal event handler to clear the buttons."""        if self.ignore(event):        if self.ignore(event) or self._changed_canvas():             return         self._background = self.canvas.copy_from_bbox(self.ax.bbox)         self.ax.draw_artist(self._buttons)


Question: def clear(self, event):         """Internal event handler to clear the cursor."""        if self.ignore(event):        if self.ignore(event) or self._changed_canvas():             return         if self.useblit:             self.background = self.canvas.copy_from_bbox(self.ax.bbox)


Question: return         if self.useblit:             for canvas, info in self._canvas_infos.items():<ins>                # someone has switched the canvas on us!  This happens if                # `savefig` needs to save to a format the previous backend did                # not support (e.g. saving a figure using an Agg based backend                # saved to a vector format).                if canvas is not canvas.figure.canvas:                    continue</ins>                 info["background"] = canvas.copy_from_bbox(canvas.figure.bbox)      def onmove(self, event):


Question: elif mode == 'psd':         result = np.conj(result) * result     elif mode == 'magnitude':        result = np.abs(result) / np.abs(window).sum()        result = np.abs(result) / window.sum()     elif mode == 'angle' or mode == 'phase':         # we unwrap the phase later to handle the onesided vs. twosided case         result = np.angle(result)     elif mode == 'complex':        result /= np.abs(window).sum()        result /= window.sum()      if mode == 'psd':

[Bug]: Windows correction is not correct in Windows correction is not correct in : The is not needed, and give wrong result for window with negative value, such as . For reference, the implementation of scipy can be found here : 4372. 0 No response No response latest No response No response No response None


Question: result /= Fs             # Scale the spectrum by the norm of the window to compensate for             # windowing loss; see Bendat & Piersol Sec 11.5.2.            result /= (np.abs(window)**2).sum()            result /= (window**2).sum()         else:             # In this case, preserve power in the segment, not amplitude            result /= np.abs(window).sum()**2            result /= window.sum()**2      t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs


Question: dimensions as the current child.         """         if hasattr(self, "_child"):  # Absent during init.<ins>            self.invalidate()</ins>             new_dims = (child.input_dims, child.output_dims)             old_dims = (self._child.input_dims, self._child.output_dims)             if new_dims != old_dims:

[Bug]: (x,y) disappears after changing yscale The output of (x,y) disappears while changing yscale from 'log' (initial scale for the y axis) to 'linear'. The expected outcome is generated with matplotlib==3.5.3 fillbetween and hist are working fine. MacOSX 3 MacOSX 13 No response_ pip


Question: The DPI (or resolution) for the file.  This controls the size             in pixels of the resulting movie file.         """<ins>        # Check that path is valid        Path(outfile).parent.resolve(strict=True)</ins>         self.outfile = outfile         self.fig = fig         if dpi is None:

[MNT]: FFMpegWriter does not check if out path exists when initialized. FFMpegWriter does not ensure the outputpath exists when initialized (). This leads to a broken pipe error with no mention of a non-existent path which can be misleading to the user. When setup is called, check the output path exists and if not, throw an error to inform the user.


Question: deleted by `finish`; if not *None*, no temporary files are             deleted.         """<ins>        # Check that path is valid        Path(outfile).parent.resolve(strict=True)</ins>         self.fig = fig         self.outfile = outfile         if dpi is None:


Question: self.fname_format_str = '%s%%07d.%s'      def __del__(self):        if self._tmpdir:        if hasattr(self, '_tmpdir') and self._tmpdir:             self._tmpdir.cleanup()      @property


Question: import itertools import logging<ins>import numbers</ins> import time  import numpy as np

[Bug]: Validation not performed for argument to When passing non-str values to , validation is not performed. So even for invalid inputs, errors are raised only when we call Errors should be raised when invalid arguments are passed to . Similar to what we get when we pass an invalid string value as shown: Do you know why this bug is happening? No validation is done when setting values for . We do check strings on line 473, which is why we don't face this issue there. Windows 2 'TkAgg' 7 No response pip


Question: if not self.isaxes and loc in [0, 'best']:                 loc = 'upper right' <ins>        type_err_message = ("loc must be string, coordinate tuple, or"                            f" an integer 0-10, not {loc!r}")</ins>         # handle outside legends:         self._outside_loc = None         if isinstance(loc, str):


Question: loc = locs[0] + ' ' + locs[1]             # check that loc is in acceptable strings             loc = _api.check_getitem(self.codes, loc=loc)<ins>        elif np.iterable(loc):            # coerce iterable into tuple            loc = tuple(loc)            # validate the tuple represents Real coordinates            if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):                raise ValueError(type_err_message)        elif isinstance(loc, int):            # validate the integer represents a string numeric value            if loc < 0 or loc > 10:                raise ValueError(type_err_message)        else:            # all other cases are invalid values of loc            raise ValueError(type_err_message)</ins>          if self.isaxes and self._outside_loc:             raise ValueError(


Question: )         self.label_position = 'bottom'         if mpl.rcParams['xtick.labelcolor'] == 'inherit':            tick_color = mpl.rcParams['xtick.color']        else:            tick_color = mpl.rcParams['xtick.labelcolor']         self.offsetText.set(             x=1, y=0,             verticalalignment='top', horizontalalignment='right',             transform=mtransforms.blended_transform_factory(                 self.axes.transAxes, mtransforms.IdentityTransform()),             fontsize=mpl.rcParams['xtick.labelsize'],            color=mpl.rcParams['xtick.color'],            color=tick_color         )         self.offset_text_position = 'bottom'

[Bug]: offsetText is colored based on instead of tick.labelcolor In version 3.6.3, when setting ytick.labelcolor / xtick.labelcolor in styles / rcParams, it does not change the color of the exponent label as well. It will be colored based on / ! ! The following patch seems to fix it for my simple usecases: No response 3 No response No response No response None


Question: mtransforms.IdentityTransform(), self.axes.transAxes),         )         self.label_position = 'left'<ins>        if mpl.rcParams['ytick.labelcolor'] == 'inherit':            tick_color = mpl.rcParams['ytick.color']        else:            tick_color = mpl.rcParams['ytick.labelcolor']</ins>         # x in axes coords, y in display coords(!).         self.offsetText.set(             x=0, y=0.5,


Question: transform=mtransforms.blended_transform_factory(                 self.axes.transAxes, mtransforms.IdentityTransform()),             fontsize=mpl.rcParams['ytick.labelsize'],            color=mpl.rcParams['ytick.color'],            color=tick_color         )         self.offset_text_position = 'left'


Question: if not ref_artist.pickable():             ref_artist.set_picker(True)         self.got_artist = False<del>        self.canvas = self.ref_artist.figure.canvas</del>         self._use_blit = use_blit and self.canvas.supports_blit         self.cids = [             self.canvas.callbacks._connect_picklable(

[Bug]: Unable to pickle figure with draggable legend I am unable to pickle figure with draggable legend. Same error comes for draggable annotations. Pickling successful No response Windows 10 0 No response 10 No response pip


Question: 'button_release_event', self.on_release),         ] <ins>    # A property, not an attribute, to maintain picklability.    canvas = property(lambda self: self.ref_artist.figure.canvas)</ins>     def on_motion(self, evt):         if self._check_still_parented() and self.got_artist:             dx = evt.x - self.mouse_x


Question: def __init__(self, init=()):         self._mapping = {weakref.ref(x): [weakref.ref(x)] for x in init} <ins>    def __getstate__(self):        return {            **vars(self),            # Convert weak refs to strong ones.            "_mapping": {k(): [v() for v in vs] for k, vs in self._mapping.items()},        }    def __setstate__(self, state):        vars(self).update(state)        # Convert strong refs to weak ones.        self._mapping = {weakref.ref(k): [*map(weakref.ref, vs)]                         for k, vs in self._mapping.items()}</ins>     def __contains__(self, item):         return weakref.ref(item) in self._mapping

[Bug]: Unable to pickle figure with aligned labels Unable to pickle figure after calling Pickling successful No response Windows 0 No response No response No response_ None


Question: else:             raise _api.nargs_error(fn, takes="from 1 to 4", given=nargs)         z = ma.masked_invalid(z, copy=False)        self.zmax = float(z.max())        self.zmin = float(z.min())        self.zmax = z.max().astype(float)        self.zmin = z.min().astype(float)         if self.logscale and self.zmin <= 0:             z = ma.masked_where(z <= 0, z)             _api.warn_external('Log scale: values of z <= 0 have been masked')            self.zmin = float(z.min())            self.zmin = z.min().astype(float)         self._process_contour_level_args(args, z.dtype)         return (x, y, z)

plt.contour with all NaNs fails assertion in Bug summary Passing an array with all NaN values into causes the following assertion to fail in : This is actually triggered by a test-case in the xarray test suite, but I imagine it hasn't been noticed (yet) because release builds of matplotlib typically disable assertion checks. Code for reproduction Actual outcome Failed assertion (see referenced line above, tracked down with ) Expected outcome I would expect to see the empty plot (and long lists of warnings) that are currently shown if assertions are disabled: ! Matplotlib version Operating system: Linux Matplotlib version: 3.0.3 Matplotlib backend (): agg Python version: 3.6 Python, matplotlib, etc are installed from source


Question: valmin, valmax, valfmt, dragging, valstep)          # Set a value to allow _value_in_bounds() to work.        self.val = [valmin, valmax]        self.val = (valmin, valmax)         if valinit is None:             # Place at the 25th and 75th percentiles             extent = valmax - valmin

[Bug]: setval of rangeslider sets incorrect value The setval() method of a range slider doesn't set the value correctly with values close to the minimal and maximal values of the range slider. With values in the middle, everything works fine. ! The values for the rangesliders "wrong" and "wrong2" are not set correctly Expected values are: (1, 2) and (9, 10) Actual values are (1, 3.25) and (7.75, 10) The result of using setval should be the same, as when using the valinit parameter of the constructor. The problem also occurred on Manjaro with: Python version: 3.10.9 Matplotlib version: 3.6.2 Matplotlib backend: QtAgg Installation of matplotlib via Linux package manager Windows 10 2 TkAgg 11.0 No response_ pip


Question: """         val = np.sort(val)         _api.check_shape((2,), val=val)        vmin, vmax = val        vmin = self._min_in_bounds(vmin)        vmax = self._max_in_bounds(vmax)        # Reset value to allow _value_in_bounds() to work.        self.val = (self.valmin, self.valmax)        vmin, vmax = self._value_in_bounds(val)         self._update_selection_poly(vmin, vmax)         if self.orientation == "vertical":             self._handles[0].set_ydata([vmin])


Question: of a rotated text when necessary.         """         thisx, thisy = 0.0, 0.0        lines = self.get_text().split("\n")  # Ensures lines is not empty.        lines = self._get_wrapped_text().split("\n")  # Ensures lines is not empty.          ws = []         hs = []

[Bug]: constrained layout with wrapped titles When titles are long and wrapped, constrained layout doesn't leave enough room for them. ! Enough space for the titles. There's no problem if the titles have an explicit new line ("\n"), so this seems to be specific to the wrapping. RHEL7 0 and main QtAgg 11.0 N/A conda


Question: def set_props(self, **props):         """        Set the properties of the selector artist. See the `props` argument        in the selector docstring to know which properties are supported.        Set the properties of the selector artist.        See the *props* argument in the selector docstring to know which properties are        supported.         """         artist = self._selection_artist         props = cbook.normalize_kwargs(props, artist)         artist.set(**props)         if self.useblit:             self.update()        self._props.update(props)      def set_handle_props(self, **handle_props):         """

[Bug]: AttributeError: 'LassoSelector' object has no attribute 'props' I used the LassoSelector object to select the single point in the scatterplot. But when I try to update the line color of LassoSelector with the setprops function, I get an error like this AttributeError: 'LassoSelector' object has no attribute 'props'. This warning does not occur when the comment symbol is placed at the beginning of the line "(props)" in the "set_ props" function of the matplotlib library's code.


Question: # but we maintain it until it is removed         self._pressv = None <del>        self._props = props</del>         self.onmove_callback = onmove_callback         self.minspan = minspan


Question: # Reset canvas so that `new_axes` connects events.         self.canvas = None        self.new_axes(ax)        self.new_axes(ax, _props=props)          # Setup handles         self._handle_props = {


Question: # prev attribute is deprecated but we still need to maintain it         self._prev = (0, 0)     def new_axes(self, ax):    def new_axes(self, ax, *, _props=None):         """Set SpanSelector to operate on a new Axes."""         self.ax = ax         if self.canvas is not ax.figure.canvas:


Question: else:             trans = ax.get_yaxis_transform()             w, h = 1, 0        rect_artist = Rectangle((0, 0), w, h,                                transform=trans,                                visible=False,                                **self._props)        rect_artist = Rectangle((0, 0), w, h, transform=trans, visible=False)        if _props is not None:            rect_artist.update(_props)        elif self._selection_artist is not None:            rect_artist.update_from(self._selection_artist)          self.ax.add_patch(rect_artist)         self._selection_artist = rect_artist


Question: if props is None:             props = dict(facecolor='red', edgecolor='black',                          alpha=0.2, fill=True)        self._props = {**props, 'animated': self.useblit}        self._visible = self._props.pop('visible', self._visible)        to_draw = self._init_shape(**self._props)        props = {**props, 'animated': self.useblit}        self._visible = props.pop('visible', self._visible)        to_draw = self._init_shape(**props)         self.ax.add_patch(to_draw)          self._selection_artist = to_draw


Question: if self._interactive:             self._handle_props = {                'markeredgecolor': (self._props or {}).get(                    'edgecolor', 'black'),                'markeredgecolor': (props or {}).get('edgecolor', 'black'),                 **cbook.normalize_kwargs(handle_props, Line2D)}              self._corner_order = ['SW', 'SE', 'NE', 'NW']


Question: if props is None:             props = dict(color='k', linestyle='-', linewidth=2, alpha=0.5)        self._props = {**props, 'animated': self.useblit}        self._selection_artist = line = Line2D([], [], **self._props)        props = {**props, 'animated': self.useblit}        self._selection_artist = line = Line2D([], [], **props)         self.ax.add_line(line)          if handle_props is None:             handle_props = dict(markeredgecolor='k',                                markerfacecolor=self._props.get('color', 'k'))                                markerfacecolor=props.get('color', 'k'))         self._handle_props = handle_props         self._polygon_handles = ToolHandles(self.ax, [], [],                                             useblit=self.useblit,


Question: # Get decades between major ticks.         stride = (max(math.ceil(numdec / (numticks - 1)), 1)                   if mpl.rcParams['_internal.classic_mode'] else                  (numdec + 1) // numticks + 1)                  numdec // numticks + 1)          # if we have decided that the stride is as big or bigger than         # the range, clip the stride back to the available range - 1

[Bug]: LogLocator with subs argument fragile. Logarithmic tick markers do not appear if the y-axis scales a sufficient range, with the keyword argument of set to non-trivial values. ! ! I expect to see ticks in both cases, as appears in the "Good Plot". The problem is isolated to . This returns correct values in the first case (e.g., ([1.e-01 2.e-01 5.e-01 1.e+00 2.e+00 5.e+00 1.e+01 2.e+01 5.e+01 1.e+02 2.e+02 5.e+02])([]) in the second case. Windows 2 module://backendinteragg 13 No response conda [Bug]: LogLocator with subs argument fragile. Logarithmic tick markers do not appear if the y-axis scales a sufficient range, with the keyword argument of set to non-trivial values. ! ! I expect to see ticks in both cases, as appears in the "Good Plot". The problem is isolated to . This returns correct values in the first case (e.g., ([1.e-01 2.e-01 5.e-01 1.e+00 2.e+00 5.e+00 1.e+01 2.e+01 5.e+01 1.e+02 2.e+02 5.e+02])([]) in the second case. Windows 2 module://backendinteragg 13 No response conda


Question: def __str__(self):         try:            size = self.get_size()            return f"{type(self).__name__}(size={size!r})"            shape = self.get_shape()            return f"{type(self).__name__}(shape={shape!r})"         except RuntimeError:             return type(self).__name__

[ENH]: Add as alias for in AxesImage, or make that include depth too changed to . While this indeed corresponds to , this is not consistent with the numpy API, where and . Perhaps we can consider 1) tweaking to instead, and add as an alias for ? Alternatively, could return (i.e., including whether the data is colormapped, RGB, or RGBA), and we could use that* info in ? (displaying whether the data is colormapped/RGB/RGBA seems reasonably useful) No response_


Question: def get_size(self):         """Return the size of the image as tuple (numrows, numcols)."""        return self.get_shape()[:2]    def get_shape(self):        """        Return the shape of the image as tuple (numrows, numcols, channels).        """         if self._A is None:             raise RuntimeError('You must first set the image array')         return self._A.shape[:2]        return self._A.shape      def set_alpha(self, alpha):         """