Question: """         return self.renderer.buffer_rgba()     def print_raw(self, filename_or_obj):    def print_raw(self, filename_or_obj, *, metadata=None):        if metadata is not None:            raise ValueError("metadata not supported for raw/rgba")         FigureCanvasAgg.draw(self)         renderer = self.get_renderer()         with cbook.open_file_cm(filename_or_obj, "wb") as fh:

[Bug]: savefig + jpg + metadata fails with inscrutable error message If we call with a with a extension, with the kwarg specified, the error message is inscrutable. Either metadata should be , the argument ignored, or a more informative error message. No response OS/X 1 MacOSX Python 3.11.2 No response pip


Question: # print_figure(), and the latter ensures that `self.figure.dpi` already     # matches the dpi kwarg (if any).     def print_jpg(self, filename_or_obj, *, pil_kwargs=None):    def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):         # savefig() has already applied savefig.facecolor; we now set it to         # white to make imsave() blend semi-transparent figures against an         # assumed white background.         with mpl.rc_context({"savefig.facecolor": "white"}):            self._print_pil(filename_or_obj, "jpeg", pil_kwargs)            self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)      print_jpeg = print_jpg     def print_tif(self, filename_or_obj, *, pil_kwargs=None):        self._print_pil(filename_or_obj, "tiff", pil_kwargs)    def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):        self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)      print_tiff = print_tif     def print_webp(self, filename_or_obj, *, pil_kwargs=None):        self._print_pil(filename_or_obj, "webp", pil_kwargs)    def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):        self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)      print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(         """diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py-- a/lib/matplotlib/figure.py++ b/lib/matplotlib/figure.py


