Question: '--all', action='store_true', dest='all', default=False,             help='Display all settings, regardless of their value. Default values are prefixed by "###".',         )        parser.add_argument(            '--default', dest='default', metavar='MODULE', default=None,            help=(                "The settings module to compare the current settings against. Leave empty to "                "compare against Django's default settings."            ),        )      def handle(self, **options):         # Inspired by Postfix's "postconf -n".        from django.conf import settings, global_settings        from django.conf import settings, Settings, global_settings          # Because settings are imported lazily, we need to explicitly load them.         settings._setup()          user_settings = module_to_dict(settings._wrapped)        default_settings = module_to_dict(global_settings)        default = options['default']        default_settings = module_to_dict(Settings(default) if default else global_settings)          output = []         for key in sorted(user_settings):

diffsettings should allow to compare to another settings module (not only to default Django settings) Description Rationale: I use a hierarchy of settings modules, where imports imports I want to see what I customized, e.g. diffsettings --


Question: # At least one model must be migrated to the database.                     router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name)                     for app_label in consistency_check_labels                    for model in apps.get_models(app_label)                    for model in apps.get_app_config(app_label).get_models()             )):                 loader.check_consistent_history(connection)

makemigrations router.allowmigrate() calls for consistency checks use incorrect (applabel, model) pairs Description As reported in ticket:#comment:14, I makemigrations incorrectly calls allow_migrate() for each app with all the models in the project rather than for each app with the app's models. It broke the router I use because it was passing invalid combinations for shards since not all shards have the same models. [ PR]


Question: """         pass     def conditional_expression_supported_in_where_clause(self, expression):        """        Return True, if the conditional expression is supported in the WHERE        clause.        """        return True     def combine_expression(self, connector, sub_expressions):         """         Combine a list of subexpressions into a single expression, usingdiff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py-- a/django/db/backends/oracle/operations.py++ b/django/db/backends/oracle/operations.py

Allow expressions in .filter() calls Description Expressions in filter calls will allow 3rd party apps to create query syntax extensions (for example .filter(F('some_field').lower() == 'anssi')) style). In addition, having the ability to use expressions everywhere unifies the ORM experience.


Question: from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import strip_quotes, truncate_name<ins>from django.db.models.expressions import Exists, ExpressionWrapperfrom django.db.models.query_utils import Q</ins> from django.db.utils import DatabaseError from django.utils import timezone from django.utils.encoding import force_bytes, force_str


Question: if fields:             return self.connection.features.max_query_params // len(fields)         return len(objs)    def conditional_expression_supported_in_where_clause(self, expression):        """        Oracle supports only EXISTS(...) or filters in the WHERE clause, others        must be compared with True.        """        if isinstance(expression, Exists):            return True        if isinstance(expression, ExpressionWrapper) and isinstance(expression.expression, Q):            return True        return Falsediff --git a/django/db/models/expressions.py b/django/db/models/expressions.py-- a/django/db/models/expressions.py++ b/django/db/models/expressions.py


Question: return self._combine(other, self.POW, False)      def __and__(self, other):<ins>        if getattr(self, 'conditional', False) and getattr(other, 'conditional', False):            return Q(self) & Q(other)</ins>         raise NotImplementedError(             "Use .bitand() and .bitor() for bitwise logical operations."         )


Question: return self._combine(other, self.BITRIGHTSHIFT, False)      def __or__(self, other):<ins>        if getattr(self, 'conditional', False) and getattr(other, 'conditional', False):            return Q(self) | Q(other)</ins>         raise NotImplementedError(             "Use .bitand() and .bitor() for bitwise logical operations."         )


Question: ])         return c <ins>    @property    def conditional(self):        return isinstance(self.output_field, fields.BooleanField)</ins>     @property     def field(self):         return self.output_field


Question: class When(Expression):     template = 'WHEN %(condition)s THEN %(result)s'    # This isn't a complete conditional expression, must be used in Case().    conditional = False      def __init__(self, condition=None, then=None, **lookups):         if lookups and condition is None:             condition, lookups = Q(**lookups), None         if condition is None or not getattr(condition, 'conditional', False) or lookups:            raise TypeError("__init__() takes either a Q object or lookups as keyword arguments")            raise TypeError(                'When() supports a Q object, a boolean expression, or lookups '                'as a condition.'            )         if isinstance(condition, Q) and not condition:             raise ValueError("An empty Q() can't be used as a When() condition.")         super().__init__(output_field=None)


Question: class OrderBy(BaseExpression):     template = '%(expression)s %(ordering)s'    conditional = False      def __init__(self, expression, descending=False, nulls_first=False, nulls_last=False):         if nulls_first and nulls_last:diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py-- a/django/db/models/sql/query.py++ b/django/db/models/sql/query.py


Question: """         if isinstance(filter_expr, dict):             raise FieldError("Cannot parse keyword query as dict")<ins>        if hasattr(filter_expr, 'resolve_expression') and getattr(filter_expr, 'conditional', False):            if connections[DEFAULT_DB_ALIAS].ops.conditional_expression_supported_in_where_clause(filter_expr):                condition = filter_expr.resolve_expression(self)            else:                # Expression is not supported in the WHERE clause, add                # comparison with True.                condition = self.build_lookup(['exact'], filter_expr.resolve_expression(self), True)            clause = self.where_class()            clause.add(condition, AND)            return clause, []</ins>         arg, value = filter_expr         if not arg:             raise FieldError("Cannot parse keyword query %r" % arg)


Question: class Command(BaseCommand):     help = """Displays differences between the current settings.py and Django's    default settings. Settings that don't appear in the defaults are    followed by "###"."""    default settings."""      requires_system_checks = False      def add_arguments(self, parser):         parser.add_argument(             '--all', action='store_true', dest='all',            help='Display all settings, regardless of their value. Default values are prefixed by "###".',            help=(                'Display all settings, regardless of their value. In "hash" '                'mode, default values are prefixed by "###".'            ),         )         parser.add_argument(             '--default', dest='default', metavar='MODULE', default=None,

Add "unified diff" output mode to diffsettings management command Description Most people are used to unified diffs vs. the somewhat strange "###" formatting of diffsettings, so this adds an optional —output=unified.


Question: "compare against Django's default settings."             ),         )        parser.add_argument(            '--output', default='hash', choices=('hash', 'unified'), dest='output',            help=(                "Selects the output format. 'hash' mode displays each changed "                "setting, with the settings that don't appear in the defaults "                "followed by ###. 'unified' mode prefixes the default setting "                "with a minus sign, followed by the changed setting prefixed "                "with a plus sign."            ),        )      def handle(self, **options):        # Inspired by Postfix's "postconf -n".         from django.conf import settings, Settings, global_settings          # Because settings are imported lazily, we need to explicitly load them.


Question: user_settings = module_to_dict(settings._wrapped)         default = options['default']         default_settings = module_to_dict(Settings(default) if default else global_settings)        output_func = {            'hash': self.output_hash,            'unified': self.output_unified,        }[options['output']]        return '\n'.join(output_func(user_settings, default_settings, **options))     def output_hash(self, user_settings, default_settings, **options):        # Inspired by Postfix's "postconf -n".         output = []         for key in sorted(user_settings):             if key not in default_settings:


Question: output.append("%s = %s" % (key, user_settings[key]))             elif options['all']:                 output.append("### %s = %s" % (key, user_settings[key]))        return '\n'.join(output)        return output    def output_unified(self, user_settings, default_settings, **options):        output = []        for key in sorted(user_settings):            if key not in default_settings:                output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))            elif user_settings[key] != default_settings[key]:                output.append(self.style.ERROR("- %s = %s" % (key, default_settings[key])))                output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))            elif options['all']:                output.append("  %s = %s" % (key, user_settings[key]))        return output


Question: """     form_class = AuthenticationForm     authentication_form = None<ins>    next_page = None</ins>     redirect_field_name = REDIRECT_FIELD_NAME     template_name = 'registration/login.html'     redirect_authenticated_user = False

Add nextpage to LoginView Description LogoutView has a nextpage attribute used to override settings.LOGOUTREDIRECTURL. It would be nice if LoginView had the same mechanism.


Question: return super().dispatch(request, *args, **kwargs)      def get_success_url(self):        url = self.get_redirect_url()        return url or resolve_url(settings.LOGIN_REDIRECT_URL)        return self.get_redirect_url() or self.get_default_redirect_url()      def get_redirect_url(self):         """Return the user-originating redirect URL if it's safe."""


Question: )         return redirect_to if url_is_safe else '' <ins>    def get_default_redirect_url(self):        """Return the default redirect URL."""        return resolve_url(self.next_page or settings.LOGIN_REDIRECT_URL)</ins>     def get_form_class(self):         return self.authentication_form or self.form_class


Question: def __init__(self, argv=None):         self.argv = argv or sys.argv[:]         self.prog_name = os.path.basename(self.argv[0])<ins>        if self.prog_name == '__main__.py':            self.prog_name = 'python -m django'</ins>         self.settings_exception = None      def main_help_text(self, commands_only=False):

Improve program name for Django's command-line utility. Description By default, according to the documentation there are three ways to execute Django's command-line utility: $ django-admin <command[options] $ <command[options] $ python -m django <command[options] When executing the help command, however, the way these are rendered may be incorrect: $ django-admin help Type 'django-admin help <subcommand' for help on a specific subcommand. ... $ help Type ' help <subcommand' for help on a specific subcommand. ... $ python -m django help Type ' help <subcommand' for help on a specific subcommand. ... It should also be noted that will typically not work and is required: $ help bash: command not found On Windows it will work, but only if the file type is associated with the Python interpreter and not an editor. So, the issues here are: should be replaced by python -m django (or possibly use (sys.executable)) Should be replaced with on non-Windows platforms? What about Windows? What should happen with the option in the documentation?


