Question: MultiCursor should be able to bind to axes in more than one figure... Multicursor only works if all the axes are in the same figure... Originally posted by in and possible solution: Originally posted by in

self.connect()     canvas = _api.deprecate_privatize_attribute("3.6")    background = _api.deprecated("3.6")(lambda self: (        self._backgrounds[self.axes[0].figure.canvas] if self.axes else None))     def connect(self):         """Connect events."""        self._cidmotion = self.canvas.mpl_connect('motion_notify_event',                                                  self.onmove)        self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear)        for canvas, info in self._canvas_infos.items():            info["cids"] = [                canvas.mpl_connect('motion_notify_event', self.onmove),                canvas.mpl_connect('draw_event', self.clear),            ]      def disconnect(self):         """Disconnect events."""        self.canvas.mpl_disconnect(self._cidmotion)        self.canvas.mpl_disconnect(self._ciddraw)        for canvas, info in self._canvas_infos.items():            for cid in info["cids"]:                canvas.mpl_disconnect(cid)            info["cids"].clear()      def clear(self, event):         """Clear the cursor."""         if self.ignore(event):             return         if self.useblit:            self.background = (                self.canvas.copy_from_bbox(self.canvas.figure.bbox))            for canvas, info in self._canvas_infos.items():                info["background"] = canvas.copy_from_bbox(canvas.figure.bbox)         for line in self.vlines + self.hlines:             line.set_visible(False)      def onmove(self, event):        if self.ignore(event):            return        if event.inaxes not in self.axes:            return        if not self.canvas.widgetlock.available(self):        if (self.ignore(event)                or event.inaxes not in self.axes                or not event.canvas.widgetlock.available(self)):             return         self.needclear = True         if not self.visible:


Question: MultiCursor should be able to bind to axes in more than one figure... Multicursor only works if all the axes are in the same figure... Originally posted by in and possible solution: Originally posted by in

def _update(self):         if self.useblit:            if self.background is not None:                self.canvas.restore_region(self.background)            for canvas, info in self._canvas_infos.items():                if info["background"]:                    canvas.restore_region(info["background"])             if self.vertOn:                 for ax, line in zip(self.axes, self.vlines):                     ax.draw_artist(line)             if self.horizOn:                 for ax, line in zip(self.axes, self.hlines):                     ax.draw_artist(line)            self.canvas.blit()            for canvas in self._canvas_infos:                canvas.blit()         else:            self.canvas.draw_idle()            for canvas in self._canvas_infos:                canvas.draw_idle()   class _SelectorWidget(AxesWidget):


Question: [Bug]: offset dash linestyle has no effect in patch objects When setting the linestyle on a patch object using a dash tuple the offset has no effect. <img width="874" alt="Screen Shot 2022-05-04 at 4 45 33 PM" src="https://user-"the patch edge lines overlap, not adhering to the offset. Haven't been able to get any patch objects to have a proper offset on the edge line style but the expected outcome is shown here with Line2D objects <img width="580" alt="Screen Shot 2022-05-04 at 4 59 25 PM" src="https://user-"I have tried the Ellipse patch object as well and found the same issue. I also reproduced in Ubuntu 18.04 VM running matplotlib 3.5.0 with agg backend. OS/X 4 MacOSX Python 3.8.8 No response conda

# docstring inherited         if not self.get_visible():             return        # Patch has traditionally ignored the dashoffset.        with cbook._setattr_cm(                 self, _dash_pattern=(0, self._dash_pattern[1])), \        with cbook._setattr_cm(self, _dash_pattern=(self._dash_pattern)), \              self._bind_draw_path_function(renderer) as draw_path:             path = self.get_path()             transform = self.get_transform()


Question: [Bug]: DPI of a figure is doubled after unpickling on M1 Mac When a figure is unpickled, it's dpi is doubled. This behaviour happens every time and if done in a loop it can cause an . This seems to happen only on M1 MacBooks and the version of python doesn't matter. OS/X 2 MacOSX 12 No response pip

# Set cached renderer to None -- it can't be pickled.         state["_cachedRenderer"] = None <ins>        # discard any changes to the dpi due to pixel ratio changes        state["_dpi"] = state.get('_original_dpi', state['_dpi'])</ins>         # add version information to the state         state['__mpl_version__'] = mpl.__version__


Question: [Bug]: scatter plot color settings discarded unless c given When making an animation of a scatter plot, if you don't set (the color value parameter) when initializing the artist, the color settings are ignored. Even though is passed to , the points use the default "viridis" color map. I would expect the points to use the "gray" color map. If you modify the above code to use: it works as expected. It seems like all color-related settings, including cmap, vmin, vmax, etc. are discarded unless is given during the first call to . This workaround (passing an empty ) isn't problematic, but I found the default behavior quite unintuitive and it took me the better part of a day to figure out what was happening, so I figured it would be worth reporting. Possible solutions: Raise an error/warning if // are given but is not Store parameters like // even if they aren't immediately used These changes should probably happen in in . According to , wrote most of this logic. macOS 12.4 2 MacOSX 13 N/A from source ()