Question: `~.FigureCanvasSVG.print_svg`.             - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.             Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support            embedding metadata.            Does not currently support 'jpg', 'tiff', or 'webp', but may include            embedding EXIF metadata in the future.         bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`             Bounding box in inches: only the given portion of the figure is             saved.  If 'tight', try to figure out the tight bbox of the figure.diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py-- a/lib/matplotlib/image.py++ b/lib/matplotlib/image.py


Question: Metadata in the image file.  The supported keys depend on the output         format, see the documentation of the respective backends for more         information.<ins>        Currently only supported for "png", "pdf", "ps", "eps", and "svg".</ins>     pil_kwargs : dict, optional         Keyword arguments passed to `PIL.Image.Image.save`.  If the 'pnginfo'         key is present, it completely overrides *metadata*, including the


Question: for k, v in metadata.items():                     if v is not None:                         pnginfo.add_text(k, v)<ins>        elif metadata is not None:            raise ValueError(f"metadata not supported for format {format!r}")</ins>         if format in ["jpg", "jpeg"]:             format = "jpeg"  # Pillow doesn't recognize "jpg".             facecolor = mpl.rcParams["savefig.facecolor"]


Question: self._axobservers.process("_axes_change_event", self)         self.stale = True         self._localaxes.remove(ax)<ins>        self.canvas.release_mouse(ax)</ins>          # Break link between any shared axes         for name in ax._axis_names:

[Bug]: using clf and in range slider onchanged callback blocks input to widgets When using clear figure, adding new widgets and then redrawing the current figure in the onchanged callback of a range slider the inputs to all the widgets in the figure are blocked. When doing the same in the button callback onclicked, everything works fine. The widgets can't receive any input from a mouse click, when redrawing in the onchanged callback of a range Slider. When using a button, there is no problem. The range slider callback onchanged behaves the same as the button callback onclicked. The problem also occurred on Manjaro with: Python version: 3.10.9 Matplotlib version: 3.6.2 Matplotlib backend: QtAgg Installation of matplotlib via Linux package manager Windows 10 2 TkAgg 11.0 No response pip


Question: ref_artist.set_picker(True)         self.got_artist = False         self._use_blit = use_blit and self.canvas.supports_blit        self.cids = [            self.canvas.callbacks._connect_picklable(                'pick_event', self.on_pick),            self.canvas.callbacks._connect_picklable(                'button_release_event', self.on_release),        callbacks = ref_artist.figure._canvas_callbacks        self._disconnectors = [            functools.partial(                callbacks.disconnect, callbacks._connect_picklable(name, func))            for name, func in [                ("pick_event", self.on_pick),                ("button_release_event", self.on_release),                ("motion_notify_event", self.on_motion),            ]         ]      # A property, not an attribute, to maintain picklability.     canvas = property(lambda self: self.ref_artist.figure.canvas)     cids = property(lambda self: [        disconnect.args[0] for disconnect in self._disconnectors[:2]])     def on_motion(self, evt):         if self._check_still_parented() and self.got_artist:             dx = evt.x - self.mouse_x

[Bug]: Attribute Error combining matplotlib 3.7.1 and mplcursor on data selection If you combine mplcursor and matplotlib 3.7.1, you'll get an after clicking a few data points. Henceforth, selecting a new data point will trigger the same traceback. Otherwise, it works fine. No terminal output Using matplotlib 3.7.0 or lower works fine. Using a conda install or pip install doesn't affect the output. Windows 11 and Windwos 10 1 QtAgg 16 No response conda


Question: self.ref_artist.draw(                     self.ref_artist.figure._get_renderer())                 self.canvas.blit()            self._c1 = self.canvas.callbacks._connect_picklable(                "motion_notify_event", self.on_motion)             self.save_offset()      def on_release(self, event):         if self._check_still_parented() and self.got_artist:             self.finalize_offset()             self.got_artist = False            self.canvas.mpl_disconnect(self._c1)             if self._use_blit:                 self.ref_artist.set_animated(False)


Question: def disconnect(self):         """Disconnect the callbacks."""        for cid in self.cids:            self.canvas.mpl_disconnect(cid)        try:            c1 = self._c1        except AttributeError:            pass        else:            self.canvas.mpl_disconnect(c1)        for disconnector in self._disconnectors:            disconnector()      def save_offset(self):         pass


Question: "that was already in the registry.")          self._cmaps[name] = cmap.copy()        # Someone may set the extremes of a builtin colormap and want to register it        # with a different name for future lookups. The object would still have the        # builtin name, so we should update it to the registered name        if self._cmaps[name].name != name:            self._cmaps[name].name = name      def unregister(self, name):         """diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py-- a/lib/matplotlib/colors.py++ b/lib/matplotlib/colors.py

Confusing (broken?) colormap name handling Consider the following example in which one creates and registers a new colormap and attempt to use it with the interface. Everything OK so far. Note the difference in the names and . Now when we try to use the new colormap things start to go wrong. As seen from the error message, it's that is looked up instead of the registered colormap name, . Manually looking up works just fine: For this to work as I had expected, one has to make sure that the colormap name and the registered name are the same due to some sort of "double internal name lookup tables" in matplotlib. I found this problem to be very confusing at first since I imported a colormap from another module, registered it, and tried to use it with no luck, e.g. something like: at which point, I expected to be able to refer to my newly registered colormap by the name .


Question: return cmapobject      def __eq__(self, other):        if (not isinstance(other, Colormap) or self.name != other.name or        if (not isinstance(other, Colormap) or                 self.colorbar_extend != other.colorbar_extend):             return False         # To compare lookup tables the Colormaps have to be initialized


Question: if mappable is None:             mappable = cm.ScalarMappable(norm=norm, cmap=cmap) <del>        # Ensure the given mappable's norm has appropriate vmin and vmax        # set even if mappable.draw has not yet been called.        if mappable.get_array() is not None:            mappable.autoscale_None()</del>         self.mappable = mappable         cmap = mappable.cmap         norm = mappable.norm

Update colorbar after changing How can I update a colorbar, after I changed the norm instance of the colorbar? has now effect and throws a -Exception. Consider this example: Output for :


Question: b = np.hstack((b, b[-1] + 1))          # transform from 0-1 to vmin-vmax:        if self.mappable.get_array() is not None:            self.mappable.autoscale_None()         if not self.norm.scaled():            # If we still aren't scaled after autoscaling, use 0, 1 as default             self.norm.vmin = 0             self.norm.vmax = 1         self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(


Question: locator_list = []     sentinel = object()     for ax in fig.axes:        locator_list.append(ax.get_axes_locator())        locator = ax.get_axes_locator()        if locator is not None:            ax.apply_aspect(locator(ax, None))        locator_list.append(locator)         current_pos = ax.get_position(original=False).frozen()         ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)         # override the method that enforces the aspect ratio on the Axes

[Bug]: Setting bboxinches to a Bbox in fig.savefig resizes colorbar Setting bboxinches in fig.savefig to a specified Bbox rather than "tight" resizes the colorbar relative to when bboxinches is not set—the resulting colorbar is a lot larger than it should be. ! ! Calling fig.savefig without bboxinches set first and then calling it again with bbox_inches set produces expected outcome. Calling () prior to savefig also works. MacOS 12.2.1 (Monterey) 1 inline (for interactive), png for plot, also a problem with pdf 10 Jupyter lab 3.2.9 conda


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

UserWarning thrown when all values are "bad", but not when only some are <!--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.--Bug summary If all values passed as colors are "bad" (), a warning is thrown from numpy about converting masked values to null. If some of the values are "bad", this does not happen. Code for reproduction This does not warn: This does: This is difficult to hide since since the warning is not thrown when the figure is being constructed, but when it is shown. Here's a full traceback to show this: <details<summaryFull traceback </summary</detailsExpected outcome I wouldn't expect the second to warn if the first doesn't. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: macOS Matplotlib version: 3.3.1 Matplotlib backend (): MacOSX and Python version: 3.8.5 Jupyter version (if applicable): Replicates in python repl, but also was happening in ipython and jupyter lab Other libraries: Installed with pip [Bug]: ax.errorbar raises for all-nan data on matplotlib 3.6.2 The function raises a error when contains only values. No crash, similar to the case where only some values are NaN. This happens because unconditionally looks for a first finite element in and . Debian 2 TkAgg 2 No response pip


Question: def _safe_first_finite(obj, *, skip_nonfinite=True):     """    Return the first non-None (and optionally finite) element in *obj*.    Return the first finite element in *obj* if one is available and skip_nonfinite is    True. Otherwise return the first element.      This is a method for internal use.     This is a type-independent way of obtaining the first non-None element,    supporting both index access and the iterator protocol.    The first non-None element will be obtained when skip_none is True.    This is a type-independent way of obtaining the first finite element, supporting    both index access and the iterator protocol.     """     def safe_isfinite(val):         if val is None:


Question: raise RuntimeError("matplotlib does not "                            "support generators as input")     else:        return next(val for val in obj if safe_isfinite(val))        return next((val for val in obj if safe_isfinite(val)), safe_first_element(obj))   def sanitize_sequence(data):


Question: """         Save information required to reproduce the current view.         Called before a view is changed, such as during a pan or zoom        initiated by the user. You may return any information you deem        necessary to describe the view.        This method is called before a view is changed, such as during a pan or zoom        initiated by the user.  It returns an opaque object that describes the current        view, in a format compatible with :meth:`_set_view`.         .. note::            Intended to be overridden by new projection types, but if not, the            default implementation saves the view limits. You *must* implement            :meth:`_set_view` if you implement this method.        The default implementation saves the view limits and autoscaling state.        Subclasses may override this as needed, as long as :meth:`_set_view` is also        adjusted accordingly.         """        xmin, xmax = self.get_xlim()        ymin, ymax = self.get_ylim()        return xmin, xmax, ymin, ymax        return {            "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(),            "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(),        }      def _set_view(self, view):         """         Apply a previously saved view.         Called when restoring a view, such as with the navigation buttons.        This method is called when restoring a view (with the return value of        :meth:`_get_view` as argument), such as with the navigation buttons.         .. note::            Intended to be overridden by new projection types, but if not, the            default implementation restores the view limits. You *must*            implement :meth:`_get_view` if you implement this method.        Subclasses that override :meth:`_get_view` also need to override this method        accordingly.         """        xmin, xmax, ymin, ymax = view        self.set_xlim((xmin, xmax))        self.set_ylim((ymin, ymax))        self.set(**view)      def _prepare_view_from_bbox(self, bbox, direction='in',                                 mode=None, twinx=False, twiny=False):diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py-- a/lib/mpl_toolkits/mplot3d/axes3d.py++ b/lib/mpl_toolkits/mplot3d/axes3d.py

handling of zeros in log-scale changes irreversibly after user zoom matplotlib 2.0b1 (but also present before that) Call e.g. and type "k" and "l" to switch both axes to log scale. The points at the two ends, where one of the coordinate is zero, are cropped out. This has been the behavior for a long time and seems reasonable. Now come back to linear scale ("k", "l") and zoom in with the zoom tool to one of the ends of the segment, e.g. xlims=(-0.1, 0.4), ylims=(8.6, 9.1) or something similar. Switching again to log scale now leads to a badly scaled plot, because the axis now goes all the way to (float epsilon). Even this is not unreasonable: the user effectively set his own axes limits, rather than the autocomputed ones, and these limits are invalid in log scale. The problem comes when you go back to the original limits (either "back" or "h" ("home")): even then, log-scale is broken (both axes to to instead of cropping the extremities); in fact, it seems impossible to restore the original behavior of autocomputed axes limits.


Question: def _get_view(self):         # docstring inherited        return (self.get_xlim(), self.get_ylim(), self.get_zlim(),                self.elev, self.azim, self.roll)        return {            "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(),            "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(),            "zlim": self.get_zlim(), "autoscalez_on": self.get_autoscalez_on(),        }, (self.elev, self.azim, self.roll)      def _set_view(self, view):         # docstring inherited        xlim, ylim, zlim, elev, azim, roll = view        self.set(xlim=xlim, ylim=ylim, zlim=zlim)        props, (elev, azim, roll) = view        self.set(**props)         self.elev = elev         self.azim = azim         self.roll = roll


Question: if not hasattr(self, '_facecolors2d'):             self.axes.M = self.axes.get_proj()             self.do_3d_projection()        return self._facecolors2d        return np.asarray(self._facecolors2d)      def get_edgecolor(self):         # docstring inherited

[Bug]: legend for Poly3dCollection fails When plotting an iso surface using Poly3dCollection, Supposed to insert a legend. ! on assumes is a , having the attribute . Consequently, a tuple will be generated if the 's size is not zero. In this case with , is already a and checking for will result in an error. A quick fix would be to have to make sure that colors has . MacOS 2 MacOSX 11.2 No response pip


Question: if not hasattr(self, '_edgecolors2d'):             self.axes.M = self.axes.get_proj()             self.do_3d_projection()        return self._edgecolors2d        return np.asarray(self._edgecolors2d)   def poly_collection_2d_to_3d(col, zs=0, zdir='z'):


Question: and previous_engine is not None:                 _api.warn_external('The figure layout has changed to tight')         finally:            self.set_layout_engine(None)            self.set_layout_engine('none')   def figaspect(arg):

tight layout kwargs have no effect if rc autolayout setting is set (MPL 1.5.3) Bug summary kwargs passed to tight layout do not have an effect if rc the figure.autolayout setting is set Code for reproduction No padding is inserted in the following example if figure.autolayout is set to True in the rc Matplotlib version Tested with a conda installed Matplotlib 1.5.3 on Ubuntu Linux.


Question: Grab the image information from the figure and save as a movie frame.          All keyword arguments in *savefig_kwargs* are passed on to the        `~.Figure.savefig` call that saves the figure.        `~.Figure.savefig` call that saves the figure.  However, several        keyword arguments that are supported by `~.Figure.savefig` may not be        passed as they are controlled by the MovieWriter:        - *dpi*, *bbox_inches*:  These may not be passed because each frame of the           animation much be exactly the same size in pixels.        - *format*: This is controlled by the MovieWriter.         """      @abc.abstractmethod

[Bug]: does not work for writer.grabframe() will make snowflake movie in the example. The example runs fine after removing . https://user- https://user- No response No response 1 No response No response No response None


Question: ``*args, **kw`` are any parameters that should be passed to `setup`.         """        if mpl.rcParams['savefig.bbox'] == 'tight':            _log.info("Disabling savefig.bbox = 'tight', as it may cause "                      "frame size to vary, which is inappropriate for "                      "animation.")         # This particular sequence is what contextlib.contextmanager wants         self.setup(fig, outfile, dpi, *args, **kwargs)        try:            yield self        finally:            self.finish()        with mpl.rc_context({'savefig.bbox': None}):            try:                yield self            finally:                self.finish()   class MovieWriter(AbstractMovieWriter):


Question: def grab_frame(self, **savefig_kwargs):         # docstring inherited<ins>        _validate_grabframe_kwargs(savefig_kwargs)</ins>         _log.debug('MovieWriter.grab_frame: Grabbing frame.')         # Readjust the figure size in case it has been changed by the user.         # All frames must have the same size to save the movie correctly.


Question: def grab_frame(self, **savefig_kwargs):         # docstring inherited         # Creates a filename for saving using basename and counter.<ins>        _validate_grabframe_kwargs(savefig_kwargs)</ins>         path = Path(self._base_temp_name() % self._frame_counter)         self._temp_paths.append(path)  # Record the filename for later use.         self._frame_counter += 1  # Ensures each created name is unique.


Question: self._frames = []      def grab_frame(self, **savefig_kwargs):<ins>        _validate_grabframe_kwargs(savefig_kwargs)</ins>         buf = BytesIO()         self.fig.savefig(             buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})


Question: self._clear_temp = False      def grab_frame(self, **savefig_kwargs):<ins>        _validate_grabframe_kwargs(savefig_kwargs)</ins>         if self.embed_frames:             # Just stop processing if we hit the limit             if self._hit_limit:


Question: # TODO: Right now, after closing the figure, saving a movie won't work         # since GUI widgets are gone. Either need to remove extra code to         # allow for this non-existent use case or find a way to make it work.<del>        if mpl.rcParams['savefig.bbox'] == 'tight':            _log.info("Disabling savefig.bbox = 'tight', as it may cause "                      "frame size to vary, which is inappropriate for "                      "animation.")</del>          facecolor = savefig_kwargs.get('facecolor',                                        mpl.rcParams['savefig.facecolor'])


Question: # canvas._is_saving = True makes the draw_event animation-starting         # callback a no-op; canvas.manager = None prevents resizing the GUI         # widget (both are likewise done in savefig()).        with mpl.rc_context({'savefig.bbox': None}), \             writer.saving(self._fig, filename, dpi), \             cbook._setattr_cm(self._fig.canvas,                               _is_saving=True, manager=None):        with writer.saving(self._fig, filename, dpi), \             cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None):             for anim in all_anim:                 anim._init_draw()  # Clear the initial frame             frame_number = 0


Question: a.set_animated(self._blit)      save_count = _api.deprecate_privatize_attribute("3.7")<ins>def _validate_grabframe_kwargs(savefig_kwargs):    if mpl.rcParams['savefig.bbox'] == 'tight':        raise ValueError(            f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "            "may cause frame size to vary, which is inappropriate for animation."        )    for k in ('dpi', 'bbox_inches', 'format'):        if k in savefig_kwargs:            raise TypeError(                f"grab_frame got an unexpected keyword argument {k!r}"            )</ins>


Question: s = _escape_and_apply_props(s, prop)          _writeln(self.fh, r"\begin{pgfscope}")<ins>        self._print_pgf_clip(gc)</ins>          alpha = gc.get_alpha()         if alpha != 1.0:

PGF output: Contour labels extend beyond figure boundary Bug summary When using contour plots with the PGF backend, contour labels close to the axes can protrude beyond the axis boundary. This was originally posted as a . Code for reproduction (See the [ example][1].) Actual outcome ! Expected outcome The contour label at the top should be clipped, just as in the first image shown in the [ example][1]. Matplotlib version Operating system: Ubuntu 17.10 Matplotlib version: 2.2.2 Matplotlib backend: PGF ( shows , though) Python version: 3.6.3 was installed through . [1]:


Question: """ <ins>    @_api.delete_parameter("3.8", "numdecs")</ins>     def __init__(self, base=10.0, subs=(1.0,), numdecs=4, numticks=None):         """Place ticks on the locations : subs[j] * base**i."""         if numticks is None:

[MNT]: numdecs parameter in takes a parameter numdecs, which is not described in its docstring. I also can't find anywhere the parameter is used in the code. numdec (no s) is used within , but is calculated when needed If numdecs really isn't used, maybe remove it. Otherwise describe it in the docstring.


Question: numticks = 'auto'         self._base = float(base)         self._set_subs(subs)        self.numdecs = numdecs        self._numdecs = numdecs         self.numticks = numticks     @_api.delete_parameter("3.8", "numdecs")     def set_params(self, base=None, subs=None, numdecs=None, numticks=None):         """Set parameters within this locator."""         if base is not None:


Question: if subs is not None:             self._set_subs(subs)         if numdecs is not None:            self.numdecs = numdecs            self._numdecs = numdecs         if numticks is not None:             self.numticks = numticks     numdecs = _api.deprecate_privatize_attribute(        "3.8", addendum="This attribute has no effect.")     def _set_subs(self, subs):         """         Set the minor ticks for the log scaling every ``base**i*subs[j]``.


Question: height : float or array-like             The height(s) of the bars.             Note that if *bottom* has units (e.g. datetime), *height* should be in            units that are a difference from the value of *bottom* (e.g. timedelta).         width : float or array-like, default: 0.8             The width(s) of the bars.             Note that if *x* has units (e.g. datetime), then *width* should be in            units that are a difference (e.g. timedelta) around the *x* values.         bottom : float or array-like, default: 0             The y coordinate(s) of the bottom side(s) of the bars.             Note that if *bottom* has units, then the y-axis will get a Locator and            Formatter appropriate for the units (e.g. dates, or categorical).         align : {'center', 'edge'}, default: 'center'             Alignment of the bars to the *x* coordinates:

[Bug]: bar/barh don't trigger datetime units doesn't check the units of bottom/left parameters to see if the axis needs a different converter. Same applies for : ! This works fine: ! main


Question: x = 0          if orientation == 'vertical':            # It is possible for y (bottom) to contain unit information.            # However, it is also possible for y=0 for the default and height            # to contain unit information.  This will prioritize the units of y.             self._process_unit_info(                [("x", x), ("y", height)], kwargs, convert=False)                [("x", x), ("y", y), ("y", height)], kwargs, convert=False)             if log:                 self.set_yscale('log', nonpositive='clip')         else:  # horizontal            # It is possible for x (left) to contain unit information.            # However, it is also possible for x=0 for the default and width            # to contain unit information.  This will prioritize the units of x.             self._process_unit_info(                [("x", width), ("y", y)], kwargs, convert=False)                [("x", x), ("x", width), ("y", y)], kwargs, convert=False)             if log:                 self.set_xscale('log', nonpositive='clip')


Question: width : float or array-like             The width(s) of the bars.             Note that if *left* has units (e.g. datetime), *width* should be in            units that are a difference from the value of *left* (e.g. timedelta).         height : float or array-like, default: 0.8             The heights of the bars.             Note that if *y* has units (e.g. datetime), then *height* should be in            units that are a difference (e.g. timedelta) around the *y* values.         left : float or array-like, default: 0             The x coordinates of the left side(s) of the bars.             Note that if *left* has units, then the x-axis will get a Locator and            Formatter appropriate for the units (e.g. dates, or categorical).         align : {'center', 'edge'}, default: 'center'             Alignment of the base to the *y* coordinates*:


Question: np.column_stack([ind[where], dep2[where]])])         if ind_dir == "y":             pts = pts[:, ::-1]        self.update_datalim(pts, updatex=True, updatey=True)        up_x = up_y = True        if "transform" in kwargs:            up_x, up_y = kwargs["transform"].contains_branch_seperately(self.transData)        self.update_datalim(pts, updatex=up_x, updatey=up_y)         self.add_collection(collection, autolim=False)         self._request_autoscale_view()         return collection

[Bug]: fillbetween{x} does not respect Axes transform Using an axes transform with and incorrectly sets the axes limits if the Axes coordinates are larger than the data coordinates. Note that code is slightly modified from the , but with the y-data values and threshold reduced by a factor of 10. What you get a plot where the y-limits have been expanded as if I've plotted y-data spanning between (0,1), but get a fill that covers the entire axis space. <img src="https://user-" width=50%Should look like the , but with y axis labels reduced by a factor of 10. My guess is that the y-axis limits are being set by the / values in data coordinates before the transform is applied to actually fill the regions. You will get the expected result as long as the provided Axes coordinate values are less than the extreme values of the y-data itself. For example gives a correct result. <img src="https://user-" width=50%But this issue means that you can't span the axes using this technique if your plotted data does not already span y=(0,1). Windows 10 1 module://matplotlibinline.backendinline 16 3 conda


Question: Tick label font size in points or as a string (e.g., 'large').         labelcolor : color             Tick label color.        labelfontfamily : str            Tick label font.         colors : color             Tick color and label color.         zorder : floatdiff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py-- a/lib/matplotlib/axis.py++ b/lib/matplotlib/axis.py

Add fontfamily/labelfont to tickparams <!-- Welcome! Thanks for thinking of a way to improve Matplotlib. Before creating a new feature request please search the issues for relevant feature requests. --There is no simple way of assigning a fontfamily to tick labels without needing to either override the default fontfamily or setx/yticklabels. We currently have access to color and size, kwarg to change the font would fit here nicely. <!-- For example: I'm always frustrated when [...] because [...] I would like it if [...] happened when I [...] because [...] Here is a sample image of what I am asking for [...] --Add a fontfamily/labelfont kwarg to tick_params <!-- Provide a clear and concise description of a way to accomplish what you want. For example: Add an option so that when [...] [...] will happen --<!-- Add any other context or screenshots about the feature request here. You can also include links to examples of other programs that have something similar to your request. For example: Another project [...] solved this by [...] --


Question: pad=None,         labelsize=None,         labelcolor=None,<ins>        labelfontfamily=None,</ins>         zorder=None,         gridOn=None,  # defaults to axes.grid depending on axes.grid.which         tick1On=True,


Question: self.label1 = mtext.Text(             np.nan, np.nan,             fontsize=labelsize, color=labelcolor, visible=label1On,            rotation=self._labelrotation[1])            fontfamily=labelfontfamily, rotation=self._labelrotation[1])         self.label2 = mtext.Text(             np.nan, np.nan,             fontsize=labelsize, color=labelcolor, visible=label2On,            rotation=self._labelrotation[1])            fontfamily=labelfontfamily, rotation=self._labelrotation[1])          self._apply_tickdir(tickdir)


Question: self.label2.set(rotation=self._labelrotation[1])          label_kw = {k[5:]: v for k, v in kwargs.items()                    if k in ['labelsize', 'labelcolor']}                    if k in ['labelsize', 'labelcolor', 'labelfontfamily']}         self.label1.set(**label_kw)         self.label2.set(**label_kw)


Question: # The following lists may be moved to a more accessible location.         allowed_keys = [             'size', 'width', 'color', 'tickdir', 'pad',            'labelsize', 'labelcolor', 'zorder', 'gridOn',            'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn',             'tick1On', 'tick2On', 'label1On', 'label2On',             'length', 'direction', 'left', 'bottom', 'right', 'top',             'labelleft', 'labelbottom', 'labelright', 'labeltop',


Question: else:         raise ImportError(             "Failed to import any of the following Qt binding modules: {}"            .format(", ".join(_ETS.values())))            .format(", ".join([QT_API for _, QT_API in _candidates]))        ) else:  # We should not get there.     raise AssertionError(f"Unexpected QT_API: {QT_API}") _version_info = tuple(QtCore.QLibraryInfo.version().segments())

[Bug]: VSCode matplotlib interactive mode cannot import Qt bindings Running in VS Code interactive mode, throws an exception . However, PySide6 is installed. <details<summaryError trace</summary</detailsRun in a VS Code interactive cell ipykernel: 6.22.0 ipython: 8.12.0 ipywidgets: 8.0.6 Windows 10 and Windows 11 (2 separate computers) 1 Qt5Agg 10.10 No response pip


Question: """===================================Ellipse with orientation arrow demo===================================This demo shows how to draw an ellipse withan orientation arrow (clockwise or counterclockwise).Compare this to the :doc:`Ellipse collection example</gallery/shapes_and_collections/ellipse_collection>`."""import matplotlib.pyplot as pltfrom matplotlib.markers import MarkerStylefrom matplotlib.patches import Ellipsefrom matplotlib.transforms import Affine2D# Create a figure and axisfig, ax = plt.subplots(subplot_kw={"aspect": "equal"})ellipse = Ellipse(    xy=(2, 4),    width=30,    height=20,    angle=35,    facecolor="none",    edgecolor="b")ax.add_patch(ellipse)# Plot an arrow marker at the end point of minor axisvertices = ellipse.get_co_vertices()t = Affine2D().rotate_deg(ellipse.angle)ax.plot(    vertices[0][0],    vertices[0][1],    color="b",    marker=MarkerStyle(">", "full", t),    markersize=10)# Note: To reverse the orientation arrow, switch the marker type from > to <.plt.show()# %%## .. admonition:: References##    The use of the following functions, methods, classes and modules is shown#    in this example:##    - `matplotlib.patches`#    - `matplotlib.patches.Ellipse`diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py-- a/lib/matplotlib/patches.py++ b/lib/matplotlib/patches.py

Plot ellipse with arrow showing rotation I'm trying to plot an together with an arrow showing a rotation clockwise or counterclockwise as it is shown in that image. ! That can ben implement by another optional argument? No response Plot ellipse with arrow showing rotation I'm trying to plot an together with an arrow showing a rotation clockwise or counterclockwise as it is shown in that image. ! That can ben implement by another optional argument? No response


Question: return self.get_patch_transform().transform(             [(-1, -1), (1, -1), (1, 1), (-1, 1)]) <ins>    def _calculate_length_between_points(self, x0, y0, x1, y1):        return np.sqrt((x1 - x0)**2 + (y1 - y0)**2)    def get_vertices(self):        """        Return the vertices coordinates of the ellipse.        The definition can be found `here <https://en.wikipedia.org/wiki/Ellipse>`_        .. versionadded:: 3.8        """        if self.width < self.height:            ret = self.get_patch_transform().transform([(0, 1), (0, -1)])        else:            ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])        return [tuple(x) for x in ret]    def get_co_vertices(self):        """        Return the co-vertices coordinates of the ellipse.        The definition can be found `here <https://en.wikipedia.org/wiki/Ellipse>`_        .. versionadded:: 3.8        """        if self.width < self.height:            ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])        else:            ret = self.get_patch_transform().transform([(0, 1), (0, -1)])        return [tuple(x) for x in ret]</ins>  class Annulus(Patch):     """