Question: # types they are. The key is the alias of the joined table (possibly         # the table name) and the value is a Join-like object (see         # sql.datastructures.Join for more information).        self.alias_map = {}        self.alias_map = OrderedDict()         # Sometimes the query contains references to aliases in outer queries (as         # a result of split_exclude). Correct alias quoting needs to know these         # aliases too.

Non-deterministic crash in () Description Hi, There's a logical error somewhere in Query.combine or friends. I have a pretty complicated query with many-to-many self-joins and ORs, and after the upgrade to Django 1.9 and Python 3 combine() sometimes, but not always, crashes with the assertion error assert set(()).intersection(set(())) == set() Inspecting the changemap, it does indeed contain a circular reference (BTW shouldn't you use "not" to test for an empty set rather than comparing with set()?). At first, I didn't understand how it could crash sometimes and sometimes not - we're talking about the same query being executed through a view. But when I examine changemap, its content does indeed change from reload to reload - I suppose this may have something to do with the order of dicts/sets the combine() algorithm is using.


Question: # types they are. The key is the alias of the joined table (possibly         # the table name) and the value is a Join-like object (see         # sql.datastructures.Join for more information).        self.alias_map = {}        self.alias_map = OrderedDict()         # Sometimes the query contains references to aliases in outer queries (as         # a result of split_exclude). Correct alias quoting needs to know these         # aliases too.

Here comes some code, I cut out a bunch of unused stuff, but otherwise it's the same: class Invoice(models.Model): customer = models.ForeignKey(Customer) datecreated = models.DateField(, dbindex=True) datesent = models.DateField(null=True, blank=True) datedue = models.DateField(null=True, blank=True) datepaid = models.DateField(null=True, blank=True) datecredited = models.DateField(null=True, blank=True) datecollect = models.DateField(null=True, blank=True) invoicetype = models.CharField(default="invoice", maxlength=32) reminders = models.ManyToManyField("Invoice", relatedname="remindedset", blank=True) remindercounter = models.IntegerField(null=True, blank=True) That's the model, and in the view: import datetime from import Q date = () invoices = ( Q(datecreatedlte=date), Q(datepaidgt=date) | Q(datepaid=None), Q(datecreditedgt=date) | Q(datecredited=None), customer=1, ) filteredinvoices = () notdue = Q(dateduegte=date) | Q(datedue=None) notremindedyet = ~Q(remindersdatecreatedlte=date) notcollected = Q(datecollectgt=date) | Q(datecollect=None) filteredinvoices |= (notdue, notcollected, datesentlte=date, invoicetype="invoice") filteredinvoices |= (notcollected, notremindedyet, datesentlte=date, dateduelt=date, invoicetype="invoice") for r in [1, 2, 3]: qs = (notcollected, remindersdatecreatedlte=date, remindersremindercounter=r, invoicetype="invoice") for i in range(r + 1, 3 + 1): qs = (~Q(remindersremindercounter=i) | Q(remindersremindercounter=i, remindersdatecreated_gt=date)) filteredinvoices |= qs I realize it's pretty complicated but I'm not sure what's essential and what's not. I hope someone knowledgeable of how combine() works can figure out why ordering in some cases matters.


Question: self.orphans = int(orphans)         self.allow_empty_first_page = allow_empty_first_page <ins>    def __iter__(self):        for page_number in self.page_range:            yield self.page(page_number)</ins>     def validate_number(self, number):         """Validate the given 1-based page number."""         try:

Paginator just implement the iter function Description (last modified by Alex Gaynor) Right now, when you want to iter into all the pages of a Paginator object you to use the pagerange function. It would be more logical and naturel to use the normal python of doing that by implementing the iter function like that: def iter(self): for pagenum in self.pagerange: yield (pagenum)


Question: import pkgutil import sys from collections import OrderedDict, defaultdict<ins>from difflib import get_close_matches</ins> from importlib import import_module  import django

Allow management command invocation to suggest commands for mistyped commands Description Too often I can't remember the full mgmt command name, but can remember a part of it. A little enhancement would save me time. Attaching a screenshot and a patch. Thanks.


Question: settings.INSTALLED_APPS             else:                 sys.stderr.write("No Django settings specified.\n")            sys.stderr.write(                "Unknown command: %r\nType '%s help' for usage.\n"                % (subcommand, self.prog_name)            )            possible_matches = get_close_matches(subcommand, commands)            sys.stderr.write('Unknown command: %r' % subcommand)            if possible_matches:                sys.stderr.write('. Did you mean %s?' % possible_matches[0])            sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name)             sys.exit(1)         if isinstance(app_name, BaseCommand):             # If the command is already loaded, use it directly.


Question: self, prog="%s %s" % (os.path.basename(prog_name), subcommand),             description=self.help or None,         )<ins>        # Add command-specific arguments first so that they appear in the        # --help output before arguments common to all commands.        self.add_arguments(parser)</ins>         parser.add_argument('--version', action='version', version=self.get_version())         parser.add_argument(             '-v', '--verbosity', action='store', dest='verbosity', default=1,

Reorder management command arguments in --help output to prioritize command-specific arguments Description Currently if you run a custom management command with --help, you will get output that looks like: I have highlighted in yellow the useful information specific to the command that is not boilerplate. Notice that most of this yellow text is at the end of the output, with the boilerplate dominating what the user reads first. I propose reordering the options in the output so that the useful information is at the beginning rather than the end, so that it looks like the following: Discussion on django-developers: !topic/django-developers/PByZfN_IccE


Question: '--no-color', action='store_true', dest='no_color',             help="Don't colorize the command output.",         )<del>        self.add_arguments(parser)</del>         return parser      def add_arguments(self, parser):


Question: if frameon is None:             frameon = rcParams['figure.frameon']         if not np.isfinite(figsize).all():            raise ValueError('figure size must be finite not '                             '{}'.format(figsize))        if not np.isfinite(figsize).all() or (np.array(figsize) <= 0).any():            raise ValueError('figure size must be positive finite not '                             f'{figsize}')         self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)          self.dpi_scale_trans = Affine2D().scale(dpi, dpi)

Zero-width figure crashes libpng Bug summary Zero-width figure crashes libpng. This happens when using ` or saving to png. Code for reproduction Actual outcome Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: ubuntu / conda Matplotlib version: 3.0.2, conda 3.0.2-py37h54297110 same at 3.0.3-py37h54297110 libpng 1.6.35-hbc830470, same with 1.6.36-hbc83047 Apparently I broke "conda list" on my machine so getting all the versions seems a bit tricky.


Question: # argument, so unpack them         if h is None:             w, h = w        if not all(np.isfinite(_) for _ in (w, h)):            raise ValueError('figure size must be finite not '                             '({}, {})'.format(w, h))        size = w, h        if not np.isfinite(size).all() or (np.array(size) <= 0).any():            raise ValueError(f'figure size must be positive finite not {size}')         self.bbox_inches.p1 = w, h          if forward:


Question: `.Axis.contains`.         """         martist.Artist.__init__(self)<ins>        self._remove_overlapping_locs = True</ins>         self.set_figure(axes.figure)          self.isDefault_label = True

Minor ticklabels are missing at positions of major ticks. <!--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 Minor ticklabels are missing at positions of major ticks. Code for reproduction Actual outcome The above code run with current master produces ! The minor ticklabels showing the hours are missing. Expected outcome The expected outcome would be the same as when running the code with matplotlib 3.0.2 or below: ! I would expect to see the hours throughout. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Win8 Matplotlib version: master Matplotlib backend (): any Python version: 3.6


Question: majorTicks = _LazyTickList(major=True)     minorTicks = _LazyTickList(major=False) <ins>    def get_remove_overlapping_locs(self):        return self._remove_overlapping_locs    def set_remove_overlapping_locs(self, val):        self._remove_overlapping_locs = bool(val)    remove_overlapping_locs = property(        get_remove_overlapping_locs, set_remove_overlapping_locs,        doc=('If minor ticker locations that overlap with major '             'ticker locations should be trimmed.'))</ins>     def set_label_coords(self, x, y, transform=None):         """         Set the coordinates of the label.


Question: Update ticks (position and labels) using the current data interval of         the axes.  Return the list of ticks that will be drawn.         """        major_locs = self.major.locator()        major_ticks = self.get_major_ticks(len(major_locs))        major_locs = self.get_majorticklocs()         major_labels = self.major.formatter.format_ticks(major_locs)        major_ticks = self.get_major_ticks(len(major_locs))        self.major.formatter.set_locs(major_locs)         for tick, loc, label in zip(major_ticks, major_locs, major_labels):             tick.update_position(loc)             tick.set_label1(label)             tick.set_label2(label)        minor_locs = self.minor.locator()        minor_ticks = self.get_minor_ticks(len(minor_locs))        minor_locs = self.get_minorticklocs()         minor_labels = self.minor.formatter.format_ticks(minor_locs)        minor_ticks = self.get_minor_ticks(len(minor_locs))        self.minor.formatter.set_locs(minor_locs)         for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels):             tick.update_position(loc)             tick.set_label1(label)             tick.set_label2(label)         ticks = [*major_ticks, *minor_ticks]         # mark the ticks that we will not be using as not visible        for t in (self.minorTicks[len(minor_locs):] +                  self.majorTicks[len(major_locs):]):            t.set_visible(False)         view_low, view_high = self.get_view_interval()         if view_low > view_high:             view_low, view_high = view_high, view_low


Question: # Use the transformed view limits as scale.  1e-5 is the default rtol         # for np.isclose.         tol = (hi - lo) * 1e-5        minor_locs = [            loc for loc, tr_loc in zip(minor_locs, tr_minor_locs)            if not np.isclose(tr_loc, tr_major_locs, atol=tol, rtol=0).any()]        if self.remove_overlapping_locs:            minor_locs = [                loc for loc, tr_loc in zip(minor_locs, tr_minor_locs)                if ~np.isclose(tr_loc, tr_major_locs, atol=tol, rtol=0).any()]         return minor_locs      def get_ticklocs(self, minor=False):


Question: def get_major_ticks(self, numticks=None):         'Get the tick instances; grow as necessary.'         if numticks is None:            numticks = len(self.get_major_locator()())            numticks = len(self.get_majorticklocs())          while len(self.majorTicks) < numticks:             # Update the new tick label properties from the old.


Question: def get_minor_ticks(self, numticks=None):         'Get the minor tick instances; grow as necessary.'         if numticks is None:            numticks = len(self.get_minor_locator()())            numticks = len(self.get_minorticklocs())          while len(self.minorTicks) < numticks:             # Update the new tick label properties from the old.


Question: return tuple(color)         # string gray.         try:            return (float(c),) * 3 + (alpha if alpha is not None else 1.,)            c = float(c)         except ValueError:             pass        raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))        else:            if not (0 <= c <= 1):                raise ValueError(                    f"Invalid string grayscale value {orig_c!r}. "                    f"Value must be within 0-1 range")            return c, c, c, alpha if alpha is not None else 1.        raise ValueError(f"Invalid RGBA argument: {orig_c!r}")     # tuple color.     c = np.array(c)     if not np.can_cast(c.dtype, float, "same_kind") or c.ndim != 1:         # Test the dtype explicitly as `map(float, ...)`, `np.array(...,         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.         # Test dimensionality to reject single floats.        raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))        raise ValueError(f"Invalid RGBA argument: {orig_c!r}")     # Return a tuple to prevent the cached value from being modified.     c = tuple(c.astype(float))     if len(c) not in [3, 4]:

returning erroneous value on strings of integers <!--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 returns on strings containing integers, even though these are invalid colours when passed to or equivalent. 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--I would expect either the call to successfully recognise these as colours, or the calls to return . The latter is what I would expect of these two. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Arch Linux Matplotlib version: 3.0.2 Matplotlib backend (): Qt5Agg Python version: Python 3.7.1 Jupyter version (if applicable): N/A Other libraries: 1.15.0 installed from . The example code runs without any errors on Windows, Python 3.6, 2.2.2. <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: (self._xmargin and scalex and self._autoscaleXon) or                 (self._ymargin and scaley and self._autoscaleYon)):             stickies = [artist.sticky_edges for artist in self.get_children()]            x_stickies = np.array([x for sticky in stickies for x in sticky.x])            y_stickies = np.array([y for sticky in stickies for y in sticky.y])            if self.get_xscale().lower() == 'log':                x_stickies = x_stickies[x_stickies > 0]            if self.get_yscale().lower() == 'log':                y_stickies = y_stickies[y_stickies > 0]         else:  # Small optimization.            x_stickies, y_stickies = [], []            stickies = []        x_stickies = np.sort([x for sticky in stickies for x in sticky.x])        y_stickies = np.sort([y for sticky in stickies for y in sticky.y])        if self.get_xscale().lower() == 'log':            x_stickies = x_stickies[x_stickies > 0]        if self.get_yscale().lower() == 'log':            y_stickies = y_stickies[y_stickies > 0]          def handle_single_axis(scale, autoscaleon, shared_axes, interval,                                minpos, axis, margin, stickies, set_bound):

