New in version 3.9.
The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615. By default, zoneinfo uses the system’s time zone data if available; if no system time zone data is available, the library will fall back to using the first-party tzdata package available on PyPI.
See also
Provides the time and datetime types with which the ZoneInfo class is designed to be used.
First-party package maintained by the CPython core developers to supply time zone data via PyPI.
ZoneInfo is a concrete implementation of the datetime.tzinfo abstract base class, and is intended to be attached to tzinfo, either via the constructor, the datetime.replace method or datetime.astimezone:
Datetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention:
These time zones also support the fold attribute introduced in PEP 495. During offset transitions which induce ambiguous times (such as a daylight saving time to standard time transition), the offset from before the transition is used when fold=0, and the offset after the transition is used when fold=1, for example:
When converting from another time zone, the fold will be set to the correct value:
The zoneinfo module does not directly provide time zone data, and instead pulls time zone information from the system time zone database or the first-party PyPI package tzdata, if available. Some systems, including notably Windows systems, do not have an IANA database available, and so for projects targeting cross-platform compatibility that require time zone data, it is recommended to declare a dependency on tzdata. If neither system data nor tzdata are available, all calls to ZoneInfo will raise ZoneInfoNotFoundError.
When ZoneInfo(key) is called, the constructor first searches the directories specified in TZPATH for a file matching key, and on failure looks for a match in the tzdata package. This behavior can be configured in three ways:
The default TZPATH includes several common deployment locations for the time zone database (except on Windows, where there are no “well-known” locations for time zone data). On POSIX systems, downstream distributors and those building Python from source who know where their system time zone data is deployed may change the default time zone path by specifying the compile-time option TZPATH (or, more likely, the configure flag --with-tzpath), which should be a string delimited by os.pathsep.
On all platforms, the configured value is available as the TZPATH key in sysconfig.get_config_var().
When initializing TZPATH (either at import time or whenever reset_tzpath() is called with no arguments), the zoneinfo module will use the environment variable PYTHONTZPATH, if it exists, to set the search path.
This is an os.pathsep-separated string containing the time zone search path to use. It must consist of only absolute rather than relative paths. Relative components specified in PYTHONTZPATH will not be used, but otherwise the behavior when a relative path is specified is implementation-defined; CPython will raise InvalidTZPathWarning, but other implementations are free to silently ignore the erroneous component or raise an exception.
To set the system to ignore the system data and use the tzdata package instead, set PYTHONTZPATH="".
The TZ search path can also be configured at runtime using the reset_tzpath() function. This is generally not an advisable operation, though it is reasonable to use it in test functions that require the use of a specific time zone path (or require disabling access to the system time zones).
A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key. Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation via ZoneInfo.clear_cache(), for all values of key, the following assertion will always be true:
key must be in the form of a relative, normalized POSIX path, with no up-level references. The constructor will raise ValueError if a non-conforming key is passed.
If no file matching key is found, the constructor will raise ZoneInfoNotFoundError.
The ZoneInfo class has two alternate constructors:
Constructs a ZoneInfo object from a file-like object returning bytes (e.g. a file opened in binary mode or an io.BytesIO object). Unlike the primary constructor, this always constructs a new object.
The key parameter sets the name of the zone for the purposes of __str__() and __repr__().
Objects created via this constructor cannot be pickled (see pickling).
An alternate constructor that bypasses the constructor’s cache. It is identical to the primary constructor, but returns a new object on each call. This is most likely to be useful for testing or demonstration purposes, but it can also be used to create a system with a different cache invalidation strategy.
Objects created via this constructor will also bypass the cache of a deserializing process when unpickled.
Caution
Using this constructor may change the semantics of your datetimes in surprising ways, only use it if you know that you need to.
The following class methods are also available:
A method for invalidating the cache on the ZoneInfo class. If no arguments are passed, all caches are invalidated and the next call to the primary constructor for each key will return a new instance.
If an iterable of key names is passed to the only_keys parameter, only the specified keys will be removed from the cache. Keys passed to only_keys but not found in the cache are ignored.
Warning
Invoking this function may change the semantics of datetimes using ZoneInfo in surprising ways; this modifies process-wide global state and thus may have wide-ranging effects. Only use it if you know that you need to.
The class has one attribute:
This is a read-only attribute that returns the value of key passed to the constructor, which should be a lookup key in the IANA time zone database (e.g. America/New_York, Europe/Paris or Asia/Tokyo).
For zones constructed from file without specifying a key parameter, this will be set to None.
Note
Although it is a somewhat common practice to expose these to end users, these values are designed to be primary keys for representing the relevant zones and not necessarily user-facing elements. Projects like CLDR (the Unicode Common Locale Data Repository) can be used to get more user-friendly strings from these keys.
The string representation returned when calling str on a ZoneInfo object defaults to using the ZoneInfo.key attribute (see the note on usage in the attribute documentation):
For objects constructed from a file without specifying a key parameter, str falls back to calling repr(). ZoneInfo’s repr is implementation-defined and not necessarily stable between versions, but it is guaranteed not to be a valid ZoneInfo key.
Rather than serializing all transition data, ZoneInfo objects are serialized by key, and ZoneInfo objects constructed from files (even those with a value for key specified) cannot be pickled.
The behavior of a ZoneInfo file depends on how it was constructed:
ZoneInfo(key): When constructed with the primary constructor, a ZoneInfo object is serialized by key, and when deserialized, the deserializing process uses the primary and thus it is expected that these are expected to be the same object as other references to the same time zone. For example, if europe_berlin_pkl is a string containing a pickle constructed from ZoneInfo("Europe/Berlin"), one would expect the following behavior:
ZoneInfo.no_cache(key): When constructed from the cache-bypassing constructor, the ZoneInfo object is also serialized by key, but when deserialized, the deserializing process uses the cache bypassing constructor. If europe_berlin_pkl_nc is a string containing a pickle constructed from ZoneInfo.no_cache("Europe/Berlin"), one would expect the following behavior:
This method of serialization requires that the time zone data for the required key be available on both the serializing and deserializing side, similar to the way that references to classes and functions are expected to exist in both the serializing and deserializing environments. It also means that no guarantees are made about the consistency of results when unpickling a ZoneInfo pickled in an environment with a different version of the time zone data.
Get a set containing all the valid keys for IANA time zones available anywhere on the time zone path. This is recalculated on every call to the function.
This function only includes canonical zone names and does not include “special” zones such as those under the posix/ and right/ directories, or the posixrules zone.
Caution
This function may open a large number of files, as the best way to determine if a file on the time zone path is a valid time zone is to read the “magic string” at the beginning.
Note
These values are not designed to be exposed to end-users; for user facing elements, applications should use something like CLDR (the Unicode Common Locale Data Repository) to get more user-friendly strings. See also the cautionary note on ZoneInfo.key.
Sets or resets the time zone search path (TZPATH) for the module. When called with no arguments, TZPATH is set to the default value.
Calling reset_tzpath will not invalidate the ZoneInfo cache, and so calls to the primary ZoneInfo constructor will only use the new TZPATH in the case of a cache miss.
The to parameter must be a sequence of strings or os.PathLike and not a string, all of which must be absolute paths. ValueError will be raised if something other than an absolute path is passed.
A read-only sequence representing the time zone search path – when constructing a ZoneInfo from a key, the key is joined to each entry in the TZPATH, and the first file found is used.
TZPATH may contain only absolute paths, never relative paths, regardless of how it is configured.
The object that zoneinfo.TZPATH points to may change in response to a call to reset_tzpath(), so it is recommended to use zoneinfo.TZPATH rather than importing TZPATH from zoneinfo or assigning a long-lived variable to zoneinfo.TZPATH.
For more information on configuring the time zone search path, see Configuring the data sources.
Raised when construction of a ZoneInfo object fails because the specified key could not be found on the system. This is a subclass of KeyError.
Raised when PYTHONTZPATH contains an invalid component that will be filtered out, such as a relative path.