collection.set_cmap(cmap)             collection.set_norm(norm)             collection._scale_norm(norm, vmin, vmax)<ins>        else:            extra_kwargs = {                    'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax                    }            extra_keys = [k for k, v in extra_kwargs.items() if v is not None]            if any(extra_keys):                keys_str = ", ".join(f"'{k}'" for k in extra_keys)                _api.warn_external(                    "No data for colormapping provided via 'c'. "                    f"Parameters {keys_str} will be ignored")</ins>         collection._internal_update(kwargs)          # Classic mode only:


Question: 'Poly3DCollection' object has no attribute '_facecolors2d' The following minimal example demonstrates the issue: It fails on the last line with the following traceback: Tested with mpl versions 1.3.1 and 1.4.2. Sent here by Benjamin, from the mpl users mailing list (mail with the same title). Sorry for dumping this without more assistance, I'm not yet at a python level where I can help in debugging, I think (well, it seems daunting).

self.stale = True      def get_facecolor(self):        # docstring inherited        # self._facecolors2d is not initialized until do_3d_projection        if not hasattr(self, '_facecolors2d'):            self.axes.M = self.axes.get_proj()            self.do_3d_projection()         return self._facecolors2d      def get_edgecolor(self):        # docstring inherited        # self._edgecolors2d is not initialized until do_3d_projection        if not hasattr(self, '_edgecolors2d'):            self.axes.M = self.axes.get_proj()            self.do_3d_projection()         return self._edgecolors2d


Question: [Bug]: 'Line3D' object has no attribute 'verts3d' I use matplotlib 3D to visualize some lines in 3D. When I first run the following code, the code can run right. But, if I give a numpy array, it will report the error 'input operand has more dimensions than allowed by the axis remapping'. The point is when next I give and other variables an int number, the AttributeError: 'Line3D' object has no attribute 'verts3d' will appear and can not be fixed whatever I change the variables or delete them. The error can be only fixed when I restart the kernel of ipython console. I don't know why it happens, so I come here for help. Traceback (most recent call last): File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 3444, in runcode exec(codeobj, self.userglobalns, ) File "<ipython-input-80-", line 20, in () File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 368, in show return (args, kwargs) File "", line 29, in call (kwargs) File "", line 112, in show () File "", line 68, in show (self) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 436, in draw (self.renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 73, in drawwrapper result = draw(artist, renderer, args, **kwargs) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 50, in drawwrapper return draw(artist, renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 2803, in draw mimage.drawlistcompositingimages( File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 132, in drawlistcompositingimages a.draw(renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 50, in drawwrapper return draw(artist, renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 469, in draw super().draw(renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 50, in drawwrapper return draw(artist, renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 3082, in draw mimage.drawlistcompositingimages( File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 132, in drawlistcompositingimages a.draw(renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 50, in drawwrapper return draw(artist, renderer) File "/home/hanyaning/anaconda3/envs/SBeA/lib/python3.8/site-", line 215, in draw xs3d, ys3d, zs3d = self.verts3d AttributeError: 'Line3D' object has no attribute 'verts3d' Some 3D lines No response Local: windows + pycharm, Remote: Ubuntu 20.04 0 module://backendinteragg 12 No response_ pip

def set_3d_properties(self, zs=0, zdir='z'):         xs = self.get_xdata()         ys = self.get_ydata()<ins>        zs = cbook._to_unmasked_float_array(zs).ravel()</ins>         zs = np.broadcast_to(zs, len(xs))         self._verts3d = juggle_axes(xs, ys, zs, zdir)         self.stale = True


Question: [Bug]: colorbar with unattached mappables can't steal space This is something I noticed downstream in networkx: Formerly, space for a was stolen from the current ; that was deprecated and now in 3.6, it is stolen from the mappable's . But if the mappable is not to an , it fails with a somewhat unrelated-looking error. Either we should switch to the current Axes if the mappable doesn't have one (probably not desired given the previous change), or raise a clearer error message when this happens. No response No response 0rc1 No response No response No response pip

"""          if ax is None:            ax = getattr(mappable, "axes", self.gca())            ax = getattr(mappable, "axes", None)          if (self.get_layout_engine() is not None and                 not self.get_layout_engine().colorbar_gridspec):             use_gridspec = False         # Store the value of gca so that we can set it back later on.         if cax is None:            if ax is None:                raise 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.')             current_ax = self.gca()             userax = False             if (use_gridspec and isinstance(ax, SubplotBase)):


Question: [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

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


Question: [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

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: 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?

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> """)


Question: 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?

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: 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?

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: [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, 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

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())


Question: [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

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)


Question: 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

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


Question: 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

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: 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

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: [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

# 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)):


Question: [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.

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.


Question: [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.

"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: [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.

# 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: [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.

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


Question: [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.

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


Question: [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

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):


Question: [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

# 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


Question: [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

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


Question: [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

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: [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

# 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: [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...

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,


Question: [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...

# 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: [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...

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: [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...

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: [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...

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: [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

# 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),


Question: [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

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: 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.

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__)


Question: 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.

"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: 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.

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: 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.

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: 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.

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: 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.

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: 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.

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: 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.

#    >>> 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: [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

'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):


Question: [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

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: [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

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: [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.

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)


Question: [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

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 = {}


Question: [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.

# 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.


Question: 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

"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.


Question: 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

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: 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

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: 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

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: 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

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: 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

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: 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

@_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: [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

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":


Question: [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

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:


Question: [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

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: [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

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: [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

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: [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

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: [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

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: [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

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: 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.

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


Question: 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

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:


Question: 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

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: [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

"""=================================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


Question: [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

|           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: [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

*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: [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

(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: [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

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: [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

"""         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


Question: [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

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: [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

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)


Question: [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

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: [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

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


Question: [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

# 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: [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

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: [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

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.