Non-sensical negative radial scale minimum autoset in polar plot When plotting a set of data on a polar plot, the default bottom ylimit might not be zero unexpectedly from the perspective of the user, resulting in confusion about the meaning of the plot, especially for a person (like me) unfamiliar with the concept of a polar plot where r=0 is not at the very center point of the plot. In a Jupyter Notebook (-0., 1.) ! I ran across this when plotting data and wondering if I had a bug in my analysis somewhere that was giving me a hole around the origin. It took me some time to figure out that the problem was simply in the axis scaling as I expected the version on the left (which seems sensible to me as the default) and not the version on the right which has a hole in the middle. Matplotlib version Operating system: Windows 10, also Ubuntu Linux Matplotlib version: 3.0.2 from pip Matplotlib backend (): inline Python version: 3.7, 3.6 Jupyter version (if applicable): JupyterLab 0.35.4


Question: locator = axis.get_major_locator()             x0, x1 = locator.nonsingular(x0, x1)             # Prevent margin addition from crossing a sticky value.  Small            # tolerances (whose values come from isclose()) must be used due to            # floating point issues with streamplot.            def tol(x): return 1e-5 * abs(x) + 1e-8            # Index of largest element < x0 + tol, if any.            i0 = stickies.searchsorted(x0 + tol(x0)) - 1            x0bound = stickies[i0] if i0 != -1 else None            # Index of smallest element > x1 - tol, if any.            i1 = stickies.searchsorted(x1 - tol(x1))            x1bound = stickies[i1] if i1 != len(stickies) else None             # Add the margin in figure space and then transform back, to handle             # non-linear scales.             minpos = getattr(bb, minpos)             transform = axis.get_transform()             inverse_trans = transform.inverted()            # We cannot use exact equality due to floating point issues e.g.            # with streamplot.            do_lower_margin = not np.any(np.isclose(x0, stickies))            do_upper_margin = not np.any(np.isclose(x1, stickies))             x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minpos)             x0t, x1t = transform.transform([x0, x1])            if np.isfinite(x1t) and np.isfinite(x0t):                delta = (x1t - x0t) * margin            else:                # If at least one bound isn't finite, set margin to zero                delta = 0            if do_lower_margin:                x0t -= delta            if do_upper_margin:                x1t += delta            x0, x1 = inverse_trans.transform([x0t, x1t])            delta = (x1t - x0t) * margin            if not np.isfinite(delta):                delta = 0  # If a bound isn't finite, set margin to zero.            x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta])            # Apply sticky bounds.            if x0bound is not None:                x0 = max(x0, x0bound)            if x1bound is not None:                x1 = min(x1, x1bound)              if not self._tight:                 x0, x1 = locator.view_limits(x0, x1)


Question: """         if not isinstance(formatter, mticker.Formatter):             raise TypeError("formatter argument should be instance of "                    "matplotlib.ticker.Formatter")                            "matplotlib.ticker.Formatter")         self.isDefault_majfmt = False         self.major.formatter = formatter         formatter.set_axis(self)diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py-- a/lib/matplotlib/figure.py++ b/lib/matplotlib/figure.py

Remove()ing a shared axes prevents the remaining axes from using unit-provided formatters Consider One gets ! i.e. the call to prevented the axs[0] from acquiring the correct tick formatter and locator. Interestingly, using doesn't exhibit the same bug. Looks like the problem comes from where the call to (etc.), which basically call (to update the axis seen by the formatter) also make Matplotlib believe that we had a user-provided formatter (isDefaultmajloc = False, etc.) which should not be overridden by the unit framework. mpl master (ca. 3.0.2)


Question: def _remove_ax(self, ax):         def _reset_loc_form(axis):            axis.set_major_formatter(axis.get_major_formatter())            axis.set_major_locator(axis.get_major_locator())            axis.set_minor_formatter(axis.get_minor_formatter())            axis.set_minor_locator(axis.get_minor_locator())            # Set the formatters and locators to be associated with axis            # (where previously they may have been associated with another            # Axis isntance)            majfmt = axis.get_major_formatter()            if not majfmt.axis.isDefault_majfmt:                axis.set_major_formatter(majfmt)            majloc = axis.get_major_locator()            if not majloc.axis.isDefault_majloc:                axis.set_major_locator(majloc)            minfmt = axis.get_minor_formatter()            if not minfmt.axis.isDefault_minfmt:                axis.set_minor_formatter(minfmt)            minloc = axis.get_minor_locator()            if not minfmt.axis.isDefault_minloc:                axis.set_minor_locator(minloc)          def _break_share_link(ax, grouper):             siblings = grouper.get_siblings(ax)


Question: 'ha': 'center'},                  'tick': {'inward_factor': 0.2,                           'outward_factor': 0.1,                          'linewidth': rcParams['lines.linewidth'],                          'color': 'k'},                          'linewidth': rcParams['lines.linewidth']},                  'axisline': {'linewidth': 0.75,                               'color': (0, 0, 0, 1)},                  'grid': {'color': (0.9, 0.9, 0.9, 1),

Tick mark color cannot be set on Axes3D As , the method does not change the color of tick marks on , only the color of tick labels. Several workarounds were proposed, and according to one comment, this used to work as expected in version 1.3.1. Here is code that tries to change the colors of all the axes but fails to get the tick marks:


Question: 'outward_factor': 0.1,                           'linewidth': rcParams.get(                               adir + 'tick.major.width',                              rcParams['xtick.major.width']),                          'color': rcParams.get(                              adir + 'tick.color',                              rcParams['xtick.color'])},                              rcParams['xtick.major.width'])},                  'axisline': {'linewidth': rcParams['axes.linewidth'],                               'color': rcParams['axes.edgecolor']},                  'grid': {'color': rcParams['grid.color'],


Question: dx, dy = (self.axes.transAxes.transform([peparray[0:2, 1]]) -                   self.axes.transAxes.transform([peparray[0:2, 0]]))[0]         lxyz = 0.5*(edgep1 + edgep2)        lxyz = 0.5 * (edgep1 + edgep2)          # A rough estimate; points are ambiguous since 3D plots rotate         ax_scale = self.axes.bbox.size / self.figure.bbox.size


Question: ticksign = -1          for tick in ticks:<del></del>             # Get tick line positions             pos = copy.copy(edgep1)             pos[index] = tick.get_loc()


Question: tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))             tick.tick1line.set_linewidth(info['tick']['linewidth'])<del>            tick.tick1line.set_color(info['tick']['color'])</del>             tick.draw(renderer)          renderer.close_group('axis3d')


Question: density = bool(density) or bool(normed)         if density and not stacked:            hist_kwargs = dict(density=density)            hist_kwargs['density'] = density          # List to store all the top coordinates of the histograms         tops = []

hist() no longer respects range=... when density=True <!--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 <!--A short 1-2 sentences that succinctly describes the bug--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 Some array where the first value is 0 and the last one is 1. Note that this bug doesn't happen if density=False. Bisects to (). Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: linux Matplotlib version: master Matplotlib backend (): any Python version: 37 Jupyter version (if applicable): no Other libraries: numpy 1.16.2 <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: xerr = kwargs.pop('xerr', None)         yerr = kwargs.pop('yerr', None)         error_kw = kwargs.pop('error_kw', {})<ins>        ezorder = error_kw.pop('zorder', None)        if ezorder is None:            ezorder = kwargs.get('zorder', None)            if ezorder is not None:                # If using the bar zorder, increment slightly to make sure                # errorbars are drawn on top of bars                ezorder += 0.01        error_kw.setdefault('zorder', ezorder)</ins>         ecolor = kwargs.pop('ecolor', 'k')         capsize = kwargs.pop('capsize', rcParams["errorbar.capsize"])         error_kw.setdefault('ecolor', ecolor)

bar plot yerr lines/caps should respect zorder Bug summary Bar plot error bars break when zorder is greater than 1. Actual outcome ! Matplotlib version Operating system: Arch Linux Matplotlib version: 2.2.3 Matplotlib backend (): Python version: 3.6 Jupyter version (if applicable): 5.7.0 Conda default channel Possible related issue:


Question: """     Select the backend used for rendering and GUI integration. <ins>    If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used    and if the new backend is different than the current backend, all Figures    will be closed.</ins>     Parameters     ----------     backend : str

