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

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

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


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

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


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

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

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


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

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

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

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

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,


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

# 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


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

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

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

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

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

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


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

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

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


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

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


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

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

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


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

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

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


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

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

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

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

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


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

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)


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

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


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

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

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

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

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

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

# 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


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

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

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

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


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

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


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

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

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:


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

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

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


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

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


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

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


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

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


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

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

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


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

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

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)


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

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


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

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


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

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


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

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

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

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

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

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


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

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

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


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

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

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


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

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

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

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)


Question: Switching to inline backend closes GUI windows <!--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 a plot is made with the backend on and then the backend is changed to , the active plot window(s) are closed. This makes it very difficult to switch cleanly between backends within a notebook. The two mediocre workarounds I can see are: always specify the backend before plotting (since you can't automatically "switch back") use and switch back to after the user is done with the GUI figure. This has the downside of locking the Notebook execution while the figure is live. Code for reproduction The linked gist shows what I'd like to accomplish which is a context manager that enables matplotlib plotting in a GUI window from within a Notebook that is otherwise using the backend. Basically I want the notebook to use inline (for a variety of reasons), but I occasionally wish I could interact with the data in a separate figure. As a side note, easy switching between and / backends would also scratch part of this itch, but the interactive notebook backends still don't enable full screen usage or easily throwing a plot on another monitor. has full screen figured out, so that seems doable. Here's the context manager I wish worked: Actual outcome The outcome of the above code is that a plot window flashes into existence for a split second, then is closed when the call is processed. Expected outcome It would be great if plots created with the qt5 backend could stay visible while other plots with the inline backend were also being created. If use (to establish a reliable event loop) and create a bunch of Qt windows by other means, they live concurrently with the Notebook as long as the kernel is alive. I'd like matplotlib GUI figures to be able to live on regardless of the current backend. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Matplotlib version: 3.1.1 Matplotlib backend (): and Python version: 3.7.3 Jupyter version (if applicable): <!--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--

import matplotlib as mpl from matplotlib import (     _api, backend_tools as tools, cbook, colors, _docstring, text,    _tight_bbox, transforms, widgets, get_backend, is_interactive, rcParams)    _tight_bbox, transforms, widgets, is_interactive, rcParams) from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.cbook import _setattr_cm


Question: Switching to inline backend closes GUI windows <!--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 a plot is made with the backend on and then the backend is changed to , the active plot window(s) are closed. This makes it very difficult to switch cleanly between backends within a notebook. The two mediocre workarounds I can see are: always specify the backend before plotting (since you can't automatically "switch back") use and switch back to after the user is done with the GUI figure. This has the downside of locking the Notebook execution while the figure is live. Code for reproduction The linked gist shows what I'd like to accomplish which is a context manager that enables matplotlib plotting in a GUI window from within a Notebook that is otherwise using the backend. Basically I want the notebook to use inline (for a variety of reasons), but I occasionally wish I could interact with the data in a separate figure. As a side note, easy switching between and / backends would also scratch part of this itch, but the interactive notebook backends still don't enable full screen usage or easily throwing a plot on another monitor. has full screen figured out, so that seems doable. Here's the context manager I wish worked: Actual outcome The outcome of the above code is that a plot window flashes into existence for a split second, then is closed when the call is processed. Expected outcome It would be great if plots created with the qt5 backend could stay visible while other plots with the inline backend were also being created. If use (to establish a reliable event loop) and create a bunch of Qt windows by other means, they live concurrently with the Notebook as long as the kernel is alive. I'd like matplotlib GUI figures to be able to live on regardless of the current backend. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Matplotlib version: 3.1.1 Matplotlib backend (): and Python version: 3.7.3 Jupyter version (if applicable): <!--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--

# thus warrants a warning.             return         raise NonGuiException(            f"Matplotlib is currently using {get_backend()}, which is a "            f"non-GUI backend, so cannot show the figure.")            f"{type(self.canvas).__name__} is non-interactive, and thus cannot be "            f"shown")      def destroy(self):         passdiff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py-- a/lib/matplotlib/pyplot.py++ b/lib/matplotlib/pyplot.py


Question: Switching to inline backend closes GUI windows <!--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 a plot is made with the backend on and then the backend is changed to , the active plot window(s) are closed. This makes it very difficult to switch cleanly between backends within a notebook. The two mediocre workarounds I can see are: always specify the backend before plotting (since you can't automatically "switch back") use and switch back to after the user is done with the GUI figure. This has the downside of locking the Notebook execution while the figure is live. Code for reproduction The linked gist shows what I'd like to accomplish which is a context manager that enables matplotlib plotting in a GUI window from within a Notebook that is otherwise using the backend. Basically I want the notebook to use inline (for a variety of reasons), but I occasionally wish I could interact with the data in a separate figure. As a side note, easy switching between and / backends would also scratch part of this itch, but the interactive notebook backends still don't enable full screen usage or easily throwing a plot on another monitor. has full screen figured out, so that seems doable. Here's the context manager I wish worked: Actual outcome The outcome of the above code is that a plot window flashes into existence for a split second, then is closed when the call is processed. Expected outcome It would be great if plots created with the qt5 backend could stay visible while other plots with the inline backend were also being created. If use (to establish a reliable event loop) and create a bunch of Qt windows by other means, they live concurrently with the Notebook as long as the kernel is alive. I'd like matplotlib GUI figures to be able to live on regardless of the current backend. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Matplotlib version: 3.1.1 Matplotlib backend (): and Python version: 3.7.3 Jupyter version (if applicable): <!--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--

# Need to keep a global reference to the backend for compatibility reasons.     # See https://github.com/matplotlib/matplotlib/issues/6092     matplotlib.backends.backend = newbackend  # type: ignore[attr-defined]     if not cbook._str_equal(old_backend, newbackend):        if get_fignums():            _api.warn_deprecated("3.8", message=(                "Auto-close()ing of figures upon backend switching is deprecated since "                "%(since)s and will be removed %(removal)s.  To suppress this warning, "                "explicitly call plt.close('all') first."))         close("all")     # make sure the repl display hook is installed in case we become    # interactive    # Make sure the repl display hook is installed in case we become interactive.     install_repl_displayhook()


Question: Postscript backend gives wrong page sizes Bug summary When creating a Figure of exactly A4 size, the PS backend chooses "letter" as document type, leading to additional borders of the output in x direction and undesired cropping in y direction. Code for reproduction Actual outcome When not specifying the papertype explicitly, the PS backend chooses "letter" format as can be seen from the resulting postscript output. It should, instead, choose A4 format. When specifying the papertype explicitly, the output looks fine. Expected outcome The PS backend should choose A4 format if the Figure is exactly this size. Anyway, nothing should ever be cropped off the Figure. If the Figure does not fit one papertype, the next larger one should be chosen. I also do not understand why the output of the PS backend is restricted to a handfull of explicit paper sizes in the first place. Postscript does well support arbitrary page sizes. Can someone explain why matplotlib chose to only support the given sizes? This is not transparent to the user, who expects to get output of exactly the size of his/her desired Figure object. Matplotlib version Operating system: Ubuntu 19.04 Matplotlib version: 3.1.1 Matplotlib backend: PS Python version: 3.7.4 Jupyter version: 1.0.0 Other libraries: Matplotlib was installed via conda.

if papertype is None:             papertype = mpl.rcParams['ps.papersize']         papertype = papertype.lower()        _api.check_in_list(['auto', *papersize], papertype=papertype)        _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype)          orientation = _api.check_getitem(             _Orientation, orientation=orientation.lower())