Get a set containing all the valid keys for IANA time zones available anywhere on the time zone path. This is recalculated on every call to the function.
This function only includes canonical zone names and does not include “special” zones such as those under the posix/ and right/ directories, or the posixrules zone.
Caution
This function may open a large number of files, as the best way to determine if a file on the time zone path is a valid time zone is to read the “magic string” at the beginning.
Note
These values are not designed to be exposed to end-users; for user facing elements, applications should use something like CLDR (the Unicode Common Locale Data Repository) to get more user-friendly strings. See also the cautionary note on ZoneInfo.key.


Raised when PYTHONTZPATH contains an invalid component that will be filtered out, such as a relative path.


Sets or resets the time zone search path (TZPATH) for the module. When called with no arguments, TZPATH is set to the default value.
Calling reset_tzpath will not invalidate the ZoneInfo cache, and so calls to the primary ZoneInfo constructor will only use the new TZPATH in the case of a cache miss.
The to parameter must be a sequence of strings or os.PathLike and not a string, all of which must be absolute paths. ValueError will be raised if something other than an absolute path is passed.


A read-only sequence representing the time zone search path – when constructing a ZoneInfo from a key, the key is joined to each entry in the TZPATH, and the first file found is used.
TZPATH may contain only absolute paths, never relative paths, regardless of how it is configured.
The object that zoneinfo.TZPATH points to may change in response to a call to reset_tzpath(), so it is recommended to use zoneinfo.TZPATH rather than importing TZPATH from zoneinfo or assigning a long-lived variable to zoneinfo.TZPATH.
For more information on configuring the time zone search path, see Configuring the data sources.


A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key. Calls to the primary constructor will always return objects that compare identically; put another way, barring cache invalidation via ZoneInfo.clear_cache(), for all values of key, the following assertion will always be true:
key must be in the form of a relative, normalized POSIX path, with no up-level references. The constructor will raise ValueError if a non-conforming key is passed.
If no file matching key is found, the constructor will raise ZoneInfoNotFoundError.


A method for invalidating the cache on the ZoneInfo class. If no arguments are passed, all caches are invalidated and the next call to the primary constructor for each key will return a new instance.
If an iterable of key names is passed to the only_keys parameter, only the specified keys will be removed from the cache. Keys passed to only_keys but not found in the cache are ignored.
Warning
Invoking this function may change the semantics of datetimes using ZoneInfo in surprising ways; this modifies process-wide global state and thus may have wide-ranging effects. Only use it if you know that you need to.


Constructs a ZoneInfo object from a file-like object returning bytes (e.g. a file opened in binary mode or an io.BytesIO object). Unlike the primary constructor, this always constructs a new object.
The key parameter sets the name of the zone for the purposes of __str__() and __repr__().
Objects created via this constructor cannot be pickled (see pickling).


This is a read-only attribute that returns the value of key passed to the constructor, which should be a lookup key in the IANA time zone database (e.g. America/New_York, Europe/Paris or Asia/Tokyo).
For zones constructed from file without specifying a key parameter, this will be set to None.
Note
Although it is a somewhat common practice to expose these to end users, these values are designed to be primary keys for representing the relevant zones and not necessarily user-facing elements. Projects like CLDR (the Unicode Common Locale Data Repository) can be used to get more user-friendly strings from these keys.


An alternate constructor that bypasses the constructor’s cache. It is identical to the primary constructor, but returns a new object on each call. This is most likely to be useful for testing or demonstration purposes, but it can also be used to create a system with a different cache invalidation strategy.
Objects created via this constructor will also bypass the cache of a deserializing process when unpickled.
Caution
Using this constructor may change the semantics of your datetimes in surprising ways, only use it if you know that you need to.


Raised when construction of a ZoneInfo object fails because the specified key could not be found on the system. This is a subclass of KeyError.


This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) are provided. The threading module provides an easier to use and higher-level threading API built on top of this module.
Changed in version 3.7: This module used to be optional, it is now always available.
This module defines the following constants and functions:
Raised on thread-specific errors.
Changed in version 3.3: This is now a synonym of the built-in RuntimeError.
This is the type of lock objects.
Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments.
When the function returns, the thread silently exits.
When the function terminates with an unhandled exception, sys.unraisablehook() is called to handle the exception. The object attribute of the hook argument is function. By default, a stack trace is printed and then the thread exits (but other threads continue to run).
When the function raises a SystemExit exception, it is silently ignored.
Changed in version 3.8: sys.unraisablehook() is now used to handle unhandled exceptions.
Simulate the effect of a signal.SIGINT signal arriving in the main thread. A thread can use this function to interrupt the main thread.
If signal.SIGINT isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), this function does nothing.
Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.
Return a new lock object. Methods of locks are described below. The lock is initially unlocked.
Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.
Return the native integral Thread ID of the current thread assigned by the kernel. This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS).
Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
New in version 3.8.
Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a RuntimeError is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information).
Availability: Windows, systems with POSIX threads.
The maximum value allowed for the timeout parameter of Lock.acquire(). Specifying a timeout greater than this value will raise an OverflowError.
New in version 3.2.
Lock objects have the following methods:
Without any optional argument, this method acquires the lock unconditionally, if necessary waiting until it is released by another thread (only one thread at a time can acquire a lock — that’s their reason for existence).
If the integer waitflag argument is present, the action depends on its value: if it is zero, the lock is only acquired if it can be acquired immediately without waiting, while if it is nonzero, the lock is acquired unconditionally as above.
If the floating-point timeout argument is present and positive, it specifies the maximum wait time in seconds before returning. A negative timeout argument specifies an unbounded wait. You cannot specify a timeout if waitflag is zero.
The return value is True if the lock is acquired successfully, False if not.
Changed in version 3.2: The timeout parameter is new.
Changed in version 3.2: Lock acquires can now be interrupted by signals on POSIX.
Releases the lock. The lock must have been acquired earlier, but not necessarily by the same thread.
Return the status of the lock: True if it has been acquired by some thread, False if not.
In addition to these methods, lock objects can also be used via the with statement, e.g.:
Caveats:


Return a new lock object. Methods of locks are described below. The lock is initially unlocked.


Raised on thread-specific errors.
Changed in version 3.3: This is now a synonym of the built-in RuntimeError.


Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.


Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.


Return the native integral Thread ID of the current thread assigned by the kernel. This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS).
Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
New in version 3.8.


Simulate the effect of a signal.SIGINT signal arriving in the main thread. A thread can use this function to interrupt the main thread.
If signal.SIGINT isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), this function does nothing.


Without any optional argument, this method acquires the lock unconditionally, if necessary waiting until it is released by another thread (only one thread at a time can acquire a lock — that’s their reason for existence).
If the integer waitflag argument is present, the action depends on its value: if it is zero, the lock is only acquired if it can be acquired immediately without waiting, while if it is nonzero, the lock is acquired unconditionally as above.
If the floating-point timeout argument is present and positive, it specifies the maximum wait time in seconds before returning. A negative timeout argument specifies an unbounded wait. You cannot specify a timeout if waitflag is zero.
The return value is True if the lock is acquired successfully, False if not.
Changed in version 3.2: The timeout parameter is new.
Changed in version 3.2: Lock acquires can now be interrupted by signals on POSIX.


Return the status of the lock: True if it has been acquired by some thread, False if not.


Releases the lock. The lock must have been acquired earlier, but not necessarily by the same thread.


Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a RuntimeError is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information).
Availability: Windows, systems with POSIX threads.


Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments.
When the function returns, the thread silently exits.
When the function terminates with an unhandled exception, sys.unraisablehook() is called to handle the exception. The object attribute of the hook argument is function. By default, a stack trace is printed and then the thread exits (but other threads continue to run).
When the function raises a SystemExit exception, it is silently ignored.
Changed in version 3.8: sys.unraisablehook() is now used to handle unhandled exceptions.


The maximum value allowed for the timeout parameter of Lock.acquire(). Specifying a timeout greater than this value will raise an OverflowError.
New in version 3.2.