Existing FigureCanvasQT objects destroyed by call to Bug summary For a number of years, I have been maintaining an interactive application that embeds subclassed FigureCanvasQT objects within a PyQt application. Up until Matplotlib v3.0.3., it was possible to create standard Matplotlib PyQt figures, i.e., using within an embedded IPython shell, that coexist with the subclassed canvas objects. Now in Matplotlib v3.1.0, a call to destroys all the other canvas objects. Unfortunately, I cannot debug this within Visual Studio since I am currently unable to install Matplotlib from the source. By going through the code line by line, I can confirm that the windows are destroyed when calling , but not when calling , but I can't work out what triggers the destruction of the other windows. I presume the subclassed canvasses are not being registered somewhere, and assumes they are no longer active, but I am hoping someone will show me where to look. This may not be a Matplotlib bug, but it's certainly an unwelcome side effect in my application. Code for reproduction If you have installed () and launch it, you can reproduce this from within the embedded IPython shell with the following, which creates a new subclassed window and then attempts to open a regular window.: There are two figure numbers, because NeXpy automatically creates a window with a figure number of 1 when it is launched. Actual outcome A new window with an updated figure number is created but all other windows not created by are destroyed. Expected outcome In Matplotlib v3.0.3, a new window is created by the PyQt5 backend without destroying anything else. Matplotlib version Operating system: Mac OS v10.14.5 Matplotlib version: 3.1.0 Matplotlib backend: Qt5Agg Python version: 3.7.2 Jupyter version (if applicable): 1.0.0 Other libraries: <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: --------     :ref:`backends`     matplotlib.get_backend    matplotlib.pyplot.switch_backend     """     name = validate_backend(backend)     # don't (prematurely) resolve the "auto" backend settingdiff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py-- a/lib/matplotlib/pyplot.py++ b/lib/matplotlib/pyplot.py


Question: def switch_backend(newbackend):     """    Close all open figures and set the Matplotlib backend.    Set the pyplot backend.     The argument is case-insensitive.  Switching to an interactive backend is    possible only if no event loop for another interactive backend has started.    Switching to and from non-interactive backends is always possible.    Switching to an interactive backend is possible only if no event loop for    another interactive backend has started.  Switching to and from    non-interactive backends is always possible.    If the new backend is different than the current backend then all open    Figures will be closed via ``plt.close('all')``.      Parameters     ----------     newbackend : str        The name of the backend to use.        The case-insensitive name of the backend to use.     """     global _backend_mod     # make sure the init is pulled up so we can assign to it later     import matplotlib.backends    close("all")      if newbackend is rcsetup._auto_backend_sentinel:         current_framework = cbook._get_running_interactive_framework()


Question: switch_backend("agg")             rcParamsOrig["backend"] = "agg"             return<ins>    # have to escape the switch on access logic    old_backend = dict.__getitem__(rcParams, 'backend')</ins>      backend_mod = importlib.import_module(         cbook._backend_module_name(newbackend))


Question: # Need to keep a global reference to the backend for compatibility reasons.     # See https://github.com/matplotlib/matplotlib/issues/6092     matplotlib.backends.backend = newbackend<ins>    if not cbook._str_equal(old_backend, newbackend):        close("all")</ins>      # make sure the repl display hook is installed in case we become     # interactive


Question: cbook._warn_external(                 f"Attempting to set identical left == right == {left} results "                 f"in singular transformations; automatically expanding.")        swapped = left > right         left, right = self.xaxis.get_major_locator().nonsingular(left, right)         left, right = self.xaxis.limit_range_for_scale(left, right)        if swapped:            left, right = right, left          self.viewLim.intervalx = (left, right)         if auto is not None:

Inverting an axis using its limits does not work for log scale Bug summary Starting in matplotlib 3.1.0 it is no longer possible to invert a log axis using its limits. Code for reproduction Actual outcome The yaxis is only inverted for the scale. ! ! Expected outcome I would expect the yaxis to be inverted for both the scale. Matplotlib version Operating system: Linux and MacOS Matplotlib version: 3.1.0 Python version: 3.7.3 Python and matplotlib have been installed using conda.


Question: f"Attempting to set identical bottom == top == {bottom} "                 f"results in singular transformations; automatically "                 f"expanding.")        swapped = bottom > top         bottom, top = self.yaxis.get_major_locator().nonsingular(bottom, top)         bottom, top = self.yaxis.limit_range_for_scale(bottom, top)        if swapped:            bottom, top = top, bottom          self.viewLim.intervaly = (bottom, top)         if auto is not None:diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py-- a/lib/matplotlib/ticker.py++ b/lib/matplotlib/ticker.py


Question: return locs      def nonsingular(self, v0, v1):        """Modify the endpoints of a range as needed to avoid singularities."""        return mtransforms.nonsingular(v0, v1, increasing=False, expander=.05)        """Expand a range as needed to avoid singularities."""        return mtransforms.nonsingular(v0, v1, expander=.05)      def view_limits(self, vmin, vmax):         """diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py-- a/lib/mpl_toolkits/mplot3d/axes3d.py++ b/lib/mpl_toolkits/mplot3d/axes3d.py


Question: cbook._warn_external(                 f"Attempting to set identical left == right == {left} results "                 f"in singular transformations; automatically expanding.")        swapped = left > right         left, right = self.xaxis.get_major_locator().nonsingular(left, right)         left, right = self.xaxis.limit_range_for_scale(left, right)        if swapped:            left, right = right, left         self.xy_viewLim.intervalx = (left, right)          if auto is not None:


Question: f"Attempting to set identical bottom == top == {bottom} "                 f"results in singular transformations; automatically "                 f"expanding.")        swapped = bottom > top         bottom, top = self.yaxis.get_major_locator().nonsingular(bottom, top)         bottom, top = self.yaxis.limit_range_for_scale(bottom, top)        if swapped:            bottom, top = top, bottom         self.xy_viewLim.intervaly = (bottom, top)          if auto is not None:


Question: f"Attempting to set identical bottom == top == {bottom} "                 f"results in singular transformations; automatically "                 f"expanding.")        swapped = bottom > top         bottom, top = self.zaxis.get_major_locator().nonsingular(bottom, top)         bottom, top = self.zaxis.limit_range_for_scale(bottom, top)        if swapped:            bottom, top = top, bottom         self.zz_viewLim.intervalx = (bottom, top)          if auto is not None:


Question: # For blitting, the init_func should return a sequence of modified         # artists.         if self._init_func is None:            self._draw_frame(next(self.new_frame_seq()))            try:                frame_data = next(self.new_frame_seq())            except StopIteration:                # we can't start the iteration, it may have already been                # exhausted by a previous save or just be 0 length.                # warn and bail.                warnings.warn(                    "Can not start iterating the frames for the initial draw. "                    "This can be caused by passing in a 0 length sequence "                    "for *frames*.\n\n"                    "If you passed *frames* as a generator "                    "it may be exhausted due to a previous display or save."                )                return            self._draw_frame(frame_data)         else:             self._drawn_artists = self._init_func()             if self._blit:

and fig.savefig interfere with each other and raise StopIteration The following code snippet raises StopIteration: The same also happens if the figure is saved before the animation. The interesting thing is that the two parts of the script work fine when run alone, so there must be some interference between the two. The output produced by the above code: Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Ubunut 18.04 Matplotlib version: 3.2.2 Matplotlib backend (): TkAgg Python version: 3.7.7 Jupyter version (if applicable): No Jupyter Other libraries: Matplotlib installed using pip inside a conda environment