Question: # find the appropriate papertype         width, height = self.figure.get_size_inches()         if papertype == 'auto':            papertype = _get_papertype(                *orientation.swap_if_landscape((width, height)))        paper_width, paper_height = orientation.swap_if_landscape(            papersize[papertype])            _api.warn_deprecated("3.8", name="papertype='auto'",                                 addendum="Pass an explicit paper type, or omit the "                                 "*papertype* argument entirely.")            papertype = _get_papertype(*orientation.swap_if_landscape((width, height)))         if mpl.rcParams['ps.usedistiller']:            # distillers improperly clip eps files if pagesize is too small            if width > paper_width or height > paper_height:                papertype = _get_papertype(                    *orientation.swap_if_landscape((width, height)))                paper_width, paper_height = orientation.swap_if_landscape(                    papersize[papertype])        if is_eps:            paper_width, paper_height = width, height        else:            paper_width, paper_height = orientation.swap_if_landscape(                papersize[papertype])            if mpl.rcParams['ps.usedistiller']:                # distillers improperly clip eps files if pagesize is too small                if width > paper_width or height > paper_height:                    papertype = _get_papertype(                        *orientation.swap_if_landscape((width, height)))                    paper_width, paper_height = orientation.swap_if_landscape(                        papersize[papertype])          # center the figure on the paper         xo = 72 * 0.5 * (paper_width - width)