This constant is true if Python was not started with an -O option. See also the assert statement.


Source code: Lib/__future__.py
__future__ is a real module, and serves three purposes:
Each statement in __future__.py is of the form:
where, normally, OptionalRelease is less than MandatoryRelease, and both are 5-tuples of the same form as sys.version_info:
OptionalRelease records the first release in which the feature was accepted.
In the case of a MandatoryRelease that has not yet occurred, MandatoryRelease predicts the release in which the feature will become part of the language.
Else MandatoryRelease records when the feature became part of the language; in releases at or after that, modules no longer need a future statement to use the feature in question, but may continue to use such imports.
MandatoryRelease may also be None, meaning that a planned feature got dropped.
Instances of class _Feature have two corresponding methods, getOptionalRelease() and getMandatoryRelease().
CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the built-in function compile() to enable the feature in dynamically compiled code. This flag is stored in the compiler_flag attribute on _Feature instances.
No feature description will ever be deleted from __future__. Since its introduction in Python 2.1 the following features have found their way into the language using this mechanism:
feature
optional in
mandatory in
effect
nested_scopes
2.1.0b1
2.2
PEP 227: Statically Nested Scopes
generators
2.2.0a1
2.3
PEP 255: Simple Generators
division
2.2.0a2
3.0
PEP 238: Changing the Division Operator
absolute_import
2.5.0a1
3.0
PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement
2.5.0a1
2.6
PEP 343: The “with” Statement
print_function
2.6.0a2
3.0
PEP 3105: Make print a function
unicode_literals
2.6.0a2
3.0
PEP 3112: Bytes literals in Python 3000
generator_stop
3.5.0b1
3.7
PEP 479: StopIteration handling inside generators
annotations
3.7.0b1
3.10
PEP 563: Postponed evaluation of annotations
See also
How the compiler treats future imports.


Note
This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().
This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().
The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.
level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.
For example, the statement import spam results in bytecode resembling the following code:
The statement import spam.ham results in this call:
Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.
On the other hand, the statement from spam.ham import eggs, sausage as
saus results in
Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.
If you simply want to import a module (potentially within a package) by name, use importlib.import_module().
Changed in version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).
Changed in version 3.9: When the command line options -E or -I are being used, the environment variable PYTHONCASEOK is now ignored.


'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python
-m but not when it is imported:
For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.


Helper functions for managing the Matplotlib API.
This documentation is only relevant for Matplotlib developers, not for users.
Warning
This module and its submodules are for internal use only. Do not use them in your own code. We may change the API at any time with no warning.
Helper decorator for implementing module-level __getattr__ as a class.
This decorator must be used at the module toplevel as follows:
The __getattr__ class will be replaced by a __getattr__ function such that trying to access name on the module will resolve the corresponding property (which may be decorated e.g. with _api.deprecated for deprecating module globals). The properties are all implicitly cached. Moreover, a suitable AttributeError is generated and raised if no property with the given name exists.
kwargs must consist of a single key, value pair. If key is in _mapping, return _mapping[value]; else, raise an appropriate ValueError.
For each key, value pair in kwargs, check that value is in _values.
Sequence of values to check on.
Whether to print _values when raising ValueError.
key, value pairs as keyword arguments to find in _values.
If any value in kwargs is not found in _values.
For each key, value pair in kwargs, check that value is an instance of one of _types; if not, raise an appropriate TypeError.
As a special case, a None entry in _types is treated as NoneType.
For each key, value pair in kwargs, check that value has the shape _shape, if not, raise an appropriate ValueError.
None in the shape is treated as a "free" size that can have any length. e.g. (None, 2) -> (N, 2)
The values checked must be numpy arrays.
To check for (N, 2) shaped arrays
Bases: object
Like property, but also triggers on access via the class, and it is the class that's passed as argument.
Select and call the function that accepts *args, **kwargs.
funcs is a list of functions which should not raise any exception (other than TypeError if the arguments passed do not match their signature).
select_matching_signature tries to call each of the functions in funcs with *args, **kwargs (in the order in which they are given). Calls that fail with a TypeError are silently skipped. As soon as a call succeeds, select_matching_signature returns its return value. If no function accepts *args, **kwargs, then the TypeError raised by the last failing call is re-raised.
Callers should normally make sure that any *args, **kwargs can only bind a single func (to avoid any ambiguity), although this is not checked by select_matching_signature.
select_matching_signature is intended to help implementing signature-overloaded functions. In general, such functions should be avoided, except for back-compatibility concerns. A typical use pattern is
which allows my_func to be called either with two parameters (old1 and old2) or a single one (new). Note that the new signature is given last, so that callers get a TypeError corresponding to the new signature if the arguments they passed in do not match any signature.
warnings.warn wrapper that sets stacklevel to "outside Matplotlib".
The original emitter of the warning can be obtained by patching this function back to warnings.warn, i.e. _api.warn_external =
warnings.warn (or functools.partial(warnings.warn, stacklevel=2), etc.).
Helper functions for deprecating parts of the Matplotlib API.
This documentation is only relevant for Matplotlib developers, not for users.
Warning
This module is for internal use only. Do not use it in your own code. We may change the API at any time with no warning.
Bases: DeprecationWarning
A class for issuing deprecation warnings for Matplotlib users.
Decorator indicating that parameter name of func is being deprecated.
The actual implementation of func should keep the name parameter in its signature, or accept a **kwargs argument (through which name would be passed).
Parameters that come after the deprecated parameter effectively become keyword-only (as they cannot be passed positionally without triggering the DeprecationWarning on the deprecated parameter), and should be marked as such after the deprecation period has passed and the deprecated parameter is removed.
Parameters other than since, name, and func are keyword-only and forwarded to warn_deprecated.
Return obj.method with a deprecation if it was overridden, else None.
An unbound method, i.e. an expression of the form Class.method_name. Remember that within the body of a method, one can always use __class__ to refer to the class that is currently being defined.
Either an object of the class where method is defined, or a subclass of that class.
Whether to allow overrides by "empty" methods without emitting a warning.
Additional parameters passed to warn_deprecated to generate the deprecation warning; must at least include the "since" key.
Bases: object
Helper to deprecate public access to an attribute (or method).
This helper should only be used at class scope, as follows:
where all parameters are forwarded to deprecated. This form makes attr a property which forwards read and write access to self._attr (same name but with a leading underscore), with a deprecation warning. Note that the attribute name is derived from the name this helper is assigned to. This helper also works for deprecating methods.
Decorator to mark a function, a class, or a property as deprecated.
When deprecating a classmethod, a staticmethod, or a property, the @deprecated decorator should go under @classmethod and @staticmethod (i.e., deprecated should directly decorate the underlying callable), but over @property.
When deprecating a class C intended to be used as a base class in a multiple inheritance hierarchy, C must define an __init__ method (if C instead inherited its __init__ from its own base class, then @deprecated would mess up __init__ inheritance when installing its own (deprecation-emitting) C.__init__).
Parameters are the same as for warn_deprecated, except that obj_type defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise.
Decorator indicating that passing parameter name (or any of the following ones) positionally to func is being deprecated.
When used on a method that has a pyplot wrapper, this should be the outermost decorator, so that boilerplate.py can access the original signature.
alias of matplotlib._api.deprecation.MatplotlibDeprecationWarning
Decorator indicating that parameter old of func is renamed to new.
The actual implementation of func should use new, not old. If old is passed to func, a DeprecationWarning is emitted, and its value is used, even if new is also passed by keyword (this is to simplify pyplot wrapper functions, which always pass new explicitly to the Axes method). If new is also passed but positionally, a TypeError will be raised by the underlying function during argument binding.
Display a standardized deprecation.
The release at which this API became deprecated.
Override the default deprecation message. The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and %(removal)s format specifiers will be replaced by the values of the respective arguments passed to this function.
The name of the deprecated object.
An alternative API that the user may use in place of the deprecated API. The deprecation warning will tell the user about this alternative if provided.
If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with removal.
The object type being deprecated.
Additional text appended directly to the final message.
The expected removal version. With the default (an empty string), a removal version is automatically computed from since. Set to other Falsy values to not schedule a removal date. Cannot be used together with pending.