Question: year      = 2007 }""" # modelled after sys.version_info_VersionInfo = namedtuple('_VersionInfo',                          'major, minor, micro, releaselevel, serial') def __getattr__(name):    if name == "__version__":def _parse_to_version_info(version_str):    """    Parse a version string to a namedtuple analogous to sys.version_info.    See:    https://packaging.pypa.io/en/latest/version.html#packaging.version.parse    https://docs.python.org/3/library/sys.html#sys.version_info    """    v = parse_version(version_str)    if v.pre is None and v.post is None and v.dev is None:        return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)    elif v.dev is not None:        return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)    elif v.pre is not None:        releaselevel = {            'a': 'alpha',            'b': 'beta',            'rc': 'candidate'}.get(v.pre[0], 'alpha')        return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])    else:        # fallback for v.post: guess-next-dev scheme from setuptools_scm        return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)def _get_version():    """Return the version string used for __version__."""    # Only shell out to a git subprocess if really needed, and not on a    # shallow clone, such as those used by CI, as the latter would trigger    # a warning from setuptools_scm.    root = Path(__file__).resolve().parents[2]    if (root / ".git").exists() and not (root / ".git/shallow").exists():         import setuptools_scm        return setuptools_scm.get_version(            root=root,            version_scheme="post-release",            local_scheme="node-and-date",            fallback_version=_version.version,        )    else:  # Get the version from the _version.py setuptools_scm file.        return _version.versiondef __getattr__(name):    if name in ("__version__", "__version_info__"):         global __version__  # cache it.        # Only shell out to a git subprocess if really needed, and not on a        # shallow clone, such as those used by CI, as the latter would trigger        # a warning from setuptools_scm.        root = Path(__file__).resolve().parents[2]        if (root / ".git").exists() and not (root / ".git/shallow").exists():            __version__ = setuptools_scm.get_version(                root=root,                version_scheme="post-release",                local_scheme="node-and-date",                fallback_version=_version.version,            )        else:  # Get the version from the _version.py setuptools_scm file.            __version__ = _version.version        return __version__        __version__ = _get_version()        global __version__info__  # cache it.        __version_info__ = _parse_to_version_info(__version__)        return __version__ if name == "__version__" else __version_info__     raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

Add easily comparable version info to toplevel <!-- Welcome! Thanks for thinking of a way to improve Matplotlib. Before creating a new feature request please search the issues for relevant feature requests. --Currently matplotlib only exposes . For quick version checks, exposing either a tuple (which can be compared with other tuples) or a instance (which can be properly compared with other strings) would be a small usability improvement. (In practice I guess boring string comparisons will work just fine until we hit mpl 3.10 or 4.10 which is unlikely to happen soon, but that feels quite dirty :)) <!-- Provide a clear and concise description of the problem this feature will solve. 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 [...] --I guess I slightly prefer , but exposing just a tuple is much more common in other packages (and perhaps simpler to understand). The hardest(?) part is probably just bikeshedding this point :-) <!-- Provide a clear and concise description of a way to accomplish what you want. For example: Add an option so that when [...] [...] will happen --is a pretty common thing (citation needed). <!-- Add any other context or screenshots about the feature request here. You can also include links to examples of other programs that have something similar to your request. For example: Another project [...] solved this by [...] --


Question: **lineprops):         super().__init__(ax)         self.connect_event('motion_notify_event', self.onmove)        self.connect_event('draw_event', self.clear)        self.connect_event('motion_notify_event', self._onmove)        self.connect_event('draw_event', self._clear)          self.visible = True         self.horizOn = horizOn

Multicursor disappears when not moving on nbagg with useblit=False + burns CPU <!--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 on the nbagg backend if you stop moving the mouse the multicursor will disappear. The same example works fine on the qt backend. Additionally I noticed that when I add the multicursor my cpu usage jumps and the kernel busy indicator constantly flashes on and off. Showing the plot without the multicursor: ! and with the multicursor (just displaying, not interacting with the plot): ! That usage is pretty stable and my laptop's fan goes wild. The issue with the dissappearing was originally noticed by in 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 ! and the high CPU usage Expected outcome Red line doesn't disappear + my CPU doesn't get crushed. <!--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 Matplotlib version (): '3.3.4.post2456+gfd23bb238' Matplotlib backend (): nbagg Python version: '3.9.1 (default, Jan 26 2021, 01:34:10) \n[GCC 9.3.0]' Jupyter version (if applicable): Notebook 6.2.0 - IPython 7.20.0 dev instlal of maptlotlib + conda-forge for the others


Question: self.background = None         self.needclear = False     @_api.deprecated('3.5')     def clear(self, event):         """Internal event handler to clear the cursor."""        self._clear(event)         if self.ignore(event):             return        if self.useblit:            self.background = self.canvas.copy_from_bbox(self.ax.bbox)         self.linev.set_visible(False)         self.lineh.set_visible(False)     def onmove(self, event):    def _clear(self, event):        """Internal event handler to clear the cursor."""        if self.ignore(event):            return        if self.useblit:            self.background = self.canvas.copy_from_bbox(self.ax.bbox)    onmove = _api.deprecate_privatize_attribute('3.5')    def _onmove(self, event):         """Internal event handler to draw the cursor when the mouse moves."""         if self.ignore(event):             return


Question: self.needclear = False             return         self.needclear = True        if not self.visible:            return         self.linev.set_xdata((event.xdata, event.xdata))        self.linev.set_visible(self.visible and self.vertOn)          self.lineh.set_ydata((event.ydata, event.ydata))        self.linev.set_visible(self.visible and self.vertOn)         self.lineh.set_visible(self.visible and self.horizOn)         self._update()        if self.visible and (self.vertOn or self.horizOn):            self._update()      def _update(self):         if self.useblit:


Question: """Connect events."""         for canvas, info in self._canvas_infos.items():             info["cids"] = [                canvas.mpl_connect('motion_notify_event', self.onmove),                canvas.mpl_connect('draw_event', self.clear),                canvas.mpl_connect('motion_notify_event', self._onmove),                canvas.mpl_connect('draw_event', self._clear),             ]      def disconnect(self):


Question: canvas.mpl_disconnect(cid)             info["cids"].clear()     @_api.deprecated('3.5')     def clear(self, event):        """Clear the cursor."""        if self.ignore(event):            return        self._clear(event)        for line in self.vlines + self.hlines:            line.set_visible(False)    def _clear(self, event):         """Clear the cursor."""         if self.ignore(event):             return         if self.useblit:             for canvas, info in self._canvas_infos.items():                 info["background"] = canvas.copy_from_bbox(canvas.figure.bbox)        for line in self.vlines + self.hlines:            line.set_visible(False)     def onmove(self, event):    onmove = _api.deprecate_privatize_attribute('3.5')    def _onmove(self, event):         if (self.ignore(event)                 or event.inaxes not in self.axes                 or not event.canvas.widgetlock.available(self)):             return         self.needclear = True        if not self.visible:            return         if self.vertOn:             for line in self.vlines:                 line.set_xdata((event.xdata, event.xdata))


Question: for line in self.hlines:                 line.set_ydata((event.ydata, event.ydata))                 line.set_visible(self.visible)        self._update()        if self.visible and (self.vertOn or self.horizOn):            self._update()      def _update(self):         if self.useblit:


Question: return [self.filename(fmt) for fmt in self.formats]  def out_of_date(original, derived):def out_of_date(original, derived, includes=None):     """    Return whether *derived* is out-of-date relative to *original*, both of    which are full file paths.    Return whether *derived* is out-of-date relative to *original* or any of    the RST files included in it using the RST include directive (*includes*).    *derived* and *original* are full paths, and *includes* is optionally a    list of full paths which may have been included in the *original*.     """    return (not os.path.exists(derived) or            (os.path.exists(original) and             os.stat(derived).st_mtime < os.stat(original).st_mtime))    if not os.path.exists(derived):        return True    if includes is None:        includes = []    files_to_check = [original, *includes]    def out_of_date_one(original, derived_mtime):        return (os.path.exists(original) and                derived_mtime < os.stat(original).st_mtime)    derived_mtime = os.stat(derived).st_mtime    return any(out_of_date_one(f, derived_mtime) for f in files_to_check)   class PlotError(RuntimeError):

plotdirective is confused by include directives, part 2 (context option) Whenever a file is included in via the RST directive, Sphinx rebuilds the page; but in plotdirective, is not considered 'out of date' (as judged by the function), because the modification time of was not changed. This discrepancy is part of the reason why exists; and while working on it (at PR ) I discovered also that figures with the option set will get confused. A specific example is shown below. It's quite hard to encounter in real life but it is directly relevant to matplotlib's tests as there is a very similar construct in plots 6-9 of matplotlib's . a.rst b.rst the four files above in a directory and into it. the docs the first time using . in any way. the docs again. The third plot in throws an error. The reason for this, as suggested above, is because of the function. When is invoked again, Sphinx decides that both and must be recompiled. Now: Plot 1 is not considered out of date, because the image file already exists and was not modified. So the code is never run and is never saved to the context. Plot 2 is there to ensure that figures are closed prior to Plot 3, so that Plot 3 never generates an image file. Plot 3 is considered out of date, because there is no image file that corresponds to it. Thus it is run again, and doesn't see in the context, hence the warning. There shouldn't be any errors. One easy way to accomplish this is to make sure that Sphinx re-runs all code snippets which are context-dependent, whenever a file is recompiled. That is, if a plot directive has :context: on, then the code should always be considered out of date regardless of the file modification times. This will lead to some excessive regeneration of plots whenever included files are modified. For example, in the above code, whenever is modified, Plots 1 and 3 will always be re-created, even if is untouched. But IMO this is more sensible behaviour than the current bug. It would also be in line with what happens if any part of is modified, including the text outside the plot directives: all the plots in would be re-created. This doesn't change the case where neither nor are modified, because in that case Sphinx will never attempt to recompile either file and plot_directive will never be called.