automatic papersize selection by ps backend is almost certainly broken No minimal example, but the relevant chunk () is Note that the sorting is by name, which means that the size is the first one among "a9, a8, ..., a2, a10, a1, b9, b8, ..., b2, b10, b1" (in that order) that is larger than the requested size -- which makes no sense.


Question: self.figure.get_size_inches())             else:                 if papertype == 'auto':                    _api.warn_deprecated("3.8", name="papertype='auto'",                                         addendum="Pass an explicit paper type, or "                                         "omit the *papertype* argument entirely.")                     papertype = _get_papertype(width, height)                 paper_width, paper_height = papersize[papertype] diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py-- a/lib/matplotlib/rcsetup.py++ b/lib/matplotlib/rcsetup.py


Question: return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s)  <ins>def _validate_papersize(s):    # Re-inline this validator when the 'auto' deprecation expires.    s = ValidateInStrings("ps.papersize",                          ["auto", "letter", "legal", "ledger",                           *[f"{ab}{i}" for ab in "ab" for i in range(11)]],                          ignorecase=True)(s)    if s == "auto":        _api.warn_deprecated("3.8", name="ps.papersize='auto'",                             addendum="Pass an explicit paper type, or omit the "                             "*ps.papersize* rcParam entirely.")    return s</ins> # A validator dedicated to the named line styles, based on the items in # ls_mapper, and a list of possible strings read from Line2D.set_linestyle _validate_named_linestyle = ValidateInStrings(


Question: "tk.window_focus": validate_bool,  # Maintain shell focus for TkAgg      # Set the papersize/type    "ps.papersize":       _ignorecase(["auto", "letter", "legal", "ledger",                                      *[f"{ab}{i}"                                        for ab in "ab" for i in range(11)]]),    "ps.papersize":       _validate_papersize,     "ps.useafm":          validate_bool,     # use ghostscript or xpdf to distill ps output     "ps.usedistiller":    validate_ps_distiller,


Question: size matches the size of *x* and *y*.          """<ins>        # add edgecolors and linewidths to kwargs so they        # can be processed by normailze_kwargs        if edgecolors is not None:            kwargs.update({'edgecolors': edgecolors})        if linewidths is not None:            kwargs.update({'linewidths': linewidths})        kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection)        # re direct linewidth and edgecolor so it can be        # further processed by the rest of the function        linewidths = kwargs.pop('linewidth', None)        edgecolors = kwargs.pop('edgecolor', None)</ins>         # Process **kwargs to handle aliases, conflicts with explicit kwargs:         x, y = self._process_unit_info([("x", x), ("y", y)], kwargs)         # np.ma.ravel yields an ndarray, not a masked array,

Raise when both singular and plural scatter attributes are specified accepts both singular and plural forms of the and attributes. The plural forms are documented in the function signature, but the singular forms actually take precedence if both are specified. This adds some complexity for downstream libraries and confusion for their users (cf. ). Small change: Matplotlib could raise when both the singular and plural forms are specified. Larger change: I will confess that I don't know why the plural forms of the kwargs exist. If there's not a strong reason for the duplication, perhaps they could be deprecated, or at least "formally discouraged"? Scatter does a lot of argument checking on the / parameters (too much at times, ), so there's some local precedence for a lot of handholding. On the other hand, matplotlib generally doesn't raise when both long- and short-forms of kwargs are given edgecolorec`).


Question: # This puts the rectangle into figure-relative coordinates.         inset_locator = _TransformedBoundsLocator(bounds, transform)         bounds = inset_locator(self, None).bounds        projection_class, pkw = self.figure._process_projection_requirements(                bounds, **kwargs)        projection_class, pkw = self.figure._process_projection_requirements(**kwargs)         inset_ax = projection_class(self.figure, bounds, zorder=zorder, **pkw)          # this locator lets the axes move if in data coordinates.diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py-- a/lib/matplotlib/figure.py++ b/lib/matplotlib/figure.py

[MNT]: Do not accept arbitrary positional parameters in Figure.addaxes() ! seen at What are the parameters? This is not readable I'm surprised this works I suspect extra positional parameters are ignored. Documentation: Check whether the parameters do something. If so, document more clearly. if not deprecate extra positional parameters.


Question: args = (kwargs.pop('rect'), )          if isinstance(args[0], Axes):            a = args[0]            a, *extra_args = args             key = a._projection_init             if a.get_figure() is not self:                 raise ValueError(                     "The Axes must have been created in the present figure")         else:            rect = args[0]            rect, *extra_args = args             if not np.isfinite(rect).all():                raise ValueError('all entries in rect must be finite '                                 f'not {rect}')            projection_class, pkw = self._process_projection_requirements(                *args, **kwargs)                raise ValueError(f'all entries in rect must be finite not {rect}')            projection_class, pkw = self._process_projection_requirements(**kwargs)              # create the new axes using the axes class given             a = projection_class(self, rect, **pkw)             key = (projection_class, pkw)        if extra_args:            _api.warn_deprecated(                "3.8",                name="Passing more than one positional argument to Figure.add_axes",                addendum="Any additional positional arguments are currently ignored.")         return self._add_axes_internal(a, key)      @_docstring.dedent_interpd


Question: if (len(args) == 1 and isinstance(args[0], Integral)                     and 100 <= args[0] <= 999):                 args = tuple(map(int, str(args[0])))            projection_class, pkw = self._process_projection_requirements(                *args, **kwargs)            projection_class, pkw = self._process_projection_requirements(**kwargs)             ax = projection_class(self, *args, **pkw)             key = (projection_class, pkw)         return self._add_axes_internal(ax, key)


Question: return im         return None     def _process_projection_requirements(            self, *args, axes_class=None, polar=False, projection=None,            **kwargs):    def _process_projection_requirements(self, *, axes_class=None, polar=False,                                         projection=None, **kwargs):         """         Handle the args/kwargs to add_axes/add_subplot/gca, returning:: diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py-- a/lib/matplotlib/pyplot.py++ b/lib/matplotlib/pyplot.py


Question: if (ax.get_subplotspec() == key             and (kwargs == {}                  or (ax._projection_init                     == fig._process_projection_requirements(*args, **kwargs)))):                     == fig._process_projection_requirements(**kwargs)))):             break     else:         # we have exhausted the known Axes and none match, make a new one!


Question: wspace, hspace : float, default: None             The amount of width/height reserved for space between subfigures,             expressed as a fraction of the average subfigure width/height.            If not given, the values will be inferred from a figure or            rcParams when necessary.            If not given, the values will be inferred from rcParams if using            constrained layout (see `~.ConstrainedLayoutEngine`), or zero if            not using a layout engine.          width_ratios : array-like of length *ncols*, optional             Defines the relative widths of the columns. Each column gets a

[Bug]: wspace and hspace in subfigures not working and in do nothing. Same figure independently of the values of hspace and wspace. No response OS/X 1 MacOSX Python 3.10.9 No response conda