Helper decorator for implementing module-level __getattr__ as a class.
This decorator must be used at the module toplevel as follows:
The __getattr__ class will be replaced by a __getattr__ function such that trying to access name on the module will resolve the corresponding property (which may be decorated e.g. with _api.deprecated for deprecating module globals). The properties are all implicitly cached. Moreover, a suitable AttributeError is generated and raised if no property with the given name exists.


kwargs must consist of a single key, value pair. If key is in _mapping, return _mapping[value]; else, raise an appropriate ValueError.


For each key, value pair in kwargs, check that value is in _values.
Sequence of values to check on.
Whether to print _values when raising ValueError.
key, value pairs as keyword arguments to find in _values.
If any value in kwargs is not found in _values.


For each key, value pair in kwargs, check that value is an instance of one of _types; if not, raise an appropriate TypeError.
As a special case, a None entry in _types is treated as NoneType.


For each key, value pair in kwargs, check that value has the shape _shape, if not, raise an appropriate ValueError.
None in the shape is treated as a "free" size that can have any length. e.g. (None, 2) -> (N, 2)
The values checked must be numpy arrays.
To check for (N, 2) shaped arrays


Bases: object
Like property, but also triggers on access via the class, and it is the class that's passed as argument.


Decorator indicating that parameter name of func is being deprecated.
The actual implementation of func should keep the name parameter in its signature, or accept a **kwargs argument (through which name would be passed).
Parameters that come after the deprecated parameter effectively become keyword-only (as they cannot be passed positionally without triggering the DeprecationWarning on the deprecated parameter), and should be marked as such after the deprecation period has passed and the deprecated parameter is removed.
Parameters other than since, name, and func are keyword-only and forwarded to warn_deprecated.


Return obj.method with a deprecation if it was overridden, else None.
An unbound method, i.e. an expression of the form Class.method_name. Remember that within the body of a method, one can always use __class__ to refer to the class that is currently being defined.
Either an object of the class where method is defined, or a subclass of that class.
Whether to allow overrides by "empty" methods without emitting a warning.
Additional parameters passed to warn_deprecated to generate the deprecation warning; must at least include the "since" key.


Bases: object
Helper to deprecate public access to an attribute (or method).
This helper should only be used at class scope, as follows:
where all parameters are forwarded to deprecated. This form makes attr a property which forwards read and write access to self._attr (same name but with a leading underscore), with a deprecation warning. Note that the attribute name is derived from the name this helper is assigned to. This helper also works for deprecating methods.


Decorator to mark a function, a class, or a property as deprecated.
When deprecating a classmethod, a staticmethod, or a property, the @deprecated decorator should go under @classmethod and @staticmethod (i.e., deprecated should directly decorate the underlying callable), but over @property.
When deprecating a class C intended to be used as a base class in a multiple inheritance hierarchy, C must define an __init__ method (if C instead inherited its __init__ from its own base class, then @deprecated would mess up __init__ inheritance when installing its own (deprecation-emitting) C.__init__).
Parameters are the same as for warn_deprecated, except that obj_type defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise.


Decorator indicating that passing parameter name (or any of the following ones) positionally to func is being deprecated.
When used on a method that has a pyplot wrapper, this should be the outermost decorator, so that boilerplate.py can access the original signature.


Bases: DeprecationWarning
A class for issuing deprecation warnings for Matplotlib users.


Decorator indicating that parameter old of func is renamed to new.
The actual implementation of func should use new, not old. If old is passed to func, a DeprecationWarning is emitted, and its value is used, even if new is also passed by keyword (this is to simplify pyplot wrapper functions, which always pass new explicitly to the Axes method). If new is also passed but positionally, a TypeError will be raised by the underlying function during argument binding.


Display a standardized deprecation.
The release at which this API became deprecated.
Override the default deprecation message. The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and %(removal)s format specifiers will be replaced by the values of the respective arguments passed to this function.
The name of the deprecated object.
An alternative API that the user may use in place of the deprecated API. The deprecation warning will tell the user about this alternative if provided.
If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with removal.
The object type being deprecated.
Additional text appended directly to the final message.
The expected removal version. With the default (an empty string), a removal version is automatically computed from since. Set to other Falsy values to not schedule a removal date. Cannot be used together with pending.


Select and call the function that accepts *args, **kwargs.
funcs is a list of functions which should not raise any exception (other than TypeError if the arguments passed do not match their signature).
select_matching_signature tries to call each of the functions in funcs with *args, **kwargs (in the order in which they are given). Calls that fail with a TypeError are silently skipped. As soon as a call succeeds, select_matching_signature returns its return value. If no function accepts *args, **kwargs, then the TypeError raised by the last failing call is re-raised.
Callers should normally make sure that any *args, **kwargs can only bind a single func (to avoid any ambiguity), although this is not checked by select_matching_signature.
select_matching_signature is intended to help implementing signature-overloaded functions. In general, such functions should be avoided, except for back-compatibility concerns. A typical use pattern is
which allows my_func to be called either with two parameters (old1 and old2) or a single one (new). Note that the new signature is given last, so that callers get a TypeError corresponding to the new signature if the arguments they passed in do not match any signature.


warnings.warn wrapper that sets stacklevel to "outside Matplotlib".
The original emitter of the warning can be obtained by patching this function back to warnings.warn, i.e. _api.warn_external =
warnings.warn (or functools.partial(warnings.warn, stacklevel=2), etc.).


Enums representing sets of strings that Matplotlib uses as input parameters.
Matplotlib often uses simple data types like strings or tuples to define a concept; e.g. the line capstyle can be specified as one of 'butt', 'round', or 'projecting'. The classes in this module are used internally and serve to document these concepts formally.
As an end-user you will not use these classes directly, but only the values they define.
Define how the connection between two line segments is drawn.
For a visual impression of each JoinStyle, view these docs online, or run JoinStyle.demo.
Lines in Matplotlib are typically defined by a 1D Path and a finite linewidth, where the underlying 1D Path represents the center of the stroked line.
By default, GraphicsContextBase defines the boundaries of a stroked line to simply be every point within some radius, linewidth/2, away from any point of the center line. However, this results in corners appearing "rounded", which may not be the desired behavior if you are drawing, for example, a polygon or pointed star.
Supported values:
the "arrow-tip" style. Each boundary of the filled-in area will extend in a straight line parallel to the tangent vector of the centerline at the point it meets the corner, until they meet in a sharp point.
stokes every point within a radius of linewidth/2 of the center lines.
the "squared-off" style. It can be thought of as a rounded corner where the "circular" part of the corner has been cut off.
Note
Very long miter tips are cut off (to form a bevel) after a backend-dependent limit called the "miter limit", which specifies the maximum allowed ratio of miter length to line width. For example, the PDF backend uses the default value of 10 specified by the PDF standard, while the SVG backend does not even specify the miter limit, resulting in a default value of 4 per the SVG specification. Matplotlib does not currently allow the user to adjust this parameter.
A more detailed description of the effect of a miter limit can be found in the Mozilla Developer Docs
(Source code, png, pdf)
Demonstrate how each JoinStyle looks for various join angles.
Define how the two endpoints (caps) of an unclosed line are drawn.
How to draw the start and end points of lines that represent a closed curve (i.e. that end in a CLOSEPOLY) is controlled by the line's JoinStyle. For all other lines, how the start and end points are drawn is controlled by the CapStyle.
For a visual impression of each CapStyle, view these docs online or run CapStyle.demo.
Supported values:
the line is squared off at its endpoint.
the line is squared off as in butt, but the filled in area extends beyond the endpoint a distance of linewidth/2.
like butt, but a semicircular cap is added to the end of the line, of radius linewidth/2.
(Source code, png, pdf)
Demonstrate how each CapStyle looks for a thick line segment.