Question: def render_figures(code, code_path, output_dir, output_base, context,                    function_name, config, context_reset=False,                   close_figs=False):                   close_figs=False,                   code_includes=None):     """     Run a pyplot script and save the images in *output_dir*.


Question: all_exists = True     img = ImageFile(output_base, output_dir)     for format, dpi in formats:        if out_of_date(code_path, img.filename(format)):        if context or out_of_date(code_path, img.filename(format),                                  includes=code_includes):             all_exists = False             break         img.formats.append(format)


Question: else:                 img = ImageFile('%s_%02d' % (output_base, j), output_dir)             for fmt, dpi in formats:                if out_of_date(code_path, img.filename(fmt)):                if context or out_of_date(code_path, img.filename(fmt),                                          includes=code_includes):                     all_exists = False                     break                 img.formats.append(fmt)


Question: build_dir_link = build_dir     source_link = dest_dir_link + '/' + output_base + source_ext <ins>    # get list of included rst files so that the output is updated when any    # plots in the included files change. These attributes are modified by the    # include directive (see the docutils.parsers.rst.directives.misc module).    try:        source_file_includes = [os.path.join(os.getcwd(), t[0])                                for t in state.document.include_log]    except AttributeError:        # the document.include_log attribute only exists in docutils >=0.17,        # before that we need to inspect the state machine        possible_sources = {os.path.join(setup.confdir, t[0])                            for t in state_machine.input_lines.items}        source_file_includes = [f for f in possible_sources                                if os.path.isfile(f)]    # remove the source file itself from the includes    try:        source_file_includes.remove(source_file_name)    except ValueError:        pass</ins>     # make figures     try:         results = render_figures(code,


Question: function_name,                                  config,                                  context_reset=context_opt == 'reset',                                 close_figs=context_opt == 'close-figs')                                 close_figs=context_opt == 'close-figs',                                 code_includes=source_file_includes)         errors = []     except PlotError as err:         reporter = state.memo.reporter


Question: from matplotlib.collections import (     Collection, CircleCollection, LineCollection, PathCollection,     PolyCollection, RegularPolyCollection)<ins>from matplotlib.text import Text</ins> from matplotlib.transforms import Bbox, BboxBase, TransformedBbox from matplotlib.transforms import BboxTransformTo, BboxTransformFrom from matplotlib.offsetbox import (

Handle and label not created for Text with label Bug summary Text accepts a keyword argument but neither its handle nor its label is created and to the legend. Code for reproduction Actual outcome ! Expected outcome I expect a legend entry for the text. Matplotlib version Matplotlib version: 3.3.3


Question: handler = self.get_legend_handler(legend_handler_map, orig_handle)             if handler is None:                 _api.warn_external(                    "Legend does not support {!r} instances.\nA proxy artist "                    "may be used instead.\nSee: "                    "https://matplotlib.org/users/legend_guide.html"                    "#creating-artists-specifically-for-adding-to-the-legend-"                    "aka-proxy-artists".format(orig_handle))                             "Legend does not support handles for {0} "                             "instances.\nA proxy artist may be used "                             "instead.\nSee: https://matplotlib.org/"                             "stable/tutorials/intermediate/legend_guide.html"                             "#controlling-the-legend-entries".format(                                 type(orig_handle).__name__))                 # No handle for this artist, so we just defer to None.                 handle_list.append(None)             else:


Question: for ax in axs:         handles_original += [             *(a for a in ax._children              if isinstance(a, (Line2D, Patch, Collection))),              if isinstance(a, (Line2D, Patch, Collection, Text))),             *ax.containers]         # support parasite axes:         if hasattr(ax, 'parasites'):             for axx in ax.parasites:                 handles_original += [                     *(a for a in axx._children                      if isinstance(a, (Line2D, Patch, Collection))),                      if isinstance(a, (Line2D, Patch, Collection, Text))),                     *axx.containers]      handler_map = {**Legend.get_default_handler_map(),


Question: label = handle.get_label()         if label != '_nolegend_' and has_handler(handler_map, handle):             yield handle        elif (label not in ['_nolegend_', ''] and                not has_handler(handler_map, handle)):            _api.warn_external(                             "Legend does not support handles for {0} "                             "instances.\nSee: https://matplotlib.org/stable/"                             "tutorials/intermediate/legend_guide.html"                             "#implementing-a-custom-legend-handler".format(                                 type(handle).__name__))            continue   def _get_legend_handles_labels(axs, legend_handler_map=None):diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py-- a/lib/matplotlib/text.py++ b/lib/matplotlib/text.py


Question: """         Create a `.Text` instance at *x*, *y* with string *text*. <ins>        While Text accepts the 'label' keyword argument, by default it is not        added to the handles of a legend.</ins>         Valid keyword arguments are:          %(Text:kwdoc)s


Question: # we have re-set the vmin/vmax to account for small errors                 # that may have moved input values in/out of range                 s_vmin, s_vmax = vrange                if isinstance(self.norm, mcolors.LogNorm):                    if s_vmin < 0:                        s_vmin = max(s_vmin, np.finfo(scaled_dtype).eps)                if isinstance(self.norm, mcolors.LogNorm) and s_vmin <= 0:                    # Don't give 0 or negative values to LogNorm                    s_vmin = np.finfo(scaled_dtype).eps                 with cbook._setattr_cm(self.norm,                                        vmin=s_vmin,                                        vmax=s_vmax,

testhugerangelog is failing... <!--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.--is failing quite a few of the CI runs with a Value Error. I cannot reproduce locally, so I assume there was a numpy change somewhere... This test came in


Question: The scale factor by which the length is shrunken or             expanded (default 16.0)             The PGF backend uses this argument as an RNG seed and not as            described above. Using the same seed yields the same random shape.             .. ACCEPTS: (scale: float, length: float, randomness: float)         """         if scale is None:diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py-- a/lib/matplotlib/backends/backend_pgf.py++ b/lib/matplotlib/backends/backend_pgf.py

Sketch params ignored when using PGF backend Bug summary Calls to are ignored by the PGF backend and do not have any influence in the resulting pgf or pdf file. Code for reproduction Actual outcome ! Expected outcome ! Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--* Matplotlib version: '3.0.2' I am working on a fix for this.


Question: r"{\pgfqpoint{%fin}{%fin}}"                         % coords) <ins>        # apply pgf decorators        sketch_params = gc.get_sketch_params() if gc else None        if sketch_params is not None:            # Only "length" directly maps to "segment length" in PGF's API.            # PGF uses "amplitude" to pass the combined deviation in both x-            # and y-direction, while matplotlib only varies the length of the            # wiggle along the line ("randomness" and "length" parameters)            # and has a separate "scale" argument for the amplitude.            # -> Use "randomness" as PRNG seed to allow the user to force the            # same shape on multiple sketched lines            scale, length, randomness = sketch_params            if scale is not None:                # make matplotlib and PGF rendering visually similar                length *= 0.5                scale *= 2                # PGF guarantees that repeated loading is a no-op                writeln(self.fh, r"\usepgfmodule{decorations}")                writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}")                writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, "                        f"segment length = {(length * f):f}in, "                        f"amplitude = {(scale * f):f}in}}")                writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}")                writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}")</ins>     def _pgf_path_draw(self, stroke=True, fill=False):         actions = []         if stroke:


Question: segments = []          for path in self._paths:            vertices = [vertex for vertex, _ in path.iter_segments()]            vertices = [                vertex                for vertex, _                # Never simplify here, we want to get the data-space values                # back and there in no way to know the "right" simplification                # threshold so never try.                in path.iter_segments(simplify=False)            ]             vertices = np.asarray(vertices)             segments.append(vertices)

setsegments(getsegments()) makes lines coarse After plotting with , I would like to retrieve the lines and manipulate them. Unfortunately, I noticed that the result is much coarser than without manipulation. In fact, a simple has this effect. I would have expected this does nothing at all. MWE: This is with mpl 3.4.2.


Question: self.artists.append(self._rect)      def _setup_edge_handle(self, props):        self._edge_handles = ToolLineHandles(self.ax, self.extents,        # Define initial position using the axis bounds to keep the same bounds        if self.direction == 'horizontal':            positions = self.ax.get_xbound()        else:            positions = self.ax.get_ybound()        self._edge_handles = ToolLineHandles(self.ax, positions,                                              direction=self.direction,                                              line_props=props,                                              useblit=self.useblit)

interactive SpanSelector incorrectly forces axes limits to include 0 <!--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 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 axes xlimits are expanded to include x=0. Expected outcome The axes xlimits remain at (10, 20) + margins, as was the case in Matplotlib 3.4 (with replaced by its old name ). attn Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: linux Matplotlib version (): master (3.5.0.dev1362+g57489bf19b) Matplotlib backend (): qt5agg Python version: 39 Jupyter version (if applicable): no Other libraries: <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: x = kwargs.pop('x', None)         y = kwargs.pop('y', None)        autopos = x is None and y is None        if info['name'] in ['_supxlabel', '_suptitle']:            autopos = y is None        elif info['name'] == '_supylabel':            autopos = x is None         if x is None:             x = info['x0']         if y is None:

[Bug]: subfigure position shifts on y-axis when x kwarg to supxlabel Location of subfigure shifts lower on y-axis when 'x' kwarg is used for supxlabel for that subfigure. I've also posted to StackOverflow: Body of subfigure shifts downward (lower on y-axis) and covers supxlabel ! subfigure position doesn't change. supxlabel shifts to right. ! Windows 10 Pro 2 No response 5 16 No response conda conda-forge


Question: extend = norm.extend             else:                 extend = 'neither'        self.alpha = alpha        self.alpha = None        # Call set_alpha to handle array-like alphas properly        self.set_alpha(alpha)         self.cmap = cmap         self.norm = norm         self.values = values

[Bug]: Colorbar creation from pcolormesh with cell specific alpha values When I try to take advantage of the new ability to set cell specific alpha values in pcolormesh - and then use the resulting QuadMesh object to create a colorbar it generates an error detailed below. A heat-map with a color bar beside it. Ubuntu inside singularity container 2 agg 5 not used none pip No response_


Question: self.stale = True      def set_alpha(self, alpha):        """Set the transparency between 0 (transparent) and 1 (opaque)."""        self.alpha = alpha        """        Set the transparency between 0 (transparent) and 1 (opaque).        If an array is provided, *alpha* will be set to None to use the        transparency values associated with the colormap.        """        self.alpha = None if isinstance(alpha, np.ndarray) else alpha      def _set_scale(self, scale, **kwargs):         """


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