Question: gs = GridSpec(nrows=nrows, ncols=ncols, figure=self,                       wspace=wspace, hspace=hspace,                       width_ratios=width_ratios,                      height_ratios=height_ratios)                      height_ratios=height_ratios,                      left=0, right=1, bottom=0, top=1)          sfarr = np.empty((nrows, ncols), dtype=object)         for i in range(ncols):             for j in range(nrows):                 sfarr[j, i] = self.add_subfigure(gs[j, i], **kwargs)         if self.get_layout_engine() is None and (wspace is not None or                                                 hspace is not None):            # Gridspec wspace and hspace is ignored on subfigure instantiation,            # and no space is left.  So need to account for it here if required.            bottoms, tops, lefts, rights = gs.get_grid_positions(self)            for sfrow, bottom, top in zip(sfarr, bottoms, tops):                for sf, left, right in zip(sfrow, lefts, rights):                    bbox = Bbox.from_extents(left, bottom, right, top)                    sf._redo_transform_rel_fig(bbox=bbox)         if squeeze:             # Discarding unneeded dimensions that equal 1.  If we only have one             # subfigure, just return it instead of a 1-element array.


Question: self.axes.callbacks.process(f"{name}lim_changed", self.axes)             # Call all of the other axes that are shared with this one             for other in self._get_shared_axes():                if other is not self.axes:                    other._axis_map[name]._set_lim(                        v0, v1, emit=False, auto=auto)                    if other.figure != self.figure:                        other.figure.canvas.draw_idle()                if other is self.axes:                    continue                other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto)                if emit:                    other.callbacks.process(f"{name}lim_changed", other)                if other.figure != self.figure:                    other.figure.canvas.draw_idle()          self.stale = True         return v0, v1

xlimchanged not emitted on shared axis <!--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.--Bug summary When an axis is shared with another its registered "xlimchanged" callbacks does not get called when the change is induced by a shared axis (via sharex=). In the setxlim for sibling axis are called with emit=False: I'm very new to matplotlib, so perhaps there is a good reason for this? emit=False seems to disable both continued "inheritance" of axis (why?) and triggering of change callbacks (looking at the code above). It seems like one would at least want to trigger the xlim_changed callbacks as they would be intended to react to any change in axis limits. Edit: Setting emit=True seems to introduce a recursion issue (not sure why but as inheritance seems to be passed along anyway it doesn't really matter). Moving the callback call to outside of the "if emit:"-statement seems to solve the issue as far as I can see when trying it out. Any reason to keep it inside the if-statement?


Question: from numbers import Number import functools<ins>from types import MethodType</ins>  import numpy as np

Error creating AxisGrid with non-default axis class <!--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.--Bug summary Creating using cartopy as raises . Seems to be due to different behaviour of attr. for and other axes instances (like ) where is only a callable. The error is raised in method when trying to access keys from attr. Code for reproduction <!--A minimum code snippet required to reproduce the bug. Please make sure to minimize the number of dependencies required, and provide any necessary plotted data. Avoid using threads, as Matplotlib is (explicitly) not thread-safe.--Actual outcome <!--The output produced by the above code, which may be a screenshot, console output, etc.--Expected outcome <!--A description of the expected outcome from the code snippet--<!--If this used to work in an earlier version of Matplotlib, please note the version it used to work on--Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Ubuntu 18.04.4 LTS Matplotlib version: 3.1.2 (conda-forge) Matplotlib backend: Qt5Agg Python version: 3.7.6 Jupyter version (if applicable): Other libraries:


Question: from matplotlib.gridspec import SubplotSpec  from .axes_divider import Size, SubplotDivider, Dividerfrom .mpl_axes import Axesfrom .mpl_axes import Axes, SimpleAxisArtist   def _tick_only(ax, bottom_on, left_on):     bottom_off = not bottom_on     left_off = not left_on    ax.axis["bottom"].toggle(ticklabels=bottom_off, label=bottom_off)    ax.axis["left"].toggle(ticklabels=left_off, label=left_off)    if isinstance(ax.axis, MethodType):        bottom = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"])        left = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"])    else:        bottom = ax.axis["bottom"]        left = ax.axis["left"]    bottom.toggle(ticklabels=bottom_off, label=bottom_off)    left.toggle(ticklabels=left_off, label=left_off)   class CbarAxesBase:


Question: 'leftparen'                : 40,     'rightparen'               : 41,     'bigoplus'                 : 10753,<del>    'leftangle'                : 10216,    'rightangle'               : 10217,</del>     'leftbrace'                : 124,     'rightbrace'               : 125,     'jmath'                    : 567,

[ENH]: Missing mathematical operations Just browsed the available mathematical operators and compared with the ones defined. (One can probably do a similar thing with other groups of symbols.) The following are missing (as in not defined in in , in hex): For the corresponding symbols, see: For LaTeX names, see: One should probably be a bit discriminate when adding these, but at least those in standard LaTeX (like = ) and those from AMS should be supported.


Question: 'guilsinglleft'            : 8249,     'plus'                     : 43,     'thorn'                    : 254,    'dagger'                   : 8224    'dagger'                   : 8224,    'increment'                : 8710,    'smallin'                  : 8714,    'notsmallowns'             : 8716,    'smallowns'                : 8717,    'QED'                      : 8718,    'rightangle'               : 8735,    'smallintclockwise'        : 8753,    'smallvarointclockwise'    : 8754,    'smallointctrcclockwise'   : 8755,    'ratio'                    : 8758,    'minuscolon'               : 8761,    'dotsminusdots'            : 8762,    'sinewave'                 : 8767,    'simneqq'                  : 8774,    'nlesssim'                 : 8820,    'ngtrsim'                  : 8821,    'nlessgtr'                 : 8824,    'ngtrless'                 : 8825,    'cupleftarrow'             : 8844,    'oequal'                   : 8860,    'rightassert'              : 8870,    'rightModels'              : 8875,    'hermitmatrix'             : 8889,    'barvee'                   : 8893,    'measuredrightangle'       : 8894,    'varlrtriangle'            : 8895,    'equalparallel'            : 8917,    'npreccurlyeq'             : 8928,    'nsucccurlyeq'             : 8929,    'nsqsubseteq'              : 8930,    'nsqsupseteq'              : 8931,    'sqsubsetneq'              : 8932,    'sqsupsetneq'              : 8933,    'disin'                    : 8946,    'varisins'                 : 8947,    'isins'                    : 8948,    'isindot'                  : 8949,    'varisinobar'              : 8950,    'isinobar'                 : 8951,    'isinvb'                   : 8952,    'isinE'                    : 8953,    'nisd'                     : 8954,    'varnis'                   : 8955,    'nis'                      : 8956,    'varniobar'                : 8957,    'niobar'                   : 8958,    'bagmember'                : 8959,    'triangle'                 : 9651 }  # Each element is a 4-tuple of the form:


Question: _legend_kw_doc_base) _docstring.interpd.update(_legend_kw_doc=_legend_kw_both_st) <ins>_legend_kw_set_loc_st = (    _loc_doc_base.format(parent='axes/figure',                         default=":rc:`legend.loc` for Axes, 'upper right' for Figure",                         best=_loc_doc_best, outside=_outside_doc))_docstring.interpd.update(_legend_kw_set_loc_doc=_legend_kw_set_loc_st)</ins>  class Legend(Artist):     """

[ENH]: Add public method to update object's loc property . I'm working on the issue The object's property can only be set at initialization time. There is no public method to update the property when the object has been created. It can now be understood as implemented as follows: Desired implementation No response


Question: )         self.parent = parent <del>        loc0 = loc        self._loc_used_default = loc is None        if loc is None:            loc = mpl.rcParams["legend.loc"]            if not self.isaxes and loc in [0, 'best']:                loc = 'upper right'        type_err_message = ("loc must be string, coordinate tuple, or"                            f" an integer 0-10, not {loc!r}")        # handle outside legends:        self._outside_loc = None        if isinstance(loc, str):            if loc.split()[0] == 'outside':                # strip outside:                loc = loc.split('outside ')[1]                # strip "center" at the beginning                self._outside_loc = loc.replace('center ', '')                # strip first                self._outside_loc = self._outside_loc.split()[0]                locs = loc.split()                if len(locs) > 1 and locs[0] in ('right', 'left'):                    # locs doesn't accept "left upper", etc, so swap                    if locs[0] != 'center':                        locs = locs[::-1]                    loc = locs[0] + ' ' + locs[1]            # check that loc is in acceptable strings            loc = _api.check_getitem(self.codes, loc=loc)        elif np.iterable(loc):            # coerce iterable into tuple            loc = tuple(loc)            # validate the tuple represents Real coordinates            if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):                raise ValueError(type_err_message)        elif isinstance(loc, int):            # validate the integer represents a string numeric value            if loc < 0 or loc > 10:                raise ValueError(type_err_message)        else:            # all other cases are invalid values of loc            raise ValueError(type_err_message)        if self.isaxes and self._outside_loc:            raise ValueError(                f"'outside' option for loc='{loc0}' keyword argument only "                "works for figure legends")        if not self.isaxes and loc == 0:            raise ValueError(                "Automatic legend placement (loc='best') not implemented for "                "figure legend")</del>         self._mode = mode         self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)


Question: # init with null renderer         self._init_legend_box(handles, labels, markerfirst)         tmp = self._loc_used_default        self._set_loc(loc)        self._loc_used_default = tmp  # ignore changes done by _set_loc        # Set legend location        self.set_loc(loc)          # figure out title font properties:         if title_fontsize is not None and title_fontproperties is not None:


Question: a.set_transform(self.get_transform()) <ins>    @_docstring.dedent_interpd    def set_loc(self, loc=None):        """        Set the location of the legend.        .. versionadded:: 3.8        Parameters        ----------        %(_legend_kw_set_loc_doc)s        """        loc0 = loc        self._loc_used_default = loc is None        if loc is None:            loc = mpl.rcParams["legend.loc"]            if not self.isaxes and loc in [0, 'best']:                loc = 'upper right'        type_err_message = ("loc must be string, coordinate tuple, or"                            f" an integer 0-10, not {loc!r}")        # handle outside legends:        self._outside_loc = None        if isinstance(loc, str):            if loc.split()[0] == 'outside':                # strip outside:                loc = loc.split('outside ')[1]                # strip "center" at the beginning                self._outside_loc = loc.replace('center ', '')                # strip first                self._outside_loc = self._outside_loc.split()[0]                locs = loc.split()                if len(locs) > 1 and locs[0] in ('right', 'left'):                    # locs doesn't accept "left upper", etc, so swap                    if locs[0] != 'center':                        locs = locs[::-1]                    loc = locs[0] + ' ' + locs[1]            # check that loc is in acceptable strings            loc = _api.check_getitem(self.codes, loc=loc)        elif np.iterable(loc):            # coerce iterable into tuple            loc = tuple(loc)            # validate the tuple represents Real coordinates            if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):                raise ValueError(type_err_message)        elif isinstance(loc, int):            # validate the integer represents a string numeric value            if loc < 0 or loc > 10:                raise ValueError(type_err_message)        else:            # all other cases are invalid values of loc            raise ValueError(type_err_message)        if self.isaxes and self._outside_loc:            raise ValueError(                f"'outside' option for loc='{loc0}' keyword argument only "                "works for figure legends")        if not self.isaxes and loc == 0:            raise ValueError(                "Automatic legend placement (loc='best') not implemented for "                "figure legend")        tmp = self._loc_used_default        self._set_loc(loc)        self._loc_used_default = tmp  # ignore changes done by _set_loc</ins>     def _set_loc(self, loc):         # find_offset function will be provided to _legend_box and         # _legend_box will draw itself at the location of the return


Question: if len(text.vertices) == 0:             return         xmin, ymin = text.vertices.min(axis=0)        xmax, ymax = text.vertices.max(axis=0)        width = xmax - xmin        height = ymax - ymin        max_dim = max(width, height)        self._transform = Affine2D() \            .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \            .scale(1.0 / max_dim)        bbox = text.get_extents()        max_dim = max(bbox.width, bbox.height)        self._transform = (            Affine2D()            .translate(-bbox.xmin + 0.5 * -bbox.width, -bbox.ymin + 0.5 * -bbox.height)            .scale(1.0 / max_dim))         self._path = text         self._snap = False

[Bug]: Star marker (using mathtext) is not center-aligned Is there any other way to center-align mathtext markers? ! All markers using mathtext were not center-aligned center-aligned markers (whether mathtext is used or not) No response No response 1 No response No response No response pip


Question: if mincnt is None:                 mincnt = 0             accum = np.array(                [reduce_C_function(acc) if len(acc) > mincnt else np.nan                [reduce_C_function(acc) if len(acc) >= mincnt else np.nan                  for Cs_at_i in [Cs_at_i1, Cs_at_i2]                  for acc in Cs_at_i[1:]],  # [1:] drops out-of-range points.                 float)

Inconsistent behavior of hexbins mincnt parameter, depending on C parameter <!--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.--Bug summary Different behavior of s parameter, depending on whether the parameter is supplied. Code for reproduction See below for a full snippet. Actual outcome <!--The output produced by the above code, which may be a screenshot, console output, etc.--With no parameter specified, a value of works as I intuitively expect: it plots only gridpoints that have at least 1 datum. With specified but not specified, I can kind of understand why it defaults to only gridpoints that have at least one data point, as otherwise the has to yield a sensible output for an empty array. Expected outcome However, with I'd expect the same gridpoints to be plotted, whether is supplied or not... Additional resources The most recent commit that changed how I should interpret : The lines in current code that deal with when is : The lines in current code that deal with when is not : Resolution Although it might mean a breaking change, I'd prefer to see the behavior of being applied also when isn't None (i.e. , rather than the current ). I'm happy to supply a PR if the matplotlib maintainers agree. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Linux 4.15.0-38-generic Matplotlib version: 3.0.2 Matplotlib backend (): Python version: 3.6.7 (default, Oct 22 2018, 11:32:17) Jupyter version (if applicable): Other libraries: numpy: 1.15.3 <!--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--Inconsistent behavior of hexbins mincnt parameter, depending on C parameter <!--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.--Bug summary Different behavior of s parameter, depending on whether the parameter is supplied. Code for reproduction See below for a full snippet.


Question: if mincnt is None:                 mincnt = 0             accum = np.array(                [reduce_C_function(acc) if len(acc) > mincnt else np.nan                [reduce_C_function(acc) if len(acc) >= mincnt else np.nan                  for Cs_at_i in [Cs_at_i1, Cs_at_i2]                  for acc in Cs_at_i[1:]],  # [1:] drops out-of-range points.                 float)

Actual outcome <!--The output produced by the above code, which may be a screenshot, console output, etc.--With no parameter specified, a value of works as I intuitively expect: it plots only gridpoints that have at least 1 datum. With specified but not specified, I can kind of understand why it defaults to only gridpoints that have at least one data point, as otherwise the has to yield a sensible output for an empty array. Expected outcome However, with I'd expect the same gridpoints to be plotted, whether is supplied or not... Additional resources The most recent commit that changed how I should interpret : The lines in current code that deal with when is : The lines in current code that deal with when is not : Resolution Although it might mean a breaking change, I'd prefer to see the behavior of being applied also when isn't None (i.e. , rather than the current ). I'm happy to supply a PR if the matplotlib maintainers agree. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Linux 4.15.0-38-generic Matplotlib version: 3.0.2 Matplotlib backend (): Python version: 3.6.7 (default, Oct 22 2018, 11:32:17) Jupyter version (if applicable): Other libraries: numpy: 1.15.3 <!--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--


Question: background_gradient[:, :, :3] = [1, 1, 0]     background_gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]]  # alpha channel     ax.imshow(background_gradient, interpolation="bicubic", zorder=0.1,              extent=(0, 1, 0, 1), transform=ax.transAxes, aspect="auto")              extent=(0, 1, 0, 1), transform=ax.transAxes)      plt.show() diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py-- a/lib/matplotlib/axes/_axes.py++ b/lib/matplotlib/axes/_axes.py

imshow() should not modify axes aspect if transform != ax.transData. Currently, imshow() automatically updates the axes aspect via the kwarg; its default, None, means , which is "equal" by default (i.e., square image pixels). If the kwarg is also passed, and set to something else[1] than (the default), then setting the aspect is clearly not useful (the image is not going to be drawn in data coordinates so it should not affect the relative size of x- and y-data). In that case, the default of should just mean "don't modify the aspect". [1] Really, this should be "something that does not contains transData as a branch", as in . The current behavior is the reason why and need to explicitly set the aspect to "auto" in or after the last imshow() call (otherwise, some head-scratching occurs). On the other hand, making this change would once again lead to some seriously non-obvious interaction between parameters (the meaning of depends on the value of ), which I'm not sure is great either :/ Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: linux Matplotlib version: master/any Matplotlib backend (): qt5agg Python version: 37


Question: The input may either be actual RGB(A) data, or 2D scalar data, which         will be rendered as a pseudocolor image. For displaying a grayscale        image set up the colormapping using the parameters        image, set up the colormapping using the parameters         ``cmap='gray', vmin=0, vmax=255``.          The number of pixels used to render an image is set by the Axes size        and the *dpi* of the figure. This can lead to aliasing artifacts when        the image is resampled because the displayed image size will usually        and the figure *dpi*. This can lead to aliasing artifacts when        the image is resampled, because the displayed image size will usually         not match the size of *X* (see         :doc:`/gallery/images_contours_and_fields/image_antialiasing`).         The resampling can be controlled via the *interpolation* parameter


Question: This parameter is ignored if *X* is RGB(A). <del>        aspect : {'equal', 'auto'} or float, default: :rc:`image.aspect`</del><ins>        aspect : {'equal', 'auto'} or float or None, default: None</ins>             The aspect ratio of the Axes.  This parameter is particularly             relevant for images since it determines whether data pixels are             square.


Question: that the data fit in the Axes. In general, this will result in               non-square pixels. <ins>            Normally, None (the default) means to use :rc:`image.aspect`.  However, if            the image uses a transform that does not contain the axes data transform,            then None means to not modify the axes aspect at all (in that case, directly            call `.Axes.set_aspect` if desired).</ins>         interpolation : str, default: :rc:`image.interpolation`             The interpolation method used.


Question: `~matplotlib.pyplot.imshow` expects RGB images adopting the straight         (unassociated) alpha representation.         """<del>        if aspect is None:            aspect = mpl.rcParams['image.aspect']        self.set_aspect(aspect)</del>         im = mimage.AxesImage(self, cmap=cmap, norm=norm,                               interpolation=interpolation, origin=origin,                               extent=extent, filternorm=filternorm,


Question: interpolation_stage=interpolation_stage,                               **kwargs) <ins>        if aspect is None and not (                im.is_transform_set()                and not im.get_transform().contains_branch(self.transData)):            aspect = mpl.rcParams['image.aspect']        if aspect is not None:            self.set_aspect(aspect)</ins>         im.set_data(X)         im.set_alpha(alpha)         if im.get_clip_path() is None:


Question: # data limits should not be adjusted.             datalim = []         line = mlines._AxLine(xy1, xy2, slope, **kwargs)        line = mlines.AxLine(xy1, xy2, slope, **kwargs)         # Like add_line, but correctly handling data limits.         self._set_artist_props(line)         if line.get_clip_path() is None:diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py-- a/lib/matplotlib/lines.py++ b/lib/matplotlib/lines.py

[ENH]: Add setters for AxLine.xy1, .xy2, .slope Currently the control points / slope of the artist returned by axline() cannot be (publically) modified after being instantiated. It would be nice if the relevant properties (xy1, xy2, slope) had setters (following normal Artist design). For simplicity it is probably enough if we don't let one set xy2 if slope is set and vice-versa (i.e. whether axline is specified by 2 points or by point-and-slope is locked in). Note that while I do have a use case for changing a previously set xy1/xy2, wanting to switch between the two different representations seems rarer to me(?) This would likely also make AxLine public. No response_