Define how the two endpoints (caps) of an unclosed line are drawn.
How to draw the start and end points of lines that represent a closed curve (i.e. that end in a CLOSEPOLY) is controlled by the line's JoinStyle. For all other lines, how the start and end points are drawn is controlled by the CapStyle.
For a visual impression of each CapStyle, view these docs online or run CapStyle.demo.
Supported values:
the line is squared off at its endpoint.
the line is squared off as in butt, but the filled in area extends beyond the endpoint a distance of linewidth/2.
like butt, but a semicircular cap is added to the end of the line, of radius linewidth/2.
(Source code, png, pdf)
Demonstrate how each CapStyle looks for a thick line segment.


Demonstrate how each CapStyle looks for a thick line segment.


Define how the connection between two line segments is drawn.
For a visual impression of each JoinStyle, view these docs online, or run JoinStyle.demo.
Lines in Matplotlib are typically defined by a 1D Path and a finite linewidth, where the underlying 1D Path represents the center of the stroked line.
By default, GraphicsContextBase defines the boundaries of a stroked line to simply be every point within some radius, linewidth/2, away from any point of the center line. However, this results in corners appearing "rounded", which may not be the desired behavior if you are drawing, for example, a polygon or pointed star.
Supported values:
the "arrow-tip" style. Each boundary of the filled-in area will extend in a straight line parallel to the tangent vector of the centerline at the point it meets the corner, until they meet in a sharp point.
stokes every point within a radius of linewidth/2 of the center lines.
the "squared-off" style. It can be thought of as a rounded corner where the "circular" part of the corner has been cut off.
Note
Very long miter tips are cut off (to form a bevel) after a backend-dependent limit called the "miter limit", which specifies the maximum allowed ratio of miter length to line width. For example, the PDF backend uses the default value of 10 specified by the PDF standard, while the SVG backend does not even specify the miter limit, resulting in a default value of 4 per the SVG specification. Matplotlib does not currently allow the user to adjust this parameter.
A more detailed description of the effect of a miter limit can be found in the Mozilla Developer Docs
(Source code, png, pdf)
Demonstrate how each JoinStyle looks for various join angles.


Demonstrate how each JoinStyle looks for various join angles.


A python interface to Adobe Font Metrics Files.
Although a number of other Python implementations exist, and may be more complete than this, it was decided not to go with them because they were either:
It is pretty easy to use, and has no external dependencies:
As in the Adobe Font Metrics File Format Specification, all dimensions are given in units of 1/1000 of the scale factor (point size) of the font being used.
Bases: object
Parse the AFM file in file object fh.
The font family name, e.g., 'Times'.
Return the fontangle as float.
Return the cap height as float.
Return the font family name, e.g., 'Times'.
Return the font name, e.g., 'Times-Roman'.
Return the font full name, e.g., 'Times-Roman'.
Get the bounding box (ink) height of character c (space is 0).
Return the standard horizontal stem width as float, or None if not specified in AFM file.
Return the kerning pair distance (possibly 0) for chars c1 and c2.
Return the kerning pair distance (possibly 0) for chars name1 and name2.
Get the name of the character, i.e., ';' is 'semicolon'.
Return the string bounding box.
Return the string bounding box and the maximal descent.
Return the underline thickness as float.
Return the standard vertical stem width as float, or None if not specified in AFM file.
Return the font weight, e.g., 'Bold' or 'Roman'.
Get the width of the character from the character metric WX field.
Get the width of the character from a type1 character name.
Return the xheight as float.
Return the string width (including kerning) and string height as a (w, h) tuple.
Bases: tuple
Represents the character metrics of a single character.
The fields do currently only describe a subset of character metrics information defined in the AFM standard.
Create new instance of CharMetrics(width, name, bbox)
The bbox of the character (B) as a tuple (llx, lly, urx, ury).
The character name (N).
The character width (WX).
Bases: tuple
Represents the information on a composite element of a composite char.
Create new instance of CompositePart(name, dx, dy)
x-displacement of the part from the origin.
y-displacement of the part from the origin.
Name of the part, e.g. 'acute'.


Bases: object
Parse the AFM file in file object fh.
The font family name, e.g., 'Times'.
Return the fontangle as float.
Return the cap height as float.
Return the font family name, e.g., 'Times'.
Return the font name, e.g., 'Times-Roman'.
Return the font full name, e.g., 'Times-Roman'.
Get the bounding box (ink) height of character c (space is 0).
Return the standard horizontal stem width as float, or None if not specified in AFM file.
Return the kerning pair distance (possibly 0) for chars c1 and c2.
Return the kerning pair distance (possibly 0) for chars name1 and name2.
Get the name of the character, i.e., ';' is 'semicolon'.
Return the string bounding box.
Return the string bounding box and the maximal descent.
Return the underline thickness as float.
Return the standard vertical stem width as float, or None if not specified in AFM file.
Return the font weight, e.g., 'Bold' or 'Roman'.
Get the width of the character from the character metric WX field.
Get the width of the character from a type1 character name.
Return the xheight as float.
Return the string width (including kerning) and string height as a (w, h) tuple.


Return the font family name, e.g., 'Times'.


Return the font name, e.g., 'Times-Roman'.


Return the font full name, e.g., 'Times-Roman'.


Get the bounding box (ink) height of character c (space is 0).


Return the standard horizontal stem width as float, or None if not specified in AFM file.


Return the kerning pair distance (possibly 0) for chars c1 and c2.


Return the kerning pair distance (possibly 0) for chars name1 and name2.


Get the name of the character, i.e., ';' is 'semicolon'.


Return the string bounding box and the maximal descent.


Return the underline thickness as float.


Return the standard vertical stem width as float, or None if not specified in AFM file.


Return the font weight, e.g., 'Bold' or 'Roman'.


Get the width of the character from the character metric WX field.


Get the width of the character from a type1 character name.


Return the string width (including kerning) and string height as a (w, h) tuple.


Bases: tuple
Represents the character metrics of a single character.
The fields do currently only describe a subset of character metrics information defined in the AFM standard.
Create new instance of CharMetrics(width, name, bbox)
The bbox of the character (B) as a tuple (llx, lly, urx, ury).
The character name (N).
The character width (WX).


The bbox of the character (B) as a tuple (llx, lly, urx, ury).


Bases: tuple
Represents the information on a composite element of a composite char.
Create new instance of CompositePart(name, dx, dy)
x-displacement of the part from the origin.
y-displacement of the part from the origin.
Name of the part, e.g. 'acute'.


x-displacement of the part from the origin.


y-displacement of the part from the origin.