[Bug]: spines and ticklabels Hello everyone, I am not sure if this is a bug or just how the spines function () is supposed to work. Basically, if I set the spines command "after" the tickparams specs, the "labelrotation" commands is not followed but everything else is. Any suggestions? Seems kind of weird that only some of the tickparams are executed and not others. Thank you! Key aspect of code below: ["top"].setposition(("axes", 1.05)) ax1.tickparams(axis='x', colors="green", gridcolor='g',labelsize='small', labelrotation = 45) ["top"].setposition(("axes", 1.05)) See code above. I would expect the labels to be rotated regardless of where the spine command is placed. Windows or MacOs 2 No response 6 No response No response pip No response_


Question: class CallbackRegistry:     """    Handle registering and disconnecting for a set of signals and callbacks:    Handle registering, processing, blocking, and disconnecting    for a set of signals and callbacks:          >>> def oneat(x):         ...    print('eat', x)

Add ability to disable callbacks temporarily It may be useful to update some attributes on an object that has callbacks temporarily and we don't want those callback signals being processed during that time. I guess we could add a context manager on CallbackRegistry? Originally posted by in


Question: >>> callbacks.process('eat', 456)         eat 456         >>> callbacks.process('be merry', 456) # nothing will be called         >>> callbacks.disconnect(id_eat)         >>> callbacks.process('eat', 456)      # nothing will be called         >>> with callbacks.blocked(signal='drink'):        ...     callbacks.process('drink', 123) # nothing will be called        >>> callbacks.process('drink', 123)        drink 123     In practice, one should always disconnect all callbacks when they are     no longer needed to avoid dangling references (and thus memory leaks).     However, real code in Matplotlib rarely does so, and due to its design,


Question: else:                         raise <ins>    @contextlib.contextmanager    def blocked(self, *, signal=None):        """        Block callback signals from being processed.        A context manager to temporarily block/disable callback signals        from being processed by the registered listeners.        Parameters        ----------        signal : str, optional            The callback signal to block. The default is to block all signals.        """        orig = self.callbacks        try:            if signal is None:                # Empty out the callbacks                self.callbacks = {}            else:                # Only remove the specific signal                self.callbacks = {k: orig[k] for k in orig if k != signal}            yield        finally:            self.callbacks = orig</ins>  class silent_list(list):     """


Question: # Clear the callback registry for this axis, or it may "leak"         self.callbacks = cbook.CallbackRegistry()         self._reset_major_tick_kw()        self._reset_minor_tick_kw()        # whether the grids are on        self._major_tick_kw['gridOn'] = (                mpl.rcParams['axes.grid'] and                mpl.rcParams['axes.grid.which'] in ('both', 'major'))        self._minor_tick_kw['gridOn'] = (                mpl.rcParams['axes.grid'] and                mpl.rcParams['axes.grid.which'] in ('both', 'minor'))         self.reset_ticks()          self.converter = None

() adds extra ticks, un-hides shared-axis tick labels Bug summary When using shared axes (e.g. from ), calling causes ticks and tick labels to be shown that should be hidden. The axes are still linked, though (e.g. adjusting the plotting range on one subplot adjusts the others as well). This is a behavior change between matplotlib 3.4.1 and 3.4.2. Code for reproduction This code produces different results with matplotlib 3.4.1 and 3.4.2: This example is of course silly, but I use the general pattern when making animations with FuncAnimation, where my plotting function is a complex module which doesn't facilitate blitting, so I clear and re-use the axes for each frame of the animation. Actual outcome This is the plot produced with matplotlib 3.4.2: ! The presence of tick labels that should be hidden by virtue of the shared axes is the clearest problem in this plot, but there are also ticks that appear along the top and right side of each subplot which are not present in the example below (and not part of the default plotting style, IIRC). The top and right-side ticks also appear when not using multiple subplots, so I think the shared-axis aspect reveals another symptom but is not a core part of this bug. If the call is removed, the plot produced with matplotlib 3.4.2 appears identical to the 3.4.1 plot below. Expected outcome This is the plot produced with matplotlib 3.4.1: ! Matplotlib version Operating system: Ubuntu 20.04 Matplotlib version (): 3.4.2 Matplotlib backend (): module://matplotlibinline.backendinline Python version: 3.8.10 Jupyter version (if applicable): jupyter core 4.7.1, jupyter lab 3.0.16 Other libraries: I've installed matplotlib (3.4.2-py38h578d9bd0) via conda from conda-forge


Question: """         # local import only to avoid circularity         from matplotlib.axes import Axes        from matplotlib.figure import Figure        from matplotlib.figure import FigureBase          super().__init__()

Adding a legend to a doesn't work <!--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 <!--A short 1-2 sentences that succinctly describes the bug--Adding a legend to a doesn't work 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--I'd expect this to work and produce a legend. The example is of course a bit contrived but it would be useful to allow a legend per subfigure Changing L437 here to check against fixes it. I can make a PR at some point but wanted to flag the issue here in case anyone gets to it first. Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: macOS 11.4 Matplotlib version (): 3.4.2.post1350+gdba02be18e Matplotlib backend (): TkAgg Python version: Python 3.8.3 <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: self.isaxes = True             self.axes = parent             self.set_figure(parent.figure)        elif isinstance(parent, Figure):        elif isinstance(parent, FigureBase):             self.isaxes = False             self.set_figure(parent)         else:            raise TypeError("Legend needs either Axes or Figure as parent")            raise TypeError(                "Legend needs either Axes or FigureBase as parent"            )         self.parent = parent          self._loc_used_default = loc is None


Question: if pattern_re.search(key))      def copy(self):        return {k: dict.__getitem__(self, k) for k in self}        rccopy = RcParams()        for k in self:  # Skip deprecations and revalidation.            dict.__setitem__(rccopy, k, dict.__getitem__(self, k))        return rccopy   def rc_params(fail_on_error=False):

MatplotlibDeprecationWarning when updating rcparams Bug summary Updating RC params in code produces a deprecation warning. In order to control rcParams for an internal library I am reading in parameters and popping some that I don't want used. I am using a variation on the code below. I think I have traced it to the _validators dictionary in Code for reproduction This code reproduces the error. Actual outcome Expected outcome I would expect Matplotlib to not load deprecated rcParams Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Windows Matplotlib version: 3.4.2 Matplotlib backend: 'Qt5Agg' Python version: 3.9.4 Jupyter version (if applicable): Other libraries: Setup a conda environment and just specified matplotlib from conda-forge


Question: rcParams = RcParams()  # The global instance. dict.update(rcParams, dict.items(rcParamsDefault)) dict.update(rcParams, _rc_params_in_file(matplotlib_fname()))rcParamsOrig = rcParams.copy() with _api.suppress_matplotlib_deprecation_warning():    rcParamsOrig = RcParams(rcParams.copy())     # This also checks that all rcParams are indeed listed in the template.     # Assigning to rcsetup.defaultParams is left only for backcompat.     defaultParams = rcsetup.defaultParams = {


Question: shared_x = self in self._shared_axes["x"]         shared_y = self in self._shared_axes["y"]        # Not sure whether we need this check:         if shared_x and shared_y:            raise RuntimeError("adjustable='datalim' is not allowed when both "                               "axes are shared")            raise RuntimeError("set_aspect(..., adjustable='datalim') or "                               "axis('equal') are not allowed when both axes "                               "are shared.  Try set_aspect(..., "                               "adjustable='box').")          # If y is shared, then we are only allowed to change x, etc.         if shared_y:

RuntimeError: adjustable='datalim' is not allowed when both axes are shared. <!--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 Matplotlib 2.2.2 fails to plot the figure described below. The code works with Matplotlib 2.0.2. The issue seems to be the combination of `. Code for reproduction Actual outcome With Matplotlib 2.2.2, the figure is not drawn and the following exception is raised: Expected outcome Drawn figure, no error, as with Matplotlib 2.0.2 Matplotlib version <!--Please specify your platform and versions of the relevant libraries you are using:--Operating system: Windows 7 64 bits Matplotlib version: 2.2.2 Matplotlib backend (): Qt5Agg Python version: 3.6 Jupyter version (if applicable): Other libraries: Anaconda 5.2 <!--Please tell us how you installed matplotlib and python e.g., from source, pip, conda--<!--If you installed from conda, please specify which channel you used if not the default--


Question: self.set_autoscale_on(True)                 self.set_aspect('auto')                 self.autoscale_view(tight=False)<del>                # self.apply_aspect()</del>                 if s == 'equal':                     self.set_aspect('equal', adjustable='datalim')                 elif s == 'scaled':


Question: plt.axes((left, bottom, width, height), facecolor='w')     """     fig = gcf()    pos = kwargs.pop('position', None)     if arg is None:        return fig.add_subplot(**kwargs)        if pos is None:            return fig.add_subplot(**kwargs)        else:            return fig.add_axes(pos, **kwargs)     else:         return fig.add_axes(arg, **kwargs)