Question: return self._linestyle in ('--', '-.', ':')  class _AxLine(Line2D):class AxLine(Line2D):     """     A helper class that implements `~.Axes.axline`, by recomputing the artist     transform at draw time.     """      def __init__(self, xy1, xy2, slope, **kwargs):        """        Parameters        ----------        xy1 : (float, float)            The first set of (x, y) coordinates for the line to pass through.        xy2 : (float, float) or None            The second set of (x, y) coordinates for the line to pass through.            Either *xy2* or *slope* has to be given.        slope : float or None            The slope of the line. Either *xy2* or *slope* has to be given.        """         super().__init__([0, 1], [0, 1], **kwargs)          if (xy2 is None and slope is None or


Question: self._transformed_path = None  # Force regen.         super().draw(renderer) <ins>    def get_xy1(self):        """        Return the *xy1* value of the line.        """        return self._xy1    def get_xy2(self):        """        Return the *xy2* value of the line.        """        return self._xy2    def get_slope(self):        """        Return the *slope* value of the line.        """        return self._slope    def set_xy1(self, x, y):        """        Set the *xy1* value of the line.        Parameters        ----------        x, y : float            Points for the line to pass through.        """        self._xy1 = x, y    def set_xy2(self, x, y):        """        Set the *xy2* value of the line.        Parameters        ----------        x, y : float            Points for the line to pass through.        """        if self._slope is None:            self._xy2 = x, y        else:            raise ValueError("Cannot set an 'xy2' value while 'slope' is set;"                             " they differ but their functionalities overlap")    def set_slope(self, slope):        """        Set the *slope* value of the line.        Parameters        ----------        slope : float            The slope of the line.        """        if self._xy2 is None:            self._slope = slope        else:            raise ValueError("Cannot set a 'slope' value while 'xy2' is set;"                             " they differ but their functionalities overlap")</ins>  class VertexSelector:     """


Question: # docstring inherited         if renderer is None:             renderer = self.figure._get_renderer()        self.update_positions(renderer)         return Bbox.union([child.get_window_extent(renderer)                            for child in self.get_children()])      def get_tightbbox(self, renderer=None):         # docstring inherited        if renderer is None:            renderer = self.figure._get_renderer()        self.update_positions(renderer)         return Bbox.union([child.get_tightbbox(renderer)                            for child in self.get_children()])

[Bug]: AnnotationBbox does not return correct windowextent before first draw I’m trying to use a constrained layout in a visualization that contains an artist that is an instance of AnnotationBbox, and matplotlib raises a warning saying constrained layout is not applied. The visual effect is not evident in this simple example, but it becomes very clear once we have multiple panels. UserWarning: constrainedlayout not applied because axes sizes collapsed to zero. Try making figure larger or axes decorations smaller. No warning should appear The following works without any warning The problem with the constrained layout is more evident if I have two or more panels. One way of fixing it (i.e. getting rid of the warning and bad functionality) is to do ab.setinlayout(False) before doing ax.addartist(ab). This was first posted on Discourse Ubuntu 22 2 No response No response No response_ pip


Question: self.yaxis.tick_left()         ax2.xaxis.set_visible(False)         ax2.patch.set_visible(False)<ins>        ax2.xaxis.units = self.xaxis.units</ins>         return ax2      def twiny(self):

[Bug]: dataLims get replaced by inf for charts with twinx if ax1 is a stackplot Bringing this over from Discourse In Matplotlib 3.4.0 and later versions, when using twin x-axis (two-y-axis charts), the data limits (dataLims) of the first axis (ax1) get changed to ±inf when plotting a stackplot on the second axis (ax2), which is unexpected. This prints It caught me off guard that the ax1 dataLims get changed to ±inf. It’s interesting that, if you swap the plot order (i.e. do plot on ax1 and stackplot on ax2, the dataLims don’t get replaced by infs: [-22. 26.585 ] / [-2. 0. ] / ). To not change ax1 dataLims, since I made no changes to it, like with matplotlib versions prior to 3.4.0. I went throught he changelogs and couldn't find (or perhaps missed it) that this behavior change was intentional. No response Windows 10 0 through 3.7.1 9 for old versions, 3.11.3 for new versions No response_ pip


Question: self.xaxis.tick_bottom()         ax2.yaxis.set_visible(False)         ax2.patch.set_visible(False)<ins>        ax2.yaxis.units = self.yaxis.units</ins>         return ax2      def get_shared_x_axes(self):


Question: else:                 X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))                 shading = 'flat'            C = cbook.safe_masked_invalid(C)            C = cbook.safe_masked_invalid(C, copy=True)             return X, Y, C, shading          if len(args) == 3:

[Bug]: pcolormesh writing to input mask When receives a masked array, it seems to be writing back to the mask. Since numpy 1.24 this now causes to fail if the mask is read-only. No error The code above runs fine with numpy v1.23, although the output from was already read-only at that version. From numpy release notes, this looks like the likely reason for the change: Aside from the new error, if a user passes a masked array that has nans or infs at the unmasked points, we are modifying their input array with the call to . I guess we just need to take a copy somewhere? RHEL7 1 QtAgg 11.3 N/A conda


Question: Y = _interp_grid(Y.T).T                 shading = 'flat'         C = cbook.safe_masked_invalid(C)        C = cbook.safe_masked_invalid(C, copy=True)         return X, Y, C, shading      @_preprocess_data()


Question: # unit conversion allows e.g. datetime objects as axis values             X, Y = args[:2]             X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs)            X, Y = [cbook.safe_masked_invalid(a) for a in [X, Y]]            X, Y = [cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]]              if funcname == 'pcolormesh':                 if np.ma.is_masked(X) or np.ma.is_masked(Y):

[Bug]: pcolor writing to read-only input mask When the parameter or is a masked array with a read-only mask, fails with Traceback (most recent call last): File "<stdin", line 1, in <moduleFile "/Library/Python/3.9/lib/python/site-", line 2773, in pcolormesh ret = gca().pcolormesh( File "/Library/Python/3.9/lib/python/site-", line 1442, in inner return func(ax, map(sanitizesequence, args), kwargs) File "/Library/Python/3.9/lib/python/site-", line 6220, in pcolormesh X, Y, C, shading = self.pcolorargs('pcolormesh', args, File "/Library/Python/3.9/lib/python/site-", line 5713, in pcolorargs X, Y = [cbook.safemaskedinvalid(a) for a in [X, Y]] File "/Library/Python/3.9/lib/python/site-", line 5713, in <listcompX, Y = [cbook.safemaskedinvalid(a) for a in [X, Y]] File "/Library/Python/3.9/lib/python/site-", line 715, in safemaskedinvalid xm = (x, copy=False) File "/Library/Python/3.9/lib/python/site-", line 2360, in maskedinvalid res = maskedwhere(~(np.isfinite(a)), a, copy=copy) File "/Library/Python/3.9/lib/python/site-", line 1942, in maskedwhere = shrinkmask(cond) File "/Library/Python/3.9/lib/python/site-", line 3516, in mask self.setmask(value) File "/Library/Python/3.9/lib/python/site-", line 3462, in setmask_ = mask ValueError: array is read-only No error The error still exists because I missed the following code in fixing : And I will fix it as well if allowed. OS/X 1 MacOSX 9 No response_ None


Question: *[np.ravel(np.ma.filled(t, np.nan)) for t in [xs, ys, zs]])         s = np.ma.ravel(s)  # This doesn't have to match x, y in size.         xs, ys, zs, s, c = cbook.delete_masked_points(xs, ys, zs, s, c)        xs, ys, zs, s, c, color = cbook.delete_masked_points(            xs, ys, zs, s, c, kwargs.get('color', None)            )        if kwargs.get('color', None):            kwargs['color'] = color          # For xs and ys, 2D scatter() will do the copying.         if np.may_share_memory(zs_orig, zs):  # Avoid unnecessary copies.

[Bug]: ax.scatter (projection='3d') - incorrect handling of NaN In axis 3D projection NaN values are not handled correctly, apparently the values are masked out (as it should be) but the mask is not applied to a color array that may not have NaN in the same position. A plot with the first and 3rd data point. Unconditionally reproducible. I have not seen this before, but I may never have called it this way before. Fedora 38 1 TkAgg 11.4 IPython 8.14.0 pip


Question: hatches=(None,), alpha=None, origin=None, extent=None,                  cmap=None, colors=None, norm=None, vmin=None, vmax=None,                  extend='neither', antialiased=None, nchunk=0, locator=None,                 transform=None, negative_linestyles=None,                 transform=None, negative_linestyles=None, clip_path=None,                  **kwargs):         """         Draw contour lines or filled regions, depending on

Cleaning up kwargs in ContourSet This is a continuation of a mailing list thread where we talked about how to clip a plot inside a polygon. It is a very useful application for people who are visualizing data on maps since often times we want to plot everything inside one region (country, state or province). Currently for many types of plots this is not that hard to do using the clippath keyword for most of the plotting functions, since the kwargs are usually used to modify properties of the artists to be generated by the plotting function. For example, suppose that I had a polygon defining the border of a country, poly, and some data to overlay on top. Does what I want because the kwargs of pcolor let me modify the underlying PolyCollection instance. However, there are a few plotting functions where I cannot do this, most notably in contour / contourf: Will work but the clippath kwarg gets completely ignored. To get the result I want, I need to store the output of contourf and use the setclippath method on each collection instance: So I looked at the code in and realized that no kwargs get passed when instantiating the collections. mentioned that this might call for an overhaul of how the kwargs get passed into a ContourSet. His suggestion was either adding a setclippath method directly to ContourSet, or a more thorough change of how the kwargs are getting passed so they are more consistent with the other plotting functions. Ideally, I would prefer the latter case since then for my usage case I could always get what I want just by passing in the kwarg directly. Additionally it would make the functionality of contour(f) more similar to the other plotting functions, ie some of the kwargs can be passed to the collections. Any thoughts on this?


Question: super().__init__(             antialiaseds=antialiased,             alpha=alpha,<ins>            clip_path=clip_path,</ins>             transform=transform,         )         self.axes = ax


Question: The default is taken from :rc:`contour.algorithm`. <ins>clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`    Set the clip path.  See `~matplotlib.artist.Artist.set_clip_path`.    .. versionadded:: 3.8</ins> data : indexable object, optional     DATA_PARAMETER_PLACEHOLDER


Question: minor : bool, default: False             If ``False``, set the major ticks; if ``True``, the minor ticks.         **kwargs            `.Text` properties for the labels. These take effect only if you            pass *labels*. In other cases, please use `~.Axes.tick_params`.            `.Text` properties for the labels. Using these is only allowed if            you pass *labels*. In other cases, please use `~.Axes.tick_params`.          Notes         -----

[Bug]: setticks provides mysterious error message errors with . Two issues here: is incorrect for , I should have done . It's a bit annoying that is the kwarg for some things and for . Second, the error message is somewhat annoying as I would have expected this call to work or give me an error for an incorrect kwarg. No response No response main No response No response No response None


Question: ticks.         """         if labels is None and kwargs:            raise ValueError('labels argument cannot be None when '                             'kwargs are passed')            first_key = next(iter(kwargs))            raise ValueError(                f"Incorrect use of keyword argument {first_key!r}. Keyword arguments "                "other than 'minor' modify the text labels and can only be used if "                "'labels' are passed as well.")         result = self._set_tick_locations(ticks, minor=minor)         if labels is not None:             self.set_ticklabels(labels, minor=minor, **kwargs)