Table of Contents
The easiest way to make a live animation in Matplotlib is to use one of the Animation classes.
Animation
A base class for Animations.
FuncAnimation
Makes an animation by repeatedly calling a function func.
ArtistAnimation
Animation using a fixed set of Artist objects.
In both cases it is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers) will be garbage collected which will stop the animation.
To save an animation use Animation.save, Animation.to_html5_video, or Animation.to_jshtml.
See Helper Classes below for details about what movie formats are supported.
The inner workings of FuncAnimation is more-or-less:
with details to handle 'blitting' (to dramatically improve the live performance), to be non-blocking, not repeatedly start/stop the GUI event loop, handle repeats, multiple animated axes, and easily save the animation to a movie file.
'Blitting' is a standard technique in computer graphics. The general gist is to take an existing bit map (in our case a mostly rasterized figure) and then 'blit' one more artist on top. Thus, by managing a saved 'clean' bitmap, we can only re-draw the few artists that are changing at each frame and possibly save significant amounts of time. When we use blitting (by passing blit=True), the core loop of FuncAnimation gets a bit more complicated:
This is of course leaving out many details (such as updating the background when the figure is resized or fully re-drawn). However, this hopefully minimalist example gives a sense of how init_func and func are used inside of FuncAnimation and the theory of how 'blitting' works.
The expected signature on func and init_func is very simple to keep FuncAnimation out of your book keeping and plotting logic, but this means that the callable objects you pass in must know what artists they should be working on. There are several approaches to handling this, of varying complexity and encapsulation. The simplest approach, which works quite well in the case of a script, is to define the artist at a global scope and let Python sort things out. For example
The second method is to use functools.partial to 'bind' artists to function. A third method is to use closures to build up the required artists and functions. A fourth method is to create a class.
The provided writers fall into a few broad categories.
The Pillow writer relies on the Pillow library to write the animation, keeping all data in memory.
PillowWriter
The HTML writer generates JavaScript-based animations.
HTMLWriter
Writer for JavaScript-based HTML movies.
The pipe-based writers stream the captured frames over a pipe to an external process. The pipe-based variants tend to be more performant, but may not work on all systems.
FFMpegWriter
Pipe-based ffmpeg writer.
ImageMagickWriter
Pipe-based animated gif.
The file-based writers save temporary files for each frame which are stitched into a single file at the end. Although slower, these writers can be easier to debug.
FFMpegFileWriter
File-based ffmpeg writer.
ImageMagickFileWriter
File-based animated gif writer.
Fundamentally, a MovieWriter provides a way to grab sequential frames from the same underlying Figure object. The base class MovieWriter implements 3 methods and a context manager. The only difference between the pipe-based and file-based writers is in the arguments to their respective setup methods.
The setup() method is used to prepare the writer (possibly opening a pipe), successive calls to grab_frame() capture a single frame at a time and finish() finalizes the movie and writes the output file to disk. For example
If using the writer classes directly (not through Animation.save), it is strongly encouraged to use the saving context manager
to ensures that setup and cleanup are performed as necessary.
Animation
A base class for Animations.
TimedAnimation
Animation subclass for time-based animation.
A module-level registry is provided to map between the name of the writer and the class to allow a string to be passed to Animation.save instead of a writer instance.
MovieWriterRegistry
Registry of available writer classes by human readable name.
To reduce code duplication base classes
AbstractMovieWriter
Abstract base class for writing movies.
MovieWriter
Base class for writing movies.
FileMovieWriter
MovieWriter for writing to individual files and stitching at the end.
and mixins
FFMpegBase
Mixin class for FFMpeg output.
ImageMagickBase
Mixin class for ImageMagick output.
are provided.
See the source code for how to easily implement new MovieWriter classes.


Abstract base class for writing movies. Fundamentally, what a MovieWriter does is provide is a way to grab frames by calling grab_frame().
setup() is called to start the process and finish() is called afterwards.
This class is set up to provide for writing movie frame data to a pipe. saving() is provided as a context manager to facilitate this process as:
The use of the context manager ensures that setup() and finish() are performed as necessary.
An instance of a concrete subclass of this class can be given as the writer argument of Animation.save().
__init__([fps, metadata, codec, bitrate])
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi])
Setup for writing the movie file.
frame_size
A tuple (width, height) in pixels of a movie frame.
Finish any processing for writing the movie.
A tuple (width, height) in pixels of a movie frame.
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.
Context manager to facilitate writing the movie file.
*args, **kw are any parameters that should be passed to setup.
Setup for writing the movie file.
The figure object that contains the information for frames.
The filename of the resulting movie file.
The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.


Finish any processing for writing the movie.


Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.


Context manager to facilitate writing the movie file.
*args, **kw are any parameters that should be passed to setup.


Setup for writing the movie file.
The figure object that contains the information for frames.
The filename of the resulting movie file.
The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.


A base class for Animations.
This class is not usable as is, and should be subclassed to provide needed behavior.
Note
You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops.
The figure object used to get needed events, such as draw or resize.
A class that can run a callback when desired events are generated, as well as be stopped and started.
Examples include timers (see TimedAnimation) and file system notifications.
Whether blitting is used to optimize drawing.
See also
__init__(fig[, event_source, blit])
new_frame_seq()
Return a new sequence of frame information.
new_saved_frame_seq()
Return a new sequence of saved/cached frame information.
pause()
Pause the animation.
resume()
Resume the animation.
save(filename[, writer, fps, dpi, codec, ...])
Save the animation as a movie file by drawing every frame.
to_html5_video([embed_limit])
Convert the animation to an HTML5 <video> tag.
to_jshtml([fps, embed_frames, default_mode])
Generate HTML representation of the animation.
Return a new sequence of frame information.
Return a new sequence of saved/cached frame information.
Pause the animation.
Resume the animation.
Save the animation as a movie file by drawing every frame.
The output filename, e.g., mymovie.mp4.
A MovieWriter instance to use or a key that identifies a class to use, such as 'ffmpeg'.
Movie frame rate (per second). If not set, the frame rate from the animation's frame interval.
Controls the dots per inch for the movie frames. Together with the figure's size in inches, this controls the size of the movie.
The video codec to use. Not all codecs are supported by a given MovieWriter.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Additional Animation objects that should be included in the saved movie file. These need to be from the same matplotlib.figure.Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.
Keyword arguments passed to each savefig call used to save the individual frames.
A callback function that will be called for every frame to notify the saving progress. It must have the signature
where current_frame is the current frame number and total_frames is the total number of frames to be saved. total_frames is set to None, if the total number of frames can not be determined. Return values may exist but are ignored.
Example code to write the progress to stdout:
fps, codec, bitrate, extra_args and metadata are used to construct a MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a MovieWriter, a RuntimeError will be raised.
Convert the animation to an HTML5 <video> tag.
This saves the animation as an h264 video, encoded in base64 directly into the HTML5 video tag. This respects rcParams["animation.writer"] (default: 'ffmpeg') and rcParams["animation.bitrate"] (default: -1). This also makes use of the interval to control the speed, and uses the repeat parameter to decide whether to loop.
Limit, in MB, of the returned animation. No animation is created if the limit is exceeded. Defaults to rcParams["animation.embed_limit"] (default: 20.0) = 20.0.
An HTML5 video tag with the animation embedded as base64 encoded h264 video. If the embed_limit is exceeded, this returns the string "Video too large to embed."
Generate HTML representation of the animation.
Movie frame rate (per second). If not set, the frame rate from the animation's frame interval.
What to do when the animation ends. Must be one of {'loop',
'once', 'reflect'}. Defaults to 'loop' if self.repeat is True, otherwise 'once'.


Return a new sequence of frame information.


Return a new sequence of saved/cached frame information.


Save the animation as a movie file by drawing every frame.
The output filename, e.g., mymovie.mp4.
A MovieWriter instance to use or a key that identifies a class to use, such as 'ffmpeg'.
Movie frame rate (per second). If not set, the frame rate from the animation's frame interval.
Controls the dots per inch for the movie frames. Together with the figure's size in inches, this controls the size of the movie.
The video codec to use. Not all codecs are supported by a given MovieWriter.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Additional Animation objects that should be included in the saved movie file. These need to be from the same matplotlib.figure.Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.
Keyword arguments passed to each savefig call used to save the individual frames.
A callback function that will be called for every frame to notify the saving progress. It must have the signature
where current_frame is the current frame number and total_frames is the total number of frames to be saved. total_frames is set to None, if the total number of frames can not be determined. Return values may exist but are ignored.
Example code to write the progress to stdout:
fps, codec, bitrate, extra_args and metadata are used to construct a MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a MovieWriter, a RuntimeError will be raised.


Convert the animation to an HTML5 <video> tag.
This saves the animation as an h264 video, encoded in base64 directly into the HTML5 video tag. This respects rcParams["animation.writer"] (default: 'ffmpeg') and rcParams["animation.bitrate"] (default: -1). This also makes use of the interval to control the speed, and uses the repeat parameter to decide whether to loop.
Limit, in MB, of the returned animation. No animation is created if the limit is exceeded. Defaults to rcParams["animation.embed_limit"] (default: 20.0) = 20.0.
An HTML5 video tag with the animation embedded as base64 encoded h264 video. If the embed_limit is exceeded, this returns the string "Video too large to embed."