[Bug]: axes(position = [...]) behavior when setting axes position with the position data is not being incorporated. The two axes completely overlap ! Would expect two separate axes (these were created by adding and , which should not be necessary) ! Windows 2 Qt5Agg 8 No response No response conda No response


Question: self.solver.addConstraint(c | 'required')      def add_child(self, child, i=0, j=0):        self.children[i, j] = child        # np.ix_ returns the cross product of i and j indices        self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child      def parent_constraints(self):         # constraints that are due to the parent...

[Bug]: Subfigure breaks for some slices when using When creating a figure with you cannot use arbitrary gridspecs to create subfigures as it throws an error at some point ( I think once the layout manager actually takes effect?). This happened immediately on the call in and only on the call on No error. Should be the same as with Ubuntu 2428+g8daad3364a QtAgg 2 No response No response source No response_


Question: self.unit = unit         self.proxy_target = self.value     def __copy__(self):        return TaggedValue(self.value, self.unit)     def __getattribute__(self, name):         if name.startswith('__'):             return object.__getattribute__(self, name)diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py-- a/lib/matplotlib/lines.py++ b/lib/matplotlib/lines.py

[Bug]: Line2D should copy its inputs Currently, Line2D doesn't copy its inputs if they are already arrays. Most of the time, in-place modifications to the input arrays do not affect the draw line, because there is a cache that doesn't get invalidated, but in some circumstances, it is possible for these modifications to affect the drawn line. Instead, Line2D should just copy its inputs. This was rejected in on a memory-saving argument, but note that AxesImage (which would typically have much bigger (2D) inputs than Line2D (which has 1D inputs)) does a copy, which if anything is much worse memory-wise. (1) ! (2) (same as (1)) ! (3) (different, but only x got updated, not y) ! Modifying a posteriori should not affect the Line2D. Compare e.g. with AxesImage: Both images are identical. linux 5b1 mplcairo 39 No response No response source No response


Question: 2D lines with support for a variety of line styles, markers, colors, etc. """ <ins>import copy</ins> from numbers import Integral, Number, Real import logging


Question: ----------         x : 1D array         """        self._xorig = x        self._xorig = copy.copy(x)         self._invalidx = True         self.stale = True


Question: ----------         y : 1D array         """        self._yorig = y        self._yorig = copy.copy(y)         self._invalidy = True         self.stale = True


Question: ticks : `~matplotlib.ticker.Locator` or array-like of float      format : str or `~matplotlib.ticker.Formatter`<ins>        If string, it supports '%' operator and `str.format` formats:        e.g. ``"%4.2e"`` or ``"{x:.2e}"``.</ins>      drawedges : bool

[ENH]: use new style format strings for colorbar ticks At the moment, the default format strings in colorbar are old style ones, as in their init there is: which is a different convention from the one of a normal axis, which was introduced in . As in we pass the colorbar's formatter to the long axis, the statement above may be removed to keep the default logic only in . Right now one can pass a callable directly (although that's not documented), and the default behaviour from is triggered. However, I guess making this change for format strings would imply a deprecation cycle, as it breaks current behaviour. Another option would be to check in for what kind of string format we've been passed (unsure how, although there must be way). No response_


Question: self.locator = ticks    # Handle default in _ticker()          if isinstance(format, str):            self.formatter = ticker.FormatStrFormatter(format)            # Check format between FormatStrFormatter and StrMethodFormatter            try:                self.formatter = ticker.FormatStrFormatter(format)                _ = self.formatter(0)            except TypeError:                self.formatter = ticker.StrMethodFormatter(format)         else:             self.formatter = format  # Assume it is a Formatter or None         self.draw_all()


Question: --------         .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py         """        # We do the conversion first since not all unitized data is uniform        positions, lineoffsets, linelengths = self._process_unit_info(            [("x", positions), ("y", lineoffsets), ("y", linelengths)], kwargs)         lineoffsets, linelengths = self._process_unit_info(                [("y", lineoffsets), ("y", linelengths)], kwargs)        # fix positions, noting that it can be a list of lists:         if not np.iterable(positions):             positions = [positions]         elif any(np.iterable(position) for position in positions):

[Bug]: eventplot cannot handle multiple datetime-based series I am having the exact same issue as in (which apparently was resolved at some point, but it's not working for me) with the latest version of matplotlib as passing a list of s to is not working. TypeError Traceback (most recent call last) ~\AppData\Local\ in <module4 ts1 = [(2021, 1, 15), (2021, 1, 16), (2021, 1, 18), (2021, 1, 22), (2021, 1, 26), (2021, 1, 28), (2021, 1, 30), (2021, 2, 1), (2021, 2, 3), (2021, 2, 7), (2021, 2, 8), (2021, 2, 11), (2021, 2, 15)] 5 ts2 = [(2021, 1, 1), (2021, 1, 2), (2021, 1, 3), (2021, 1, 4), (2021, 1, 5), (2021, 1, 6), (2021, 1, 7), (2021, 1, 8), (2021, 1, 9), (2021, 1, 10), (2021, 1, 11), (2021, 1, 12), (2021, 1, 13), (2021, 1, 14), (2021, 1, 15), (2021, 1, 16), (2021, 1, 17), (2021, 1, 18), (2021, 1, 19), (2021, 1, 20), (2021, 1, 25), (2021, 1, 26), (2021, 1, 27), (2021, 1, 28), (2021, 1, 29), (2021, 1, 30), (2021, 1, 31), (2021, 2, 12)] ----6 plt.eventplot([ts1,


Question: --------         .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py         """        # We do the conversion first since not all unitized data is uniform        positions, lineoffsets, linelengths = self._process_unit_info(            [("x", positions), ("y", lineoffsets), ("y", linelengths)], kwargs)         lineoffsets, linelengths = self._process_unit_info(                [("y", lineoffsets), ("y", linelengths)], kwargs)        # fix positions, noting that it can be a list of lists:         if not np.iterable(positions):             positions = [positions]         elif any(np.iterable(position) for position in positions):

ts2], colors="black") c:\Users\User\Documents\venv\lib\site-packages\matplotlib\ in eventplot(positions, orientation, lineoffsets, linelengths, linewidths, colors, linestyles, data, kwargs) 2784 linelengths=1, linewidths=None, colors=None, 2785 linestyles='solid', , data=None, kwargs): -2786 return gca().eventplot( 2787 positions, orientation=orientation, lineoffsets=lineoffsets, 2788 linelengths=linelengths, linewidths=linewidths, colors=colors, c:\Users\User\Documents\venv\lib\site-packages\matplotlib\ in inner(ax, data, args, kwargs) 1359 def inner(ax, args, data=None, kwargs): 1360 if data is None: -1361 return func(ax, map(sanitizesequence, args), kwargs) 1362 1363 bound = (ax, *args, kwargs) c:\Users\User\Documents\venv\lib\site-packages\matplotlib\axes\ in eventplot(self, positions, orientation, lineoffsets, linelengths, linewidths, colors, linestyles, kwargs) 1321 zip(positions, lineoffsets, linelengths, linewidths, 1322 colors, linestyles): -1323 coll = mcoll.EventCollection(position, 1324 orientation=orientation, 1325 lineoffset=lineoffset, c:\Users\User\Documents\venv\lib\site-packages\matplotlib\ in init(self, positions, orientation, lineoffset, linelength, linewidth, color, linestyle, antialiased, kwargs) 1619 self.lineoffset = lineoffset 1620 self.setorientation(orientation) -1621 self.setpositions(positions) 1622 1623 def getpositions(self): c:\Users\User\Documents\venv\lib\site-packages\matplotlib\ in setpositions(self, positions) 1638 posidx = 0 if self.ishorizontal() else 1 1639 segments = ((len(positions), 2, 2)) -1640 segments[:, :, posidx] = (positions)[:, None] 1641 segments[:, 0,


Question: --------         .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py         """        # We do the conversion first since not all unitized data is uniform        positions, lineoffsets, linelengths = self._process_unit_info(            [("x", positions), ("y", lineoffsets), ("y", linelengths)], kwargs)         lineoffsets, linelengths = self._process_unit_info(                [("y", lineoffsets), ("y", linelengths)], kwargs)        # fix positions, noting that it can be a list of lists:         if not np.iterable(positions):             positions = [positions]         elif any(np.iterable(position) for position in positions):

1 - posidx] = lineoffset + linelength / 2 1642 segments[:, 1, 1 - posidx] = lineoffset - linelength / 2 TypeError: float() argument must be a string or a number, not '' An eventplot with one time series per "row" in the y-axis. Windows 3 No response 7 No response No response pip No response


Question: if len(positions) == 0:             return [] <ins>        poss = []        for position in positions:            poss += self._process_unit_info([("x", position)], kwargs)        positions = poss</ins>         # prevent 'singular' keys from **kwargs dict from overriding the effect         # of 'plural' keyword arguments (e.g. 'color' overriding 'colors')         colors = cbook._local_over_kwdict(colors, kwargs, 'color')


Question: if len(positions) == 0:             return [] <ins>        poss = []        for position in positions:            poss += self._process_unit_info([("x", position)], kwargs)        positions = poss</ins>         # prevent 'singular' keys from **kwargs dict from overriding the effect         # of 'plural' keyword arguments (e.g. 'color' overriding 'colors')         colors = cbook._local_over_kwdict(colors, kwargs, 'color')


Question: if len(positions) == 0:             return [] <ins>        poss = []        for position in positions:            poss += self._process_unit_info([("x", position)], kwargs)        positions = poss</ins>         # prevent 'singular' keys from **kwargs dict from overriding the effect         # of 'plural' keyword arguments (e.g. 'color' overriding 'colors')         colors = cbook._local_over_kwdict(colors, kwargs, 'color')