Question: raise RuntimeError("No draw method should be called")      def __call__(self, ax, renderer):<ins>        if renderer is None:            renderer = ax.figure._get_renderer()</ins>         self.axes = ax         bbox = self.get_window_extent(renderer)         px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer)

[Bug]: Error while creating inset axes using Unable to create the inset axes in a plot using the code (following the first example on the website as posted posted below. I was expecting to add an empty box towards the top right of the first subplot (with axes ) in the figure, as shown in the demo on the website. No response Arch linux: 6.4.2-arch1-1 2 module://matplotlibinline.backend_inline Python 3.8.17 Jupyter lab: 3.6.5 conda


Question: # note that here we do not permanently set the figures engine to         # tight_layout but rather just perform the layout in place and remove         # any previous engines.        engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad,                                   rect=rect)        engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)         try:             previous_engine = self.get_layout_engine()             self.set_layout_engine(engine)             engine.execute(self)            if not isinstance(previous_engine, TightLayoutEngine) \                    and previous_engine is not None:            if previous_engine is not None and not isinstance(                previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine)            ):                 _api.warn_external('The figure layout has changed to tight')         finally:             self.set_layout_engine('none')

[Bug]: calling fig.tightlayout multiple times Calling multiple times warns. no-warning. does not show up in 3.7.1, does show up in 3.7.2. Have not bisected this yet (or checked main). From looking at the code I suspect / / which is from me . xref I suspect the fix is to not warn if we set the place holder due to . Arch 2 any 11 No response_ pip


Question: # path always starts with a MOVETO, and we consider there's an implicit         # MOVETO (closing the last path) at the end.         movetos = (codes == Path.MOVETO).nonzero()[0]        start = movetos[movetos < idx][-1]        start = movetos[movetos <= idx][-1]         try:             stop = movetos[movetos > idx][0]         except IndexError:

[Bug]: labels can't be placed at start of contours For some combinations of contour shape and fontsize, the automatic label placement tries to put the label right at the start of the contour. This is not currently possible on . With v3.7.1 I get ! The fix is easy: Writing a test seems harder. I tried pasting the above code into a test, and it passed against . I assume that is because the tests have different "screen space" than when I just run it as a script. Marking as "release critical" because this is a regression. RHEL7 main QtAgg 11.3 N/A git checkout


Question: from contextlib import ExitStack import functools import inspect<del>import itertools</del> import logging from numbers import Real from operator import attrgetter

[MNT]: Make cyclers indexable and rely on indexing them rather than Currently the propcycle code (in processplotvarargs) creates an over the Cycler instance to yield the successive line properties. objects are opaque, which creates some difficulties e.g. in parsescattercolorargs which needs to use self.getpatchesforfill.getnextcolor to workaround the impossibility to peek at the next color in the cycle without advancing the iterator, and also with pickling (currently we just completely drop the cycler state when pickling/unpickling). An alternative would be to drop the use of and instead simply store in processplotvarargs both the Cycler object and an integer index, which simply gets incremented at each use, and add support for indexing Cyclers (perhaps something like or forcing the caller to explicitly write , to avoid confusion with the fact that returns the finite, non-cycled length). This would both make peeking at the next color easier, and directly solve the issue of picklability. No response


Question: self.command = command         self.set_prop_cycle(None)     def __getstate__(self):        # note: it is not possible to pickle a generator (and thus a cycler).        return {'command': self.command}    def __setstate__(self, state):        self.__dict__ = state.copy()        self.set_prop_cycle(None)     def set_prop_cycle(self, cycler):         if cycler is None:             cycler = mpl.rcParams['axes.prop_cycle']        self.prop_cycler = itertools.cycle(cycler)        self._idx = 0        self._cycler_items = [*cycler]         self._prop_keys = cycler.keys  # This should make a copy      def __call__(self, axes, *args, data=None, **kwargs):


Question: """Return the next color in the cycle."""         if 'color' not in self._prop_keys:             return 'k'        return next(self.prop_cycler)['color']        c = self._cycler_items[self._idx]['color']        self._idx = (self._idx + 1) % len(self._cycler_items)        return c      def _getdefaults(self, ignore, kw):         """


Question: if any(kw.get(k, None) is None for k in prop_keys):             # Need to copy this dictionary or else the next time around             # in the cycle, the dictionary could be missing entries.            default_dict = next(self.prop_cycler).copy()            default_dict = self._cycler_items[self._idx].copy()            self._idx = (self._idx + 1) % len(self._cycler_items)             for p in ignore:                 default_dict.pop(p, None)         else:diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py-- a/lib/matplotlib/sankey.py++ b/lib/matplotlib/sankey.py


Question: fc = kwargs.pop('fc', kwargs.pop('facecolor', None))             lw = kwargs.pop('lw', kwargs.pop('linewidth', None))         if fc is None:            fc = next(self.ax._get_patches_for_fill.prop_cycler)['color']            fc = self.ax._get_patches_for_fill.get_next_color()         patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)         self.ax.add_patch(patch)


Question: return self._paths      def set_paths(self, paths):        raise NotImplementedError        self._paths = paths        self.stale = True      def get_transforms(self):         return self._transforms

[ENH]: ContourSet.set_paths To get contour labelling working with its special transforms, Cartopy has a where it replaces all the paths on the with transformed versions. This currently looks like which doesn’t smell very good. The above would smell better as


Question: self.set_sizes(sizes)         self.stale = True <del>    def set_paths(self, paths):        self._paths = paths        self.stale = True</del>     def get_paths(self):         return self._paths


Question: return linewidths, dashes     def get_antialiased(self):        """        Get the antialiasing state for rendering.        Returns        -------        array of bools        """        return self._antialiaseds     def set_antialiased(self, aa):         """         Set the antialiasing state for rendering.diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py-- a/lib/matplotlib/contour.py++ b/lib/matplotlib/contour.py

[Bug]: ContourSet.antialiased attribute not present The new does not have an attribute. This causes failures in . With v3.7.1, I can access this attribute. Marking as release critical, as this is a regression. RHEL7 main QtAgg 11.4 N/A git checkout


Question: alpha = property(lambda self: self.get_alpha())     linestyles = property(lambda self: self._orig_linestyles) <ins>    @_api.deprecated("3.8", alternative="set_antialiased or get_antialiased",                     addendum="Note that get_antialiased returns an array.")    @property    def antialiased(self):        return all(self.get_antialiased())    @antialiased.setter    def antialiased(self, aa):        self.set_antialiased(aa)</ins>     @_api.deprecated("3.8")     @property     def collections(self):


Question: The screen units to use (pixels or points) for the offset input.         """         self._artist = artist        self._ref_coord = ref_coord        x, y = ref_coord  # Make copy when ref_coord is an array (and check the shape).        self._ref_coord = x, y         self.set_unit(unit)      def set_unit(self, unit):

Updating an array passed as the xy parameter to annotate updates the anottation Bug summary When an array is used as the xy kwarg for an annotation that includes arrows, changing the array after calling the function changes the arrow position. It is very likely that the same array is kept instead of a copy. Code for reproduction Actual outcome ! Expected outcome Both arrows should be horizontal Matplotlib version Operating system: Debian 9 Matplotlib version: '3.0.3' Matplotlib backend: Qt5Agg Python version:'3.5.3' Jupyter version (if applicable): Other libraries: Numpy 1.17.3 Matplotlib was installed using pip


Question: """Return the unit for input to the transform used by ``__call__``."""         return self._unit <del>    def _get_scale(self, renderer):        unit = self.get_unit()        if unit == "pixels":            return 1.        else:            return renderer.points_to_pixels(1.)</del>     def __call__(self, renderer):         """         Return the offset transform.


Question: x, y = self._artist.transform(self._ref_coord)         else:             _api.check_isinstance((Artist, BboxBase, Transform), artist=self._artist)        sc = self._get_scale(renderer)        tr = Affine2D().scale(sc).translate(x, y)        return tr        scale = 1 if self._unit == "pixels" else renderer.points_to_pixels(1)        return Affine2D().scale(scale).translate(x, y)   class _AnnotationBase:


Question: xycoords='data',                  annotation_clip=None):         self.xy = xy        x, y = xy  # Make copy when xy is an array (and check the shape).        self.xy = x, y         self.xycoords = xycoords         self.set_annotation_clip(annotation_clip)