Generate HTML representation of the animation.
Movie frame rate (per second). If not set, the frame rate from the animation's frame interval.
What to do when the animation ends. Must be one of {'loop',
'once', 'reflect'}. Defaults to 'loop' if self.repeat is True, otherwise 'once'.


Animation using a fixed set of Artist objects.
Before creating an instance, all plotting should have taken place and the relevant artists saved.
Note
You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops.
The figure object used to get needed events, such as draw or resize.
Each list entry is a collection of Artist objects that are made visible on the corresponding frame. Other artists are made invisible.
Delay between frames in milliseconds.
The delay in milliseconds between consecutive animation runs, if repeat is True.
Whether the animation repeats when the sequence of frames is completed.
Whether blitting is used to optimize drawing.
__init__(fig, artists, *args, **kwargs)
new_frame_seq()
Return a new sequence of frame information.
new_saved_frame_seq()
Return a new sequence of saved/cached frame information.
pause()
Pause the animation.
resume()
Resume the animation.
save(filename[, writer, fps, dpi, codec, ...])
Save the animation as a movie file by drawing every frame.
to_html5_video([embed_limit])
Convert the animation to an HTML5 <video> tag.
to_jshtml([fps, embed_frames, default_mode])
Generate HTML representation of the animation.


Mixin class for FFMpeg output.
To be useful this must be multiply-inherited from with a MovieWriterBase sub-class.
__init__(*args, **kwargs)
output_args


File-based ffmpeg writer.
Frames are written to temporary files on disk and then stitched together at the end.
__init__(*args, **kwargs)
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi, frame_prefix])
Setup for writing the movie file.
frame_format
Format (png, jpeg, etc.) to use for saving the frames, which can be decided by the individual subclasses.
frame_size
A tuple (width, height) in pixels of a movie frame.
output_args
supported_formats


Pipe-based ffmpeg writer.
Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
__init__([fps, codec, bitrate, extra_args, ...])
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi])
Setup for writing the movie file.
frame_size
A tuple (width, height) in pixels of a movie frame.
output_args
supported_formats


Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.


MovieWriter for writing to individual files and stitching at the end.
This must be sub-classed to be useful.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
__init__(*args, **kwargs)
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi, frame_prefix])
Setup for writing the movie file.
frame_format
Format (png, jpeg, etc.) to use for saving the frames, which can be decided by the individual subclasses.
frame_size
A tuple (width, height) in pixels of a movie frame.
supported_formats
Finish any processing for writing the movie.
Format (png, jpeg, etc.) to use for saving the frames, which can be decided by the individual subclasses.
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.
Setup for writing the movie file.
The figure to grab the rendered frames from.
The filename of the resulting movie file.
The dpi of the output file. This, with the figure size, controls the size in pixels of the resulting movie file.
The filename prefix to use for temporary files. If None (the default), files are written to a temporary directory which is deleted by cleanup; if not None, no temporary files are deleted.


Setup for writing the movie file.
The figure to grab the rendered frames from.
The filename of the resulting movie file.
The dpi of the output file. This, with the figure size, controls the size in pixels of the resulting movie file.
The filename prefix to use for temporary files. If None (the default), files are written to a temporary directory which is deleted by cleanup; if not None, no temporary files are deleted.


Makes an animation by repeatedly calling a function func.
Note
You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops.
The figure object used to get needed events, such as draw or resize.
The function to call at each frame. The first argument will be the next value in frames. Any additional positional arguments can be supplied via the fargs parameter.
The required signature is:
If blit == True, func must return an iterable of all artists that were modified or created. This information is used by the blitting algorithm to determine which parts of the figure have to be updated. The return value is unused if blit == False and may be omitted in that case.
Source of data to pass func and each frame of the animation
If a generator function, then must have the signature:
In all of these cases, the values in frames is simply passed through to the user-supplied func and thus can be of any type.
A function used to draw a clear frame. If not given, the results of drawing from the first item in the frames sequence will be used. This function will be called once before the first frame.
The required signature is:
If blit == True, init_func must return an iterable of artists to be re-drawn. This information is used by the blitting algorithm to determine which parts of the figure have to be updated. The return value is unused if blit == False and may be omitted in that case.
Additional arguments to pass to each call to func.
Fallback for the number of values from frames to cache. This is only used if the number of frames cannot be inferred from frames, i.e. when it's an iterator without length or a generator.
Delay between frames in milliseconds.
The delay in milliseconds between consecutive animation runs, if repeat is True.
Whether the animation repeats when the sequence of frames is completed.
Whether blitting is used to optimize drawing. Note: when using blitting, any animated artists will be drawn according to their zorder; however, they will be drawn on top of any previous artists, regardless of their zorder.
Whether frame data is cached. Disabling cache might be helpful when frames contain large objects.
__init__(fig, func[, frames, init_func, ...])
new_frame_seq()
Return a new sequence of frame information.
new_saved_frame_seq()
Return a new sequence of saved/cached frame information.
pause()
Pause the animation.
resume()
Resume the animation.
save(filename[, writer, fps, dpi, codec, ...])
Save the animation as a movie file by drawing every frame.
to_html5_video([embed_limit])
Convert the animation to an HTML5 <video> tag.
to_jshtml([fps, embed_frames, default_mode])
Generate HTML representation of the animation.
Return a new sequence of frame information.
Return a new sequence of saved/cached frame information.


Writer for JavaScript-based HTML movies.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
__init__([fps, codec, bitrate, extra_args, ...])
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile, dpi[, frame_dir])
Setup for writing the movie file.
frame_format
Format (png, jpeg, etc.) to use for saving the frames, which can be decided by the individual subclasses.
frame_size
A tuple (width, height) in pixels of a movie frame.
supported_formats
Finish any processing for writing the movie.
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.
Return whether a MovieWriter subclass is actually available.
Setup for writing the movie file.
The figure to grab the rendered frames from.
The filename of the resulting movie file.
The dpi of the output file. This, with the figure size, controls the size in pixels of the resulting movie file.
The filename prefix to use for temporary files. If None (the default), files are written to a temporary directory which is deleted by cleanup; if not None, no temporary files are deleted.


Finish any processing for writing the movie.


Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.


Return whether a MovieWriter subclass is actually available.


Mixin class for ImageMagick output.
To be useful this must be multiply-inherited from with a MovieWriterBase sub-class.
__init__(*args, **kwargs)
bin_path()
isAvailable()
delay
output_args


File-based animated gif writer.
Frames are written to temporary files on disk and then stitched together at the end.
__init__(*args, **kwargs)
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi, frame_prefix])
Setup for writing the movie file.
delay
frame_format
Format (png, jpeg, etc.) to use for saving the frames, which can be decided by the individual subclasses.
frame_size
A tuple (width, height) in pixels of a movie frame.
output_args
supported_formats


Pipe-based animated gif.
Frames are streamed directly to ImageMagick via a pipe and written in a single pass.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
__init__([fps, codec, bitrate, extra_args, ...])
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi])
Setup for writing the movie file.
delay
frame_size
A tuple (width, height) in pixels of a movie frame.
output_args
supported_formats


Base class for writing movies.
This is a base class for MovieWriter subclasses that write a movie frame data to a pipe. You cannot instantiate this class directly. See examples for how to use its subclasses.
The format used in writing frame data, defaults to 'rgba'.
The figure to capture data from. This must be provided by the sub-classes.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
Movie frame rate (per second).
The codec to use.
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
__init__([fps, codec, bitrate, extra_args, ...])
bin_path()
Return the binary path to the commandline tool used by a specific subclass.
cleanup()
[Deprecated]
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
Return whether a MovieWriter subclass is actually available.
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi])
Setup for writing the movie file.
frame_size
A tuple (width, height) in pixels of a movie frame.
supported_formats
Return the binary path to the commandline tool used by a specific subclass. This is a class method so that the tool can be looked for before making a particular MovieWriter subclass available.
[Deprecated]
Deprecated since version 3.4:
Finish any processing for writing the movie.
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.
Return whether a MovieWriter subclass is actually available.
Setup for writing the movie file.
The figure object that contains the information for frames.
The filename of the resulting movie file.
The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.


Return the binary path to the commandline tool used by a specific subclass. This is a class method so that the tool can be looked for before making a particular MovieWriter subclass available.


[Deprecated]
Deprecated since version 3.4:


Setup for writing the movie file.
The figure object that contains the information for frames.
The filename of the resulting movie file.
The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.


Registry of available writer classes by human readable name.
__init__()
is_available(name)
Check if given writer is available by name.
list()
Get a list of available MovieWriters.
register(name)
Decorator for registering a class under a name.
Check if given writer is available by name.
Get a list of available MovieWriters.
Decorator for registering a class under a name.
Example use:


Check if given writer is available by name.


Decorator for registering a class under a name.
Example use:


__init__([fps, metadata, codec, bitrate])
finish()
Finish any processing for writing the movie.
grab_frame(**savefig_kwargs)
Grab the image information from the figure and save as a movie frame.
isAvailable()
saving(fig, outfile, dpi, *args, **kwargs)
Context manager to facilitate writing the movie file.
setup(fig, outfile[, dpi])
Setup for writing the movie file.
frame_size
A tuple (width, height) in pixels of a movie frame.
Finish any processing for writing the movie.
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the savefig call that saves the figure.
Setup for writing the movie file.
The figure object that contains the information for frames.
The filename of the resulting movie file.
The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file.


Animation subclass for time-based animation.
A new frame is drawn every interval milliseconds.
Note
You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops.
The figure object used to get needed events, such as draw or resize.
Delay between frames in milliseconds.
The delay in milliseconds between consecutive animation runs, if repeat is True.
Whether the animation repeats when the sequence of frames is completed.
Whether blitting is used to optimize drawing.
__init__(fig[, interval, repeat_delay, ...])
new_frame_seq()
Return a new sequence of frame information.
new_saved_frame_seq()
Return a new sequence of saved/cached frame information.
pause()
Pause the animation.
resume()
Resume the animation.
save(filename[, writer, fps, dpi, codec, ...])
Save the animation as a movie file by drawing every frame.
to_html5_video([embed_limit])
Convert the animation to an HTML5 <video> tag.
to_jshtml([fps, embed_frames, default_mode])
Generate HTML representation of the animation.


Abstract base class for objects that render into a FigureCanvas.
Typically, all visible elements in a figure are subclasses of Artist.
Artist.add_callback
Add a callback function that will be called whenever one of the Artist's properties changes.
Artist.remove_callback
Remove a callback based on its observer id.
Artist.pchanged
Call all of the registered callbacks.
Artist.get_cursor_data
Return the cursor data for a given event.
Artist.format_cursor_data
Return a string representation of data.
Artist.mouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it.
Artist.contains
Test whether the artist contains the mouse event.
Artist.pick
Process a pick event.
Artist.pickable
Return whether the artist is pickable.
Artist.set_picker
Define the picking behavior of the artist.
Artist.get_picker
Return the picking behavior of the artist.
Artist.set_clip_on
Set whether the artist uses clipping.
Artist.get_clip_on
Return whether the artist uses clipping.
Artist.set_clip_box
Set the artist's clip Bbox.
Artist.get_clip_box
Return the clipbox.
Artist.set_clip_path
Set the artist's clip path.
Artist.get_clip_path
Return the clip path.
Artist.update
Update this artist's properties from the dict props.
Artist.update_from
Copy properties from other to self.
Artist.properties
Return a dictionary of all the properties of the artist.
Artist.set
Set multiple properties at once.
Artist.draw
Draw the Artist (and its children) using the given renderer.
Artist.set_animated
Set whether the artist is intended to be used in an animation.
Artist.get_animated
Return whether the artist is animated.
Artist.set_alpha
Set the alpha value used for blending - not supported on all backends.
Artist.get_alpha
Return the alpha value used for blending - not supported on all backends.
Artist.set_snap
Set the snapping behavior.
Artist.get_snap
Return the snap setting.
Artist.set_visible
Set the artist's visibility.
Artist.get_visible
Return the visibility.
Artist.zorder
Artist.set_zorder
Set the zorder for the artist.
Artist.get_zorder
Return the artist's zorder.
Artist.set_agg_filter
Set the agg filter.
Artist.set_sketch_params
Set the sketch parameters.
Artist.get_sketch_params
Return the sketch parameters for the artist.
Artist.set_rasterized
Force rasterized (bitmap) drawing for vector graphics output.
Artist.get_rasterized
Return whether the artist is to be rasterized.
Artist.set_path_effects
Set the path effects.
Artist.get_path_effects
Artist.get_agg_filter
Return filter function to be used for agg filter.
Artist.get_window_extent
Get the artist's bounding box in display space.
Artist.get_transformed_clip_path_and_affine
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
Artist.remove
Remove the artist from the figure if possible.
Artist.axes
The Axes instance the artist resides in, or None.
Artist.set_figure
Set the Figure instance the artist belongs to.
Artist.get_figure
Return the Figure instance the artist belongs to.
Artist.get_children
Return a list of the child Artists of this Artist.
Artist.findobj
Find artist objects.
Artist.set_transform
Set the artist transform.
Artist.get_transform
Return the Transform instance used by this artist.
Artist.is_transform_set
Return whether the Artist has an explicitly set transform.
Artist.convert_xunits
Convert x using the unit type of the xaxis.
Artist.convert_yunits
Convert y using the unit type of the yaxis.
Artist.have_units
Return whether units are set on any axis.
Artist.set_gid
Set the (group) id for the artist.
Artist.get_gid
Return the group id.
Artist.set_label
Set a label that will be displayed in the legend.
Artist.get_label
Return the label used for this artist in the legend.
Artist.set_url
Set the url for the artist.
Artist.get_url
Return the url.
Artist.sticky_edges
x and y sticky edge lists for autoscaling.
Artist.set_in_layout
Set if artist is to be included in layout calculations, E.g.
Artist.get_in_layout
Return boolean flag, True if artist is included in layout calculations.
Artist.stale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
allow_rasterization
Decorator for Artist.draw method.
get
Return the value of an Artist's property, or print all of them.
getp
Return the value of an Artist's property, or print all of them.
setp
Set one or more properties on an Artist, or list allowed values.
kwdoc
Inspect an Artist class (using ArtistInspector) and return information about its settable properties and their current values.
ArtistInspector
A helper class to inspect an Artist and return information about its settable properties and their current values.


Decorator for Artist.draw method. Provides routines that run before and after the draw call. The before and after functions are useful for changing artist-dependent renderer attributes or making other setup function calls, such as starting and flushing a mixed-mode renderer.


Abstract base class for objects that render into a FigureCanvas.
Typically, all visible elements in a figure are subclasses of Artist.


Add a callback function that will be called whenever one of the Artist's properties changes.
The callback function. It must have the signature:
where artist is the calling Artist. Return values may exist but are ignored.
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later.
See also


The Axes instance the artist resides in, or None.


Test whether the artist contains the mouse event.
Whether any values are within the radius.
An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.


Convert x using the unit type of the xaxis.
If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.


Convert y using the unit type of the yaxis.
If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.


Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (Artist.get_visible returns False).
This method is overridden in the Artist subclasses.


Find artist objects.
Recursively find all Artist instances contained in the artist.
A filter criterion for the matches. This can be
Include self in the list to be checked for a match.


Return a string representation of data.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter.
See also


Return filter function to be used for agg filter.


Return the alpha value used for blending - not supported on all backends.


Return a list of the child Artists of this Artist.


Return whether the artist uses clipping.


Return the cursor data for a given event.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation.
The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse.
See also