_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_29200 |
Parameters:
signal – A signal or a list of signals to connect a function to. | |
doc_29201 |
Compute mean of groups, excluding missing values. Parameters
numeric_only:bool, default True
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data.
engine:str, default None
'cython' : Runs the operation through C-extensions from cython. 'numba' : Runs the operation through JIT compiled code from numba. None : Defaults to 'cython' or globally setting compute.use_numba New in version 1.4.0.
engine_kwargs:dict, default None
For 'cython' engine, there are no accepted engine_kwargs For 'numba' engine, the engine can accept nopython, nogil and parallel dictionary keys. The values must either be True or False. The default engine_kwargs for the 'numba' engine is {{'nopython': True, 'nogil': False, 'parallel': False}} New in version 1.4.0. Returns
pandas.Series or pandas.DataFrame
See also Series.groupby
Apply a function groupby to a Series. DataFrame.groupby
Apply a function groupby to each row or column of a DataFrame. Examples
>>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
... 'B': [np.nan, 2, 3, 4, 5],
... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])
Groupby one column and return the mean of the remaining columns in each group.
>>> df.groupby('A').mean()
B C
A
1 3.0 1.333333
2 4.0 1.500000
Groupby two columns and return the mean of the remaining column.
>>> df.groupby(['A', 'B']).mean()
C
A B
1 2.0 2.0
4.0 1.0
2 3.0 1.0
5.0 2.0
Groupby one column and return the mean of only particular column in the group.
>>> df.groupby('A')['B'].mean()
A
1 3.0
2 4.0
Name: B, dtype: float64 | |
doc_29202 | Finish the compression process. Returns the compressed data left in internal buffers. The compressor object may not be used after this method has been called. | |
doc_29203 | Context manager to swap out an item with a new object. Usage: with swap_item(obj, "item", 5):
...
This will set obj["item"] to 5 for the duration of the with block, restoring the old value at the end of the block. If item doesn’t exist on obj, it will be created and then deleted at the end of the block. The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one. | |
doc_29204 | See Migration guide for more details. tf.compat.v1.raw_ops.ComputeBatchSize
tf.raw_ops.ComputeBatchSize(
input_dataset, name=None
)
Args
input_dataset A Tensor of type variant.
name A name for the operation (optional).
Returns A Tensor of type int64. | |
doc_29205 |
Sets the seed for generating random numbers to a random number on all GPUs. It’s safe to call this function if CUDA is not available; in that case, it is silently ignored. | |
doc_29206 | The version number of this module, as a tuple of integers. This is not the version of the SQLite library. | |
doc_29207 |
Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
rectsequence of float
The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
Axes, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_subplot
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax) | |
doc_29208 | See Migration guide for more details. tf.compat.v1.raw_ops.OptionalNone
tf.raw_ops.OptionalNone(
name=None
)
Args
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_29209 | class sklearn.linear_model.Perceptron(*, penalty=None, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=0.001, shuffle=True, verbose=0, eta0=1.0, n_jobs=None, random_state=0, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False) [source]
Read more in the User Guide. Parameters
penalty{‘l2’,’l1’,’elasticnet’}, default=None
The penalty (aka regularization term) to be used.
alphafloat, default=0.0001
Constant that multiplies the regularization term if regularization is used.
l1_ratiofloat, default=0.15
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. Only used if penalty='elasticnet'. New in version 0.24.
fit_interceptbool, default=True
Whether the intercept should be estimated or not. If False, the data is assumed to be already centered.
max_iterint, default=1000
The maximum number of passes over the training data (aka epochs). It only impacts the behavior in the fit method, and not the partial_fit method. New in version 0.19.
tolfloat, default=1e-3
The stopping criterion. If it is not None, the iterations will stop when (loss > previous_loss - tol). New in version 0.19.
shufflebool, default=True
Whether or not the training data should be shuffled after each epoch.
verboseint, default=0
The verbosity level
eta0double, default=1
Constant by which the updates are multiplied.
n_jobsint, default=None
The number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance, default=None
Used to shuffle the training data, when shuffle is set to True. Pass an int for reproducible output across multiple function calls. See Glossary.
early_stoppingbool, default=False
Whether to use early stopping to terminate training when validation. score is not improving. If set to True, it will automatically set aside a stratified fraction of training data as validation and terminate training when validation score is not improving by at least tol for n_iter_no_change consecutive epochs. New in version 0.20.
validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True. New in version 0.20.
n_iter_no_changeint, default=5
Number of iterations with no improvement to wait before early stopping. New in version 0.20.
class_weightdict, {class_label: weight} or “balanced”, default=None
Preset for the class_weight fit parameter. Weights associated with classes. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary. Attributes
classes_ndarray of shape (n_classes,)
The unique classes labels.
coef_ndarray of shape (1, n_features) if n_classes == 2 else (n_classes, n_features)
Weights assigned to the features.
intercept_ndarray of shape (1,) if n_classes == 2 else (n_classes,)
Constants in decision function.
loss_function_concrete LossFunction
The function that determines the loss, or difference between the output of the algorithm and the target values.
n_iter_int
The actual number of iterations to reach the stopping criterion. For multiclass fits, it is the maximum over every binary fit.
t_int
Number of weight updates performed during training. Same as (n_iter_ * n_samples). See also
SGDClassifier
Notes Perceptron is a classification algorithm which shares the same underlying implementation with SGDClassifier. In fact, Perceptron() is equivalent to SGDClassifier(loss="perceptron",
eta0=1, learning_rate="constant", penalty=None). References https://en.wikipedia.org/wiki/Perceptron and references therein. Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.linear_model import Perceptron
>>> X, y = load_digits(return_X_y=True)
>>> clf = Perceptron(tol=1e-3, random_state=0)
>>> clf.fit(X, y)
Perceptron()
>>> clf.score(X, y)
0.939...
Methods
decision_function(X) Predict confidence scores for samples.
densify() Convert coefficient matrix to dense array format.
fit(X, y[, coef_init, intercept_init, …]) Fit linear model with Stochastic Gradient Descent.
get_params([deep]) Get parameters for this estimator.
partial_fit(X, y[, classes, sample_weight]) Perform one epoch of stochastic gradient descent on given samples.
predict(X) Predict class labels for samples in X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**kwargs) Set and validate the parameters of estimator.
sparsify() Convert coefficient matrix to sparse format.
decision_function(X) [source]
Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)
Confidence scores per (sample, class) combination. In the binary case, confidence score for self.classes_[1] where >0 means this class would be predicted.
densify() [source]
Convert coefficient matrix to dense array format. Converts the coef_ member (back) to a numpy.ndarray. This is the default format of coef_ and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns
self
Fitted estimator.
fit(X, y, coef_init=None, intercept_init=None, sample_weight=None) [source]
Fit linear model with Stochastic Gradient Descent. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
yndarray of shape (n_samples,)
Target values.
coef_initndarray of shape (n_classes, n_features), default=None
The initial coefficients to warm-start the optimization.
intercept_initndarray of shape (n_classes,), default=None
The initial intercept to warm-start the optimization.
sample_weightarray-like, shape (n_samples,), default=None
Weights applied to individual samples. If not provided, uniform weights are assumed. These weights will be multiplied with class_weight (passed through the constructor) if class_weight is specified. Returns
self :
Returns an instance of self.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
partial_fit(X, y, classes=None, sample_weight=None) [source]
Perform one epoch of stochastic gradient descent on given samples. Internally, this method uses max_iter = 1. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence and early stopping should be handled by the user. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Subset of the training data.
yndarray of shape (n_samples,)
Subset of the target values.
classesndarray of shape (n_classes,), default=None
Classes across all calls to partial_fit. Can be obtained by via np.unique(y_all), where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn’t need to contain all labels in classes.
sample_weightarray-like, shape (n_samples,), default=None
Weights applied to individual samples. If not provided, uniform weights are assumed. Returns
self :
Returns an instance of self.
predict(X) [source]
Predict class labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
set_params(**kwargs) [source]
Set and validate the parameters of estimator. Parameters
**kwargsdict
Estimator parameters. Returns
selfobject
Estimator instance.
sparsify() [source]
Convert coefficient matrix to sparse format. Converts the coef_ member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The intercept_ member is not converted. Returns
self
Fitted estimator. Notes For non-sparse models, i.e. when there are not many zeros in coef_, this may actually increase memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with (coef_ == 0).sum(), must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify.
Examples using sklearn.linear_model.Perceptron
Out-of-core classification of text documents
Comparing various online solvers
Classification of text documents using sparse features | |
doc_29210 | A type, introduced in PEP 593 (Flexible function and variable
annotations), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as Annotated is variadic). Specifically, a type T can be annotated with metadata x via the typehint Annotated[T, x]. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint Annotated[T, x] and has no special logic for metadata x, it should ignore it and simply treat the type as T. Unlike the no_type_check functionality that currently exists in the typing module which completely disables typechecking annotations on a function or a class, the Annotated type allows for both static typechecking of T (e.g., via mypy or Pyre, which can safely ignore x) together with runtime access to x within a specific application. Ultimately, the responsibility of how to interpret the annotations (if at all) is the responsibility of the tool or library encountering the Annotated type. A tool or library encountering an Annotated type can scan through the annotations to determine if they are of interest (e.g., using isinstance()). When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type. It’s up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations. Since the Annotated type allows you to put several annotations of the same (or different) type(s) on any node, the tools or libraries consuming those annotations are in charge of dealing with potential duplicates. For example, if you are doing value range analysis you might allow this: T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
Passing include_extras=True to get_type_hints() lets one access the extra annotations at runtime. The details of the syntax: The first argument to Annotated must be a valid type
Multiple type annotations are supported (Annotated supports variadic arguments): Annotated[int, ValueRange(3, 10), ctype("char")]
Annotated must be called with at least two arguments ( Annotated[int] is not valid)
The order of the annotations is preserved and matters for equality checks: Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[
int, ctype("char"), ValueRange(3, 10)
]
Nested Annotated types are flattened, with metadata ordered starting with the innermost annotation: Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
int, ValueRange(3, 10), ctype("char")
]
Duplicated annotations are not removed: Annotated[int, ValueRange(3, 10)] != Annotated[
int, ValueRange(3, 10), ValueRange(3, 10)
]
Annotated can be used with nested and generic aliases: T = TypeVar('T')
Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
V = Vec[int]
V == Annotated[list[tuple[int, int]], MaxLen(10)]
New in version 3.9. | |
doc_29211 |
Compute count of group, excluding missing values. Returns
Series or DataFrame
Count of values within each group. See also Series.groupby
Apply a function groupby to a Series. DataFrame.groupby
Apply a function groupby to each row or column of a DataFrame. | |
doc_29212 | See Migration guide for more details. tf.compat.v1.raw_ops.OneShotIterator
tf.raw_ops.OneShotIterator(
dataset_factory, output_types, output_shapes, container='',
shared_name='', name=None
)
A one-shot iterator bundles the logic for defining the dataset and the state of the iterator in a single op, which allows simple input pipelines to be defined without an additional initialization ("MakeIterator") step. One-shot iterators have the following limitations: They do not support parameterization: all logic for creating the underlying dataset must be bundled in the dataset_factory function. They are not resettable. Once a one-shot iterator reaches the end of its underlying dataset, subsequent "IteratorGetNext" operations on that iterator will always produce an OutOfRange error. For greater flexibility, use "Iterator" and "MakeIterator" to define an iterator using an arbitrary subgraph, which may capture tensors (including fed values) as parameters, and which may be reset multiple times by rerunning "MakeIterator".
Args
dataset_factory A function decorated with @Defun. A function of type () -> DT_VARIANT, where the returned DT_VARIANT is a dataset.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
container An optional string. Defaults to "".
shared_name An optional string. Defaults to "".
name A name for the operation (optional).
Returns A Tensor of type resource. | |
doc_29213 | Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element. | |
doc_29214 | See Migration guide for more details. tf.compat.v1.raw_ops.NonDeterministicInts
tf.raw_ops.NonDeterministicInts(
shape, dtype=tf.dtypes.int64, name=None
)
This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results.
Args
shape A Tensor. The shape of the output tensor.
dtype An optional tf.DType. Defaults to tf.int64. The type of the output.
name A name for the operation (optional).
Returns A Tensor of type dtype. | |
doc_29215 | Marks strings for translation but doesn’t translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. | |
doc_29216 |
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_29217 |
Return the current axisline style. | |
doc_29218 |
Extract element from each component at specified position. Extract element from lists, tuples, or strings in each element in the Series/Index. Parameters
i:int
Position of element to extract. Returns
Series or Index
Examples
>>> s = pd.Series(["String",
... (1, 2, 3),
... ["a", "b", "c"],
... 123,
... -456,
... {1: "Hello", "2": "World"}])
>>> s
0 String
1 (1, 2, 3)
2 [a, b, c]
3 123
4 -456
5 {1: 'Hello', '2': 'World'}
dtype: object
>>> s.str.get(1)
0 t
1 2
2 b
3 NaN
4 NaN
5 Hello
dtype: object
>>> s.str.get(-1)
0 g
1 3
2 c
3 NaN
4 NaN
5 None
dtype: object | |
doc_29219 |
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. | |
doc_29220 | Return the running event loop in the current OS thread. If there is no running event loop a RuntimeError is raised. This function can only be called from a coroutine or a callback. New in version 3.7. | |
doc_29221 | self.double() is equivalent to self.to(torch.float64). See to(). Parameters
memory_format (torch.memory_format, optional) – the desired memory format of returned Tensor. Default: torch.preserve_format. | |
doc_29222 | See Migration guide for more details. tf.compat.v1.raw_ops.FixedLengthRecordDataset
tf.raw_ops.FixedLengthRecordDataset(
filenames, header_bytes, record_bytes, footer_bytes, buffer_size, name=None
)
Args
filenames A Tensor of type string. A scalar or a vector containing the name(s) of the file(s) to be read.
header_bytes A Tensor of type int64. A scalar representing the number of bytes to skip at the beginning of a file.
record_bytes A Tensor of type int64. A scalar representing the number of bytes in each record.
footer_bytes A Tensor of type int64. A scalar representing the number of bytes to skip at the end of a file.
buffer_size A Tensor of type int64. A scalar representing the number of bytes to buffer. Must be > 0.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_29223 | Creates a new object of the same type of instance, replacing fields with values from changes. If instance is not a Data Class, raises TypeError. If values in changes do not specify fields, raises TypeError. The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__(), if present, is also called. Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__(). It is an error for changes to contain any fields that are defined as having init=False. A ValueError will be raised in this case. Be forewarned about how init=False fields work during a call to replace(). They are not copied from the source object, but rather are initialized in __post_init__(), if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying. | |
doc_29224 | Returns the originating port of the request using information from the HTTP_X_FORWARDED_PORT (if USE_X_FORWARDED_PORT is enabled) and SERVER_PORT META variables, in that order. | |
doc_29225 | Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before LOGOUT. | |
doc_29226 | String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or None. | |
doc_29227 |
Compute median of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex Parameters
numeric_only:bool, default True
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns
Series or DataFrame
Median of values within each group. See also Series.groupby
Apply a function groupby to a Series. DataFrame.groupby
Apply a function groupby to each row or column of a DataFrame. | |
doc_29228 |
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_29229 |
The module is mainly for debug and records the tensor values during runtime. Parameters
dtype – Quantized data type
qscheme – Quantization scheme to be used
reduce_range – Reduces the range of the quantized data type by 1 bit | |
doc_29230 |
Extract FAST corners for a given image. Parameters
image2D ndarray
Input image.
nint, optional
Minimum number of consecutive pixels out of 16 pixels on the circle that should all be either brighter or darker w.r.t testpixel. A point c on the circle is darker w.r.t test pixel p if Ic < Ip - threshold and brighter if Ic > Ip + threshold. Also stands for the n in FAST-n corner detector.
thresholdfloat, optional
Threshold used in deciding whether the pixels on the circle are brighter, darker or similar w.r.t. the test pixel. Decrease the threshold when more corners are desired and vice-versa. Returns
responsendarray
FAST corner response image. References
1
Rosten, E., & Drummond, T. (2006, May). Machine learning for high-speed corner detection. In European conference on computer vision (pp. 430-443). Springer, Berlin, Heidelberg. DOI:10.1007/11744023_34 http://www.edwardrosten.com/work/rosten_2006_machine.pdf
2
Wikipedia, “Features from accelerated segment test”, https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test Examples >>> from skimage.feature import corner_fast, corner_peaks
>>> square = np.zeros((12, 12))
>>> square[3:9, 3:9] = 1
>>> square.astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> corner_peaks(corner_fast(square, 9), min_distance=1)
array([[3, 3],
[3, 8],
[8, 3],
[8, 8]]) | |
doc_29231 | class sklearn.neighbors.KNeighborsRegressor(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs) [source]
Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the User Guide. New in version 0.9. Parameters
n_neighborsint, default=5
Number of neighbors to use by default for kneighbors queries.
weights{‘uniform’, ‘distance’} or callable, default=’uniform’
weight function used in prediction. Possible values: ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally. ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree
‘kd_tree’ will use KDTree
‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. Note: fitting on sparse input will override the setting of this parameter, using brute force.
leaf_sizeint, default=30
Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
pint, default=2
Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metricstr or callable, default=’minkowski’
the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of DistanceMetric for a list of available metrics. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors.
metric_paramsdict, default=None
Additional keyword arguments for the metric function.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Doesn’t affect fit method. Attributes
effective_metric_str or callable
The distance metric to use. It will be same as the metric parameter or a synonym of it, e.g. ‘euclidean’ if the metric parameter set to ‘minkowski’ and p parameter set to 2.
effective_metric_params_dict
Additional keyword arguments for the metric function. For most metrics will be same with metric_params parameter, but may also contain the p parameter value if the effective_metric_ attribute is set to ‘minkowski’.
n_samples_fit_int
Number of samples in the fitted data. See also
NearestNeighbors
RadiusNeighborsRegressor
KNeighborsClassifier
RadiusNeighborsClassifier
Notes See Nearest Neighbors in the online documentation for a discussion of the choice of algorithm and leaf_size. Warning Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data. https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm Examples >>> X = [[0], [1], [2], [3]]
>>> y = [0, 0, 1, 1]
>>> from sklearn.neighbors import KNeighborsRegressor
>>> neigh = KNeighborsRegressor(n_neighbors=2)
>>> neigh.fit(X, y)
KNeighborsRegressor(...)
>>> print(neigh.predict([[1.5]]))
[0.5]
Methods
fit(X, y) Fit the k-nearest neighbors regressor from the training dataset.
get_params([deep]) Get parameters for this estimator.
kneighbors([X, n_neighbors, return_distance]) Finds the K-neighbors of a point.
kneighbors_graph([X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X
predict(X) Predict the target for the provided data
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit the k-nearest neighbors regressor from the training dataset. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=’precomputed’
Training data.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)
Target values. Returns
selfKNeighborsRegressor
The fitted k-nearest neighbors regressor.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
kneighbors(X=None, n_neighbors=None, return_distance=True) [source]
Finds the K-neighbors of a point. Returns indices of and distances to the neighbors of each point. Parameters
Xarray-like, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.
n_neighborsint, default=None
Number of neighbors required for each sample. The default is the value passed to the constructor.
return_distancebool, default=True
Whether or not to return the distances. Returns
neigh_distndarray of shape (n_queries, n_neighbors)
Array representing the lengths to points, only present if return_distance=True
neigh_indndarray of shape (n_queries, n_neighbors)
Indices of the nearest points in the population matrix. Examples In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1] >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=1)
>>> neigh.fit(samples)
NearestNeighbors(n_neighbors=1)
>>> print(neigh.kneighbors([[1., 1., 1.]]))
(array([[0.5]]), array([[2]]))
As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points: >>> X = [[0., 1., 0.], [1., 0., 1.]]
>>> neigh.kneighbors(X, return_distance=False)
array([[1],
[2]]...)
kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') [source]
Computes the (weighted) graph of k-Neighbors for points in X Parameters
Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For metric='precomputed' the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features).
n_neighborsint, default=None
Number of neighbors for each sample. The default is the value passed to the constructor.
mode{‘connectivity’, ‘distance’}, default=’connectivity’
Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. Returns
Asparse-matrix of shape (n_queries, n_samples_fit)
n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix is of CSR format. See also
NearestNeighbors.radius_neighbors_graph
Examples >>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=2)
>>> neigh.fit(X)
NearestNeighbors(n_neighbors=2)
>>> A = neigh.kneighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
[0., 1., 1.],
[1., 0., 1.]])
predict(X) [source]
Predict the target for the provided data Parameters
Xarray-like of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’
Test samples. Returns
yndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int
Target values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.neighbors.KNeighborsRegressor
Face completion with a multi-output estimators
Imputing missing values with variants of IterativeImputer
Nearest Neighbors regression | |
doc_29232 |
Convert series to a different kind and/or domain and/or window. Parameters
domainarray_like, optional
The domain of the converted series. If the value is None, the default domain of kind is used.
kindclass, optional
The polynomial series type class to which the current instance should be converted. If kind is None, then the class of the current instance is used.
windowarray_like, optional
The window of the converted series. If the value is None, the default window of kind is used. Returns
new_seriesseries
The returned class can be of different type than the current instance and/or have a different domain and/or different window. Notes Conversion between domains and class types can result in numerically ill defined series. | |
doc_29233 | This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists. | |
doc_29234 |
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'} | |
doc_29235 | tf.nn.sufficient_statistics(
x, axes, shift=None, keepdims=False, name=None
)
These sufficient statistics are computed using the one pass algorithm on an input that's optionally shifted. See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data
Args
x A Tensor.
axes Array of ints. Axes along which to compute mean and variance.
shift A Tensor containing the value by which to shift the data for numerical stability, or None if no shift is to be performed. A shift close to the true mean provides the most numerically stable results.
keepdims produce statistics with the same dimensionality as the input.
name Name used to scope the operations that compute the sufficient stats.
Returns Four Tensor objects of the same type as x: the count (number of elements to average over). the (possibly shifted) sum of the elements in the array. the (possibly shifted) sum of squares of the elements in the array. the shift by which the mean must be corrected or None if shift is None. | |
doc_29236 |
Return image subtracted from its local mean. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters
image2-D array (uint8, uint16)
Input image.
selem2-D array
The neighborhood expressed as a 2-D array of 1’s and 0’s.
out2-D array (same dtype as input)
If None, a new array is allocated.
maskndarray
Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).
shift_x, shift_yint
Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).
p0, p1float in [0, …, 1]
Define the [p0, p1] percentile interval to be considered for computing the value. Returns
out2-D array (same dtype as input image)
Output image. | |
doc_29237 | sklearn.preprocessing.add_dummy_feature(X, value=1.0) [source]
Augment dataset with an additional dummy feature. This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Data.
valuefloat
Value to use for the dummy feature. Returns
X{ndarray, sparse matrix} of shape (n_samples, n_features + 1)
Same data with dummy feature added as first column. Examples >>> from sklearn.preprocessing import add_dummy_feature
>>> add_dummy_feature([[0, 1], [1, 0]])
array([[1., 0., 1.],
[1., 1., 0.]]) | |
doc_29238 | Just returns self, this method is only to comply with the Decimal Specification. | |
doc_29239 | For text/* content-types, the character set (i.e. utf8) supplied by the browser. Again, “trust but verify” is the best policy here. | |
doc_29240 | Run the command described by args. Wait for command to complete, then return a CompletedProcess instance. The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - most of the arguments to this function are passed through to that interface. (timeout, input, check, and capture_output are not.) If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output. The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated. The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well. If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured. If encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode. If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen. Examples: >>> subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
New in version 3.5. Changed in version 3.6: Added encoding and errors parameters Changed in version 3.7: Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter. | |
doc_29241 | Like setdefault(), except it takes a list of values instead of a single value. | |
doc_29242 |
True if this transform has a corresponding inverse transform. | |
doc_29243 |
Bases: matplotlib.patheffects.Stroke A shortcut PathEffect for applying Stroke and then drawing the original Artist. With this class you can use artist.set_path_effects([path_effects.withStroke()])
as a shortcut for artist.set_path_effects([path_effects.Stroke(),
path_effects.Normal()])
The path will be stroked with its gc updated with the given keyword arguments, i.e., the keyword arguments should be valid gc parameter values. draw_path(renderer, gc, tpath, affine, rgbFace)[source]
Draw the path with updated gc. | |
doc_29244 |
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate. | |
doc_29245 | Return a new path with the suffix changed. If the original path doesn’t have a suffix, the new suffix is appended instead. If the suffix is an empty string, the original suffix is removed: >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('')
PureWindowsPath('README') | |
doc_29246 |
Delete all the content of the data home cache. Parameters
data_homestr, default=None
The path to scikit-learn data directory. If None, the default path is ~/sklearn_learn_data. | |
doc_29247 |
Applies a 3D convolution over a quantized 3D input composed of several input planes. See Conv3d for details and output shape. Parameters
input – quantized input tensor of shape (minibatch,in_channels,iD,iH,iW)(\text{minibatch} , \text{in\_channels} , iD , iH , iW)
weight – quantized filters of shape (out_channels,in_channelsgroups,kD,kH,kW)(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kD , kH , kW)
bias – non-quantized bias tensor of shape (out_channels)(\text{out\_channels}) . The tensor type must be torch.float.
stride – the stride of the convolving kernel. Can be a single number or a tuple (sD, sH, sW). Default: 1
padding – implicit paddings on both sides of the input. Can be a single number or a tuple (padD, padH, padW). Default: 0
dilation – the spacing between kernel elements. Can be a single number or a tuple (dD, dH, dW). Default: 1
groups – split input into groups, in_channels\text{in\_channels} should be divisible by the number of groups. Default: 1
padding_mode – the padding mode to use. Only “zeros” is supported for quantized convolution at the moment. Default: “zeros”
scale – quantization scale for the output. Default: 1.0
zero_point – quantization zero_point for the output. Default: 0
dtype – quantization data type to use. Default: torch.quint8
Examples: >>> from torch.nn.quantized import functional as qF
>>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float)
>>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float)
>>> bias = torch.randn(8, dtype=torch.float)
>>>
>>> scale, zero_point = 1.0, 0
>>> dtype_inputs = torch.quint8
>>> dtype_filters = torch.qint8
>>>
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
>>> qF.conv3d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point) | |
doc_29248 | This method is called to handle the start of a tag (e.g. <div id="main">). The tag argument is the name of the tag converted to lower case. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. The name will be translated to lower case, and quotes in the value have been removed, and character and entity references have been replaced. For instance, for the tag <A HREF="https://www.cwi.nl/">, this method would be called as handle_starttag('a', [('href', 'https://www.cwi.nl/')]). All entity references from html.entities are replaced in the attribute values. | |
doc_29249 |
Inverse the transformation. Return a vector of size nb_features with the values of Xred assigned to each group of features Parameters
Xredarray-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples Returns
Xndarray of shape (n_samples, n_features) or (n_features,)
A vector of size n_samples with the values of Xred assigned to each of the cluster of samples. | |
doc_29250 | The namespace associated with the element name. This will be a string or None. This is a read-only attribute. | |
doc_29251 | Provides a mutable list-like object where all values stored within are stored in a shared memory block. This constrains storable values to only the int, float, bool, str (less than 10M bytes each), bytes (less than 10M bytes each), and None built-in data types. It also notably differs from the built-in list type in that these lists can not change their overall length (i.e. no append, insert, etc.) and do not support the dynamic creation of new ShareableList instances via slicing. sequence is used in populating a new ShareableList full of values. Set to None to instead attach to an already existing ShareableList by its unique shared memory name. name is the unique name for the requested shared memory, as described in the definition for SharedMemory. When attaching to an existing ShareableList, specify its shared memory block’s unique name while leaving sequence set to None.
count(value)
Returns the number of occurrences of value.
index(value)
Returns first index position of value. Raises ValueError if value is not present.
format
Read-only attribute containing the struct packing format used by all currently stored values.
shm
The SharedMemory instance where the values are stored. | |
doc_29252 |
Alias for get_edgecolor. | |
doc_29253 |
Return whether the artist is animated. | |
doc_29254 | Comment element factory. This factory function creates a special element that will be serialized as an XML comment by the standard serializer. The comment string can be either a bytestring or a Unicode string. text is a string containing the comment string. Returns an element instance representing a comment. Note that XMLParser skips over comments in the input instead of creating comment objects for them. An ElementTree will only contain comment nodes if they have been inserted into to the tree using one of the Element methods. | |
doc_29255 | Alias for dim() | |
doc_29256 |
Split arrays or matrices into random train and test subsets Quick utility that wraps input validation and next(ShuffleSplit().split(X, y)) and application to input data into a single call for splitting (and optionally subsampling) data in a oneliner. Read more in the User Guide. Parameters
*arrayssequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.
test_sizefloat or int, default=None
If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If train_size is also None, it will be set to 0.25.
train_sizefloat or int, default=None
If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.
random_stateint, RandomState instance or None, default=None
Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls. See Glossary.
shufflebool, default=True
Whether or not to shuffle the data before splitting. If shuffle=False then stratify must be None.
stratifyarray-like, default=None
If not None, data is split in a stratified fashion, using this as the class labels. Read more in the User Guide. Returns
splittinglist, length=2 * len(arrays)
List containing train-test split of inputs. New in version 0.16: If the input is sparse, the output will be a scipy.sparse.csr_matrix. Else, output type is the same as the input type. Examples >>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
[0, 1],
[6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
[8, 9]])
>>> y_test
[1, 4]
>>> train_test_split(y, shuffle=False)
[[0, 1, 2], [3, 4]] | |
doc_29257 | This is a Python type object that represents the socket object type. It is the same as type(socket(...)). | |
doc_29258 | Return the clk_id of the thread-specific CPU-time clock for the specified thread_id. Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id. Warning Passing an invalid or expired thread_id may result in undefined behavior, such as segmentation fault. Availability: Unix (see the man page for pthread_getcpuclockid(3) for further information). New in version 3.7. | |
doc_29259 | The User model has a custom manager that has the following helper methods (in addition to the methods provided by BaseUserManager):
create_user(username, email=None, password=None, **extra_fields)
Creates, saves and returns a User. The username and password are set as given. The domain portion of email is automatically converted to lowercase, and the returned User object will have is_active set to True. If no password is provided, set_unusable_password() will be called. The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom user model. See Creating users for example usage.
create_superuser(username, email=None, password=None, **extra_fields)
Same as create_user(), but sets is_staff and is_superuser to True.
with_perm(perm, is_active=True, include_superusers=True, backend=None, obj=None)
Returns users that have the given permission perm either in the "<app label>.<permission codename>" format or as a Permission instance. Returns an empty queryset if no users who have the perm found. If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state. If include_superusers is True (default), the result will include superusers. If backend is passed in and it’s defined in AUTHENTICATION_BACKENDS, then this method will use it. Otherwise, it will use the backend in AUTHENTICATION_BACKENDS, if there is only one, or raise an exception. | |
doc_29260 | This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it. | |
doc_29261 |
Bases: skimage.viewer.canvastools.base.CanvasToolBase, matplotlib.widgets.RectangleSelector Widget for selecting a rectangular region in a plot. After making the desired selection, press “Enter” to accept the selection and call the on_enter callback function. Parameters
managerViewer or PlotPlugin.
Skimage viewer or plot plugin object.
on_movefunction
Function called whenever a control handle is moved. This function must accept the rectangle extents as the only argument.
on_releasefunction
Function called whenever the control handle is released.
on_enterfunction
Function called whenever the “enter” key is pressed.
maxdistfloat
Maximum pixel distance allowed when selecting control handle.
rect_propsdict
Properties for matplotlib.patches.Rectangle. This class redefines defaults in matplotlib.widgets.RectangleSelector. Examples >>> from skimage import data
>>> from skimage.viewer import ImageViewer
>>> from skimage.viewer.canvastools import RectangleTool
>>> from skimage.draw import line
>>> from skimage.draw import set_color
>>> viewer = ImageViewer(data.coffee())
>>> def print_the_rect(extents):
... global viewer
... im = viewer.image
... coord = np.int64(extents)
... [rr1, cc1] = line(coord[2],coord[0],coord[2],coord[1])
... [rr2, cc2] = line(coord[2],coord[1],coord[3],coord[1])
... [rr3, cc3] = line(coord[3],coord[1],coord[3],coord[0])
... [rr4, cc4] = line(coord[3],coord[0],coord[2],coord[0])
... set_color(im, (rr1, cc1), [255, 255, 0])
... set_color(im, (rr2, cc2), [0, 255, 255])
... set_color(im, (rr3, cc3), [255, 0, 255])
... set_color(im, (rr4, cc4), [0, 0, 0])
... viewer.image=im
>>> rect_tool = RectangleTool(viewer, on_enter=print_the_rect)
>>> viewer.show()
Attributes
extentstuple
Return (xmin, xmax, ymin, ymax).
__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None) [source]
Parameters
axAxes
The parent axes for the widget.
onselectfunction
A callback function that is called after a selection is completed. It must have the signature: def onselect(eclick: MouseEvent, erelease: MouseEvent)
where eclick and erelease are the mouse click and release MouseEvents that start and complete the selection.
drawtype{“box”, “line”, “none”}, default: “box”
Whether to draw the full rectangle box, the diagonal line of the rectangle, or nothing at all.
minspanxfloat, default: 0
Selections with an x-span less than minspanx are ignored.
minspanyfloat, default: 0
Selections with an y-span less than minspany are ignored.
useblitbool, default: False
Whether to use blitting for faster drawing (if supported by the backend).
linepropsdict, optional
Properties with which the line is drawn, if drawtype == "line". Default: dict(color="black", linestyle="-", linewidth=2, alpha=0.5)
rectpropsdict, optional
Properties with which the rectangle is drawn, if drawtype ==
"box". Default: dict(facecolor="red", edgecolor="black", alpha=0.2, fill=True)
spancoords{“data”, “pixels”}, default: “data”
Whether to interpret minspanx and minspany in data or in pixel coordinates.
buttonMouseButton, list of MouseButton, default: all buttons
Button(s) that trigger rectangle selection.
maxdistfloat, default: 10
Distance in pixels within which the interactive tool handles can be activated.
marker_propsdict
Properties with which the interactive handles are drawn. Currently not implemented and ignored.
interactivebool, default: False
Whether to draw a set of handles that allow interaction with the widget after it is drawn.
state_modifier_keysdict, optional
Keyboard modifiers which affect the widget’s behavior. Values amend the defaults. “move”: Move the existing shape, default: no modifier. “clear”: Clear the current shape, default: “escape”. “square”: Makes the shape square, default: “shift”. “center”: Make the initial point the center of the shape, default: “ctrl”. “square” and “center” can be combined.
property corners
Corners of rectangle from lower left, moving clockwise.
property edge_centers
Midpoint of rectangle edges from left, moving clockwise.
property extents
Return (xmin, xmax, ymin, ymax).
property geometry
Geometry information that gets passed to callback functions.
on_mouse_press(event) [source]
on_mouse_release(event) [source]
on_move(event) [source] | |
doc_29262 | Returns a namedtuple (values, indices) where values is the cumulative minimum of elements of input in the dimension dim. And indices is the index location of each maximum value found in the dimension dim. yi=min(x1,x2,x3,…,xi)y_i = min(x_1, x_2, x_3, \dots, x_i)
Parameters
input (Tensor) – the input tensor.
dim (int) – the dimension to do the operation over Keyword Arguments
out (tuple, optional) – the result tuple of two output tensors (values, indices) Example: >>> a = torch.randn(10)
>>> a
tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762,
0.9165, 1.6684])
>>> torch.cummin(a, dim=0)
torch.return_types.cummin(
values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298,
-1.3298, -1.3298]),
indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) | |
doc_29263 | Assert that the __all__ variable of module contains all public names. The module’s public names (its API) are detected automatically based on whether they match the public name convention and were defined in module. The name_of_module argument can specify (as a string or tuple thereof) what module(s) an API could be defined in order to be detected as a public API. One case for this is when module imports part of its public API from other modules, possibly a C backend (like csv and its _csv). The extra argument can be a set of names that wouldn’t otherwise be automatically detected as “public”, like objects without a proper __module__ attribute. If provided, it will be added to the automatically detected ones. The blacklist argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise. Example use: import bar
import foo
import unittest
from test import support
class MiscTestCase(unittest.TestCase):
def test__all__(self):
support.check__all__(self, foo)
class OtherTestCase(unittest.TestCase):
def test__all__(self):
extra = {'BAR_CONST', 'FOO_CONST'}
blacklist = {'baz'} # Undocumented name.
# bar imports part of its API from _bar.
support.check__all__(self, bar, ('bar', '_bar'),
extra=extra, blacklist=blacklist)
New in version 3.6. | |
doc_29264 | See Migration guide for more details. tf.compat.v1.parallel_stack
tf.parallel_stack(
values, name='parallel_stack'
)
Requires that the shape of inputs be known at graph construction time. Packs the list of tensors in values into a tensor with rank one higher than each tensor in values, by packing them along the first dimension. Given a list of length N of tensors of shape (A, B, C); the output tensor will have the shape (N, A, B, C). For example: x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]
The difference between stack and parallel_stack is that stack requires all the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. parallel_stack will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Unlike stack, parallel_stack does NOT support backpropagation. This is the opposite of unstack. The numpy equivalent is tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])
Args
values A list of Tensor objects with the same shape and type.
name A name for this operation (optional).
Returns
output A stacked Tensor with the same type as values. | |
doc_29265 | See Migration guide for more details. tf.compat.v1.estimator.GlobalStepWaiterHook, tf.compat.v1.train.GlobalStepWaiterHook
tf.estimator.GlobalStepWaiterHook(
wait_until_step
)
This hook delays execution until global step reaches to wait_until_step. It is used to gradually start workers in distributed settings. One example usage would be setting wait_until_step=int(K*log(task_id+1)) assuming that task_id=0 is the chief.
Args
wait_until_step an int shows until which global step should we wait. Methods after_create_session View source
after_create_session(
session, coord
)
Called when new TensorFlow session is created. This is called to signal the hooks that a new session has been created. This has two essential differences with the situation in which begin is called: When this is called, the graph is finalized and ops can no longer be added to the graph. This method will also be called as a result of recovering a wrapped session, not only at the beginning of the overall session.
Args
session A TensorFlow Session that has been created.
coord A Coordinator object which keeps track of all threads. after_run View source
after_run(
run_context, run_values
)
Called after each call to run(). The run_values argument contains results of requested ops/tensors by before_run(). The run_context argument is the same one send to before_run call. run_context.request_stop() can be called to stop the iteration. If session.run() raises any exceptions then after_run() is not called.
Args
run_context A SessionRunContext object.
run_values A SessionRunValues object. before_run View source
before_run(
run_context
)
Called before each call to run(). You can return from this call a SessionRunArgs object indicating ops or tensors to add to the upcoming run() call. These ops/tensors will be run together with the ops/tensors originally passed to the original run() call. The run args you return can also contain feeds to be added to the run() call. The run_context argument is a SessionRunContext that provides information about the upcoming run() call: the originally requested op/tensors, the TensorFlow Session. At this point graph is finalized and you can not add ops.
Args
run_context A SessionRunContext object.
Returns None or a SessionRunArgs object.
begin View source
begin()
Called once before using the session. When called, the default graph is the one that will be launched in the session. The hook can modify the graph by adding new operations to it. After the begin() call the graph will be finalized and the other callbacks can not modify the graph anymore. Second call of begin() on the same graph, should not change the graph. end View source
end(
session
)
Called at the end of session. The session argument can be used in case the hook wants to run final ops, such as saving a last checkpoint. If session.run() raises exception other than OutOfRangeError or StopIteration then end() is not called. Note the difference between end() and after_run() behavior when session.run() raises OutOfRangeError or StopIteration. In that case end() is called but after_run() is not called.
Args
session A TensorFlow Session that will be soon closed. | |
doc_29266 | Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to: def all(iterable):
for element in iterable:
if not element:
return False
return True | |
doc_29267 | Flushes the stream by calling its flush() method. Note that the close() method is inherited from Handler and so does no output, so an explicit flush() call may be needed at times. | |
doc_29268 | tf.compat.v1.metrics.mean_per_class_accuracy(
labels, predictions, num_classes, weights=None, metrics_collections=None,
updates_collections=None, name=None
)
Calculates the accuracy for each class, then takes the mean of that. For estimation of the metric over a stream of data, the function creates an update_op operation that updates the accuracy of each class and returns them. If weights is None, weights default to 1. Use weights of 0 to mask values.
Args
labels A Tensor of ground truth labels with shape [batch size] and of type int32 or int64. The tensor will be flattened if its rank > 1.
predictions A Tensor of prediction results for semantic labels, whose shape is [batch size] and type int32 or int64. The tensor will be flattened if its rank > 1.
num_classes The possible number of labels the prediction task can have. This value must be provided, since two variables with shape = [num_classes] will be allocated.
weights Optional Tensor whose rank is either 0, or the same rank as labels, and must be broadcastable to labels (i.e., all dimensions must be either 1, or the same as the corresponding labels dimension).
metrics_collections An optional list of collections that mean_per_class_accuracy' should be added to. </td> </tr><tr> <td>updates_collections</td> <td> An optional list of collectionsupdate_opshould be added to. </td> </tr><tr> <td>name` An optional variable_scope name.
Returns
mean_accuracy A Tensor representing the mean per class accuracy.
update_op An operation that updates the accuracy tensor.
Raises
ValueError If predictions and labels have mismatched shapes, or if weights is not None and its shape doesn't match predictions, or if either metrics_collections or updates_collections are not a list or tuple.
RuntimeError If eager execution is enabled. | |
doc_29269 | In-place version of arcsin() | |
doc_29270 | tf.losses.serialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.serialize
tf.keras.losses.serialize(
loss
)
Arguments
loss A Keras Loss instance or a loss function.
Returns Loss configuration dictionary. | |
doc_29271 |
Alias for get_linestyle. | |
doc_29272 | Returns True if the useragent is allowed to fetch the url according to the rules contained in the parsed robots.txt file. | |
doc_29273 | Commit the changes pending in the current transaction, by calling MSIDatabaseCommit(). | |
doc_29274 | The CliRunner subclass, by default FlaskCliRunner that is used by test_cli_runner(). Its __init__ method should take a Flask app object as the first argument. Changelog New in version 1.0. | |
doc_29275 | Find the loader for a module, optionally within the specified path. If the module is in sys.modules, then sys.modules[name].__loader__ is returned (unless the loader would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is returned if no loader is found. A dotted name does not have its parents implicitly imported as that requires loading them and that may not be desired. To properly import a submodule you will need to import all parent packages of the submodule and use the correct argument to path. New in version 3.3. Changed in version 3.4: If __loader__ is not set, raise ValueError, just like when the attribute is set to None. Deprecated since version 3.4: Use importlib.util.find_spec() instead. | |
doc_29276 | tf.initializers.Constant, tf.initializers.constant, tf.keras.initializers.constant
tf.keras.initializers.Constant(
value=0
)
Also available via the shortcut function tf.keras.initializers.constant. Only scalar values are allowed. The constant value provided must be convertible to the dtype requested when calling the initializer. Examples:
# Standalone usage:
initializer = tf.keras.initializers.Constant(3.)
values = initializer(shape=(2, 2))
# Usage in a Keras layer:
initializer = tf.keras.initializers.Constant(3.)
layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)
Args
value A Python scalar. Methods from_config View source
@classmethod
from_config(
config
)
Instantiates an initializer from a configuration dictionary. Example: initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
Args
config A Python dictionary, the output of get_config.
Returns A tf.keras.initializers.Initializer instance.
get_config View source
get_config()
Returns the configuration of the initializer as a JSON-serializable dict.
Returns A JSON-serializable Python dict.
__call__ View source
__call__(
shape, dtype=None, **kwargs
)
Returns a tensor object initialized to self.value.
Args
shape Shape of the tensor.
dtype Optional dtype of the tensor. If not specified, tf.keras.backend.floatx() is used, which default to float32 unless you configured it otherwise (via tf.keras.backend.set_floatx(float_dtype)).
**kwargs Additional keyword arguments. | |
doc_29277 | scale a surface to an arbitrary size smoothly smoothscale(Surface, (width, height), DestSurface = None) -> Surface Uses one of two different algorithms for scaling each dimension of the input surface as required. For shrinkage, the output pixels are area averages of the colors they cover. For expansion, a bilinear filter is used. For the x86-64 and i686 architectures, optimized MMX routines are included and will run much faster than other machine types. The size is a 2 number sequence for (width, height). This function only works for 24-bit or 32-bit surfaces. An exception will be thrown if the input surface bit depth is less than 24. New in pygame 1.8. | |
doc_29278 |
A popular third-party coverage tool that provides HTML output along with advanced features such as branch coverage. Command-Line Usage The trace module can be invoked from the command line. It can be as simple as python -m trace --count -C . somefile.py ...
The above will execute somefile.py and generate annotated listings of all Python modules imported during the execution into the current directory.
--help
Display usage and exit.
--version
Display the version of the module and exit.
New in version 3.8: Added --module option that allows to run an executable module. Main options At least one of the following options must be specified when invoking trace. The --listfuncs option is mutually exclusive with the --trace and --count options. When --listfuncs is provided, neither --count nor --trace are accepted, and vice versa.
-c, --count
Produce a set of annotated listing files upon program completion that shows how many times each statement was executed. See also --coverdir, --file and --no-report below.
-t, --trace
Display lines as they are executed.
-l, --listfuncs
Display the functions executed by running the program.
-r, --report
Produce an annotated list from an earlier program run that used the --count and --file option. This does not execute any code.
-T, --trackcalls
Display the calling relationships exposed by running the program.
Modifiers
-f, --file=<file>
Name of a file to accumulate counts over several tracing runs. Should be used with the --count option.
-C, --coverdir=<dir>
Directory where the report files go. The coverage report for package.module is written to file dir/package/module.cover.
-m, --missing
When generating annotated listings, mark lines which were not executed with >>>>>>.
-s, --summary
When using --count or --report, write a brief summary to stdout for each file processed.
-R, --no-report
Do not generate annotated listings. This is useful if you intend to make several runs with --count, and then produce a single set of annotated listings at the end.
-g, --timing
Prefix each line with the time since the program started. Only used while tracing.
Filters These options may be repeated multiple times.
--ignore-module=<mod>
Ignore each of the given module names and its submodules (if it is a package). The argument can be a list of names separated by a comma.
--ignore-dir=<dir>
Ignore all modules and packages in the named directory and subdirectories. The argument can be a list of directories separated by os.pathsep.
Programmatic Interface
class trace.Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)
Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed.
run(cmd)
Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec().
runctx(cmd, globals=None, locals=None)
Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.
runfunc(func, /, *args, **kwds)
Call func with the given arguments under control of the Trace object with the current tracing parameters.
results()
Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.
class trace.CoverageResults
A container for coverage results, created by Trace.results(). Should not be created directly by the user.
update(other)
Merge in data from another CoverageResults object.
write_results(show_missing=True, summary=False, coverdir=None)
Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.
A simple example demonstrating the use of the programmatic interface: import sys
import trace
# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
ignoredirs=[sys.prefix, sys.exec_prefix],
trace=0,
count=1)
# run the new command using the given tracer
tracer.run('main()')
# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".") | |
doc_29279 |
Alias for is_monotonic_increasing. | |
doc_29280 |
Roll provided date backward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_29281 | Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character. | |
doc_29282 | class multiprocessing.shared_memory.SharedMemory(name=None, create=False, size=0)
Creates a new shared memory block or attaches to an existing shared memory block. Each shared memory block is assigned a unique name. In this way, one process can create a shared memory block with a particular name and a different process can attach to that same shared memory block using that same name. As a resource for sharing data across processes, shared memory blocks may outlive the original process that created them. When one process no longer needs access to a shared memory block that might still be needed by other processes, the close() method should be called. When a shared memory block is no longer needed by any process, the unlink() method should be called to ensure proper cleanup. name is the unique name for the requested shared memory, specified as a string. When creating a new shared memory block, if None (the default) is supplied for the name, a novel name will be generated. create controls whether a new shared memory block is created (True) or an existing shared memory block is attached (False). size specifies the requested number of bytes when creating a new shared memory block. Because some platforms choose to allocate chunks of memory based upon that platform’s memory page size, the exact size of the shared memory block may be larger or equal to the size requested. When attaching to an existing shared memory block, the size parameter is ignored.
close()
Closes access to the shared memory from this instance. In order to ensure proper cleanup of resources, all instances should call close() once the instance is no longer needed. Note that calling close() does not cause the shared memory block itself to be destroyed.
unlink()
Requests that the underlying shared memory block be destroyed. In order to ensure proper cleanup of resources, unlink() should be called once (and only once) across all processes which have need for the shared memory block. After requesting its destruction, a shared memory block may or may not be immediately destroyed and this behavior may differ across platforms. Attempts to access data inside the shared memory block after unlink() has been called may result in memory access errors. Note: the last process relinquishing its hold on a shared memory block may call unlink() and close() in either order.
buf
A memoryview of contents of the shared memory block.
name
Read-only access to the unique name of the shared memory block.
size
Read-only access to size in bytes of the shared memory block.
The following example demonstrates low-level use of SharedMemory instances: >>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55]) # Modify multiple at once
>>> buffer[4] = 100 # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5]) # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy' # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5]) # Access via shm_a
b'howdy'
>>> shm_b.close() # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink() # Call unlink only once to release the shared memory
The following example demonstrates a practical use of the SharedMemory class with NumPy arrays, accessing the same numpy.ndarray from two distinct Python shells: >>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8]) # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:] # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name # We did not specify a name so one was chosen for us
'psm_21467_46075'
>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([ 1, 1, 2, 3, 5, 888])
>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([ 1, 1, 2, 3, 5, 888])
>>> # Clean up from within the second Python shell
>>> del c # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()
>>> # Clean up from within the first Python shell
>>> del b # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink() # Free and release the shared memory block at the very end
class multiprocessing.managers.SharedMemoryManager([address[, authkey]])
A subclass of BaseManager which can be used for the management of shared memory blocks across processes. A call to start() on a SharedMemoryManager instance causes a new process to be started. This new process’s sole purpose is to manage the life cycle of all shared memory blocks created through it. To trigger the release of all shared memory blocks managed by that process, call shutdown() on the instance. This triggers a SharedMemory.unlink() call on all of the SharedMemory objects managed by that process and then stops the process itself. By creating SharedMemory instances through a SharedMemoryManager, we avoid the need to manually track and trigger the freeing of shared memory resources. This class provides methods for creating and returning SharedMemory instances and for creating a list-like object (ShareableList) backed by shared memory. Refer to multiprocessing.managers.BaseManager for a description of the inherited address and authkey optional input arguments and how they may be used to connect to an existing SharedMemoryManager service from other processes.
SharedMemory(size)
Create and return a new SharedMemory object with the specified size in bytes.
ShareableList(sequence)
Create and return a new ShareableList object, initialized by the values from the input sequence.
The following example demonstrates the basic mechanisms of a SharedMemoryManager: >>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start() # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown() # Calls unlink() on sl, raw_shm, and another_sl
The following example depicts a potentially more convenient pattern for using SharedMemoryManager objects via the with statement to ensure that all shared memory blocks are released after they are no longer needed: >>> with SharedMemoryManager() as smm:
... sl = smm.ShareableList(range(2000))
... # Divide the work among two processes, storing partial results in sl
... p1 = Process(target=do_work, args=(sl, 0, 1000))
... p2 = Process(target=do_work, args=(sl, 1000, 2000))
... p1.start()
... p2.start() # A multiprocessing.Pool might be more efficient
... p1.join()
... p2.join() # Wait for all work to complete in both processes
... total_result = sum(sl) # Consolidate the partial results now in sl
When using a SharedMemoryManager in a with statement, the shared memory blocks created using that manager are all released when the with statement’s code block finishes execution.
class multiprocessing.shared_memory.ShareableList(sequence=None, *, name=None)
Provides a mutable list-like object where all values stored within are stored in a shared memory block. This constrains storable values to only the int, float, bool, str (less than 10M bytes each), bytes (less than 10M bytes each), and None built-in data types. It also notably differs from the built-in list type in that these lists can not change their overall length (i.e. no append, insert, etc.) and do not support the dynamic creation of new ShareableList instances via slicing. sequence is used in populating a new ShareableList full of values. Set to None to instead attach to an already existing ShareableList by its unique shared memory name. name is the unique name for the requested shared memory, as described in the definition for SharedMemory. When attaching to an existing ShareableList, specify its shared memory block’s unique name while leaving sequence set to None.
count(value)
Returns the number of occurrences of value.
index(value)
Returns first index position of value. Raises ValueError if value is not present.
format
Read-only attribute containing the struct packing format used by all currently stored values.
shm
The SharedMemory instance where the values are stored.
The following example demonstrates basic use of a ShareableList instance: >>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice' # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a # Use of a ShareableList after call to unlink() is unsupported
The following example depicts how one, two, or many processes may access the same ShareableList by supplying the name of the shared memory block behind it: >>> b = shared_memory.ShareableList(range(5)) # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name) # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink() | |
doc_29283 | 'blogs.blog': lambda o: "/blogs/%s/" % o.slug,
'news.story': lambda o: "/stories/%s/%s/" % (o.pub_year, o.slug),
}
The model name used in this setting should be all lowercase, regardless of the case of the actual model class name. ADMINS Default: [] (Empty list) A list of all the people who get code error notifications. When DEBUG=False and AdminEmailHandler is configured in LOGGING (done by default), Django emails these people the details of exceptions raised in the request/response cycle. Each item in the list should be a tuple of (Full name, email address). Example: [('John', 'john@example.com'), ('Mary', 'mary@example.com')]
ALLOWED_HOSTS Default: [] (Empty list) A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations. Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE). Django also allows the fully qualified domain name (FQDN) of any entries. Some browsers include a trailing dot in the Host header which Django strips when performing host validation. If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation. When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against ['.localhost', '127.0.0.1', '[::1]']. ALLOWED_HOSTS is also checked when running tests. This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection. APPEND_SLASH Default: True When set to True, if the request URL does not match any of the patterns in the URLconf and it doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. Note that the redirect may cause any data submitted in a POST request to be lost. The APPEND_SLASH setting is only used if CommonMiddleware is installed (see Middleware). See also PREPEND_WWW. CACHES Default: {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
A dictionary containing the settings for all caches to be used with Django. It is a nested dictionary whose contents maps cache aliases to a dictionary containing the options for an individual cache. The CACHES setting must configure a default cache; any number of additional caches may also be specified. If you are using a cache backend other than the local memory cache, or you need to define multiple caches, other options will be required. The following cache options are available. BACKEND Default: '' (Empty string) The cache backend to use. The built-in cache backends are: 'django.core.cache.backends.db.DatabaseCache' 'django.core.cache.backends.dummy.DummyCache' 'django.core.cache.backends.filebased.FileBasedCache' 'django.core.cache.backends.locmem.LocMemCache' 'django.core.cache.backends.memcached.PyMemcacheCache' 'django.core.cache.backends.memcached.PyLibMCCache' 'django.core.cache.backends.redis.RedisCache' You can use a cache backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path of a cache backend class (i.e. mypackage.backends.whatever.WhateverCache). Changed in Django 3.2: The PyMemcacheCache backend was added. Changed in Django 4.0: The RedisCache backend was added. KEY_FUNCTION A string containing a dotted path to a function (or any callable) that defines how to compose a prefix, version and key into a final cache key. The default implementation is equivalent to the function: def make_key(key, key_prefix, version):
return ':'.join([key_prefix, str(version), key])
You may use any key function you want, as long as it has the same argument signature. See the cache documentation for more information. KEY_PREFIX Default: '' (Empty string) A string that will be automatically included (prepended by default) to all cache keys used by the Django server. See the cache documentation for more information. LOCATION Default: '' (Empty string) The location of the cache to use. This might be the directory for a file system cache, a host and port for a memcache server, or an identifying name for a local memory cache. e.g.: CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
OPTIONS Default: None Extra parameters to pass to the cache backend. Available parameters vary depending on your cache backend. Some information on available parameters can be found in the cache arguments documentation. For more information, consult your backend module’s own documentation. TIMEOUT Default: 300 The number of seconds before a cache entry is considered stale. If the value of this setting is None, cache entries will not expire. A value of 0 causes keys to immediately expire (effectively “don’t cache”). VERSION Default: 1 The default version number for cache keys generated by the Django server. See the cache documentation for more information. CACHE_MIDDLEWARE_ALIAS Default: 'default' The cache connection to use for the cache middleware. CACHE_MIDDLEWARE_KEY_PREFIX Default: '' (Empty string) A string which will be prefixed to the cache keys generated by the cache middleware. This prefix is combined with the KEY_PREFIX setting; it does not replace it. See Django’s cache framework. CACHE_MIDDLEWARE_SECONDS Default: 600 The default number of seconds to cache a page for the cache middleware. See Django’s cache framework. CSRF_COOKIE_AGE Default: 31449600 (approximately 1 year, in seconds) The age of CSRF cookies, in seconds. The reason for setting a long-lived expiration time is to avoid problems in the case of a user closing a browser or bookmarking a page and then loading that page from a browser cache. Without persistent cookies, the form submission would fail in this case. Some browsers (specifically Internet Explorer) can disallow the use of persistent cookies or can have the indexes to the cookie jar corrupted on disk, thereby causing CSRF protection checks to (sometimes intermittently) fail. Change this setting to None to use session-based CSRF cookies, which keep the cookies in-memory instead of on persistent storage. CSRF_COOKIE_DOMAIN Default: None The domain to be used when setting the CSRF cookie. This can be useful for easily allowing cross-subdomain requests to be excluded from the normal cross site request forgery protection. It should be set to a string such as ".example.com" to allow a POST request from a form on one subdomain to be accepted by a view served from another subdomain. Please note that the presence of this setting does not imply that Django’s CSRF protection is safe from cross-subdomain attacks by default - please see the CSRF limitations section. CSRF_COOKIE_HTTPONLY Default: False Whether to use HttpOnly flag on the CSRF cookie. If this is set to True, client-side JavaScript will not be able to access the CSRF cookie. Designating the CSRF cookie as HttpOnly doesn’t offer any practical protection because CSRF is only to protect against cross-domain attacks. If an attacker can read the cookie via JavaScript, they’re already on the same domain as far as the browser knows, so they can do anything they like anyway. (XSS is a much bigger hole than CSRF.) Although the setting offers little practical benefit, it’s sometimes required by security auditors. If you enable this and need to send the value of the CSRF token with an AJAX request, your JavaScript must pull the value from a hidden CSRF token form input instead of from the cookie. See SESSION_COOKIE_HTTPONLY for details on HttpOnly. CSRF_COOKIE_NAME Default: 'csrftoken' The name of the cookie to use for the CSRF authentication token. This can be whatever you want (as long as it’s different from the other cookie names in your application). See Cross Site Request Forgery protection. CSRF_COOKIE_PATH Default: '/' The path set on the CSRF cookie. This should either match the URL path of your Django installation or be a parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own CSRF cookie. CSRF_COOKIE_SAMESITE Default: 'Lax' The value of the SameSite flag on the CSRF cookie. This flag prevents the cookie from being sent in cross-site requests. See SESSION_COOKIE_SAMESITE for details about SameSite. CSRF_COOKIE_SECURE Default: False Whether to use a secure cookie for the CSRF cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent with an HTTPS connection. CSRF_USE_SESSIONS Default: False Whether to store the CSRF token in the user’s session instead of in a cookie. It requires the use of django.contrib.sessions. Storing the CSRF token in a cookie (Django’s default) is safe, but storing it in the session is common practice in other web frameworks and therefore sometimes demanded by security auditors. Since the default error views require the CSRF token, SessionMiddleware must appear in MIDDLEWARE before any middleware that may raise an exception to trigger an error view (such as PermissionDenied) if you’re using CSRF_USE_SESSIONS. See Middleware ordering. CSRF_FAILURE_VIEW Default: 'django.views.csrf.csrf_failure' A dotted path to the view function to be used when an incoming request is rejected by the CSRF protection. The function should have this signature: def csrf_failure(request, reason=""):
...
where reason is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. It should return an HttpResponseForbidden. django.views.csrf.csrf_failure() accepts an additional template_name parameter that defaults to '403_csrf.html'. If a template with that name exists, it will be used to render the page. CSRF_HEADER_NAME Default: 'HTTP_X_CSRFTOKEN' The name of the request header used for CSRF authentication. As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'. CSRF_TRUSTED_ORIGINS Default: [] (Empty list) A list of trusted origins for unsafe requests (e.g. POST). For requests that include the Origin header, Django’s CSRF protection requires that header match the origin present in the Host header. For a secure unsafe request that doesn’t include the Origin header, the request must have a Referer header that matches the origin present in the Host header. These checks prevent, for example, a POST request from subdomain.example.com from succeeding against api.example.com. If you need cross-origin unsafe requests, continuing the example, add 'https://subdomain.example.com' to this list (and/or http://... if requests originate from an insecure page). The setting also supports subdomains, so you could add 'https://*.example.com', for example, to allow access from all subdomains of example.com. Changed in Django 4.0: The values in older versions must only include the hostname (possibly with a leading dot) and not the scheme or an asterisk. Also, Origin header checking isn’t performed in older versions. DATABASES Default: {} (Empty dictionary) A dictionary containing the settings for all databases to be used with Django. It is a nested dictionary whose contents map a database alias to a dictionary containing the options for an individual database. The DATABASES setting must configure a default database; any number of additional databases may also be specified. The simplest possible settings file is for a single-database setup using SQLite. This can be configured using the following: DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
When connecting to other database backends, such as MariaDB, MySQL, Oracle, or PostgreSQL, additional connection parameters will be required. See the ENGINE setting below on how to specify other database types. This example is for PostgreSQL: DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
The following inner options that may be required for more complex configurations are available: ATOMIC_REQUESTS Default: False Set this to True to wrap each view in a transaction on this database. See Tying transactions to HTTP requests. AUTOCOMMIT Default: True Set this to False if you want to disable Django’s transaction management and implement your own. ENGINE Default: '' (Empty string) The database backend to use. The built-in database backends are: 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' You can use a database backend that doesn’t ship with Django by setting ENGINE to a fully-qualified path (i.e. mypackage.backends.whatever). HOST Default: '' (Empty string) Which host to use when connecting to the database. An empty string means localhost. Not used with SQLite. If this value starts with a forward slash ('/') and you’re using MySQL, MySQL will connect via a Unix socket to the specified socket. For example: "HOST": '/var/run/mysql'
If you’re using MySQL and this value doesn’t start with a forward slash, then this value is assumed to be the host. If you’re using PostgreSQL, by default (empty HOST), the connection to the database is done through UNIX domain sockets (‘local’ lines in pg_hba.conf). If your UNIX domain socket is not in the standard location, use the same value of unix_socket_directory from postgresql.conf. If you want to connect through TCP sockets, set HOST to ‘localhost’ or ‘127.0.0.1’ (‘host’ lines in pg_hba.conf). On Windows, you should always define HOST, as UNIX domain sockets are not available. NAME Default: '' (Empty string) The name of the database to use. For SQLite, it’s the full path to the database file. When specifying the path, always use forward slashes, even on Windows (e.g. C:/homes/user/mysite/sqlite3.db). CONN_MAX_AGE Default: 0 The lifetime of a database connection, as an integer of seconds. Use 0 to close database connections at the end of each request — Django’s historical behavior — and None for unlimited persistent connections. OPTIONS Default: {} (Empty dictionary) Extra parameters to use when connecting to the database. Available parameters vary depending on your database backend. Some information on available parameters can be found in the Database Backends documentation. For more information, consult your backend module’s own documentation. PASSWORD Default: '' (Empty string) The password to use when connecting to the database. Not used with SQLite. PORT Default: '' (Empty string) The port to use when connecting to the database. An empty string means the default port. Not used with SQLite. TIME_ZONE Default: None A string representing the time zone for this database connection or None. This inner option of the DATABASES setting accepts the same values as the general TIME_ZONE setting. When USE_TZ is True and this option is set, reading datetimes from the database returns aware datetimes in this time zone instead of UTC. When USE_TZ is False, it is an error to set this option.
If the database backend doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t. Changing the connection time zone changes how datetimes are read from and written to the database. If Django manages the database and you don’t have a strong reason to do otherwise, you should leave this option unset. It’s best to store datetimes in UTC because it avoids ambiguous or nonexistent datetimes during daylight saving time changes. Also, receiving datetimes in UTC keeps datetime arithmetic simple — there’s no need to consider potential offset changes over a DST transition. If you’re connecting to a third-party database that stores datetimes in a local time rather than UTC, then you must set this option to the appropriate time zone. Likewise, if Django manages the database but third-party systems connect to the same database and expect to find datetimes in local time, then you must set this option.
If the database backend supports time zones (e.g. PostgreSQL), the TIME_ZONE option is very rarely needed. It can be changed at any time; the database takes care of converting datetimes to the desired time zone. Setting the time zone of the database connection may be useful for running raw SQL queries involving date/time functions provided by the database, such as date_trunc, because their results depend on the time zone. However, this has a downside: receiving all datetimes in local time makes datetime arithmetic more tricky — you must account for possible offset changes over DST transitions. Consider converting to local time explicitly with AT TIME ZONE in raw SQL queries instead of setting the TIME_ZONE option. DISABLE_SERVER_SIDE_CURSORS Default: False Set this to True if you want to disable the use of server-side cursors with QuerySet.iterator(). Transaction pooling and server-side cursors describes the use case. This is a PostgreSQL-specific setting. USER Default: '' (Empty string) The username to use when connecting to the database. Not used with SQLite. TEST Default: {} (Empty dictionary) A dictionary of settings for test databases; for more details about the creation and use of test databases, see The test database. Here’s an example with a test database configuration: DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'USER': 'mydatabaseuser',
'NAME': 'mydatabase',
'TEST': {
'NAME': 'mytestdatabase',
},
},
}
The following keys in the TEST dictionary are available: CHARSET Default: None The character set encoding used to create the test database. The value of this string is passed directly through to the database, so its format is backend-specific. Supported by the PostgreSQL (postgresql) and MySQL (mysql) backends. COLLATION Default: None The collation order to use when creating the test database. This value is passed directly to the backend, so its format is backend-specific. Only supported for the mysql backend (see the MySQL manual for details). DEPENDENCIES Default: ['default'], for all databases other than default, which has no dependencies. The creation-order dependencies of the database. See the documentation on controlling the creation order of test databases for details. MIGRATE Default: True When set to False, migrations won’t run when creating the test database. This is similar to setting None as a value in MIGRATION_MODULES, but for all apps. MIRROR Default: None The alias of the database that this database should mirror during testing. This setting exists to allow for testing of primary/replica (referred to as master/slave by some databases) configurations of multiple databases. See the documentation on testing primary/replica configurations for details. NAME Default: None The name of database to use when running the test suite. If the default value (None) is used with the SQLite database engine, the tests will use a memory resident database. For all other database engines the test database will use the name 'test_' + DATABASE_NAME. See The test database. SERIALIZE Boolean value to control whether or not the default test runner serializes the database into an in-memory JSON string before running tests (used to restore the database state between tests if you don’t have transactions). You can set this to False to speed up creation time if you don’t have any test classes with serialized_rollback=True. Deprecated since version 4.0: This setting is deprecated as it can be inferred from the databases with the serialized_rollback option enabled. TEMPLATE This is a PostgreSQL-specific setting. The name of a template (e.g. 'template0') from which to create the test database. CREATE_DB Default: True This is an Oracle-specific setting. If it is set to False, the test tablespaces won’t be automatically created at the beginning of the tests or dropped at the end. CREATE_USER Default: True This is an Oracle-specific setting. If it is set to False, the test user won’t be automatically created at the beginning of the tests and dropped at the end. USER Default: None This is an Oracle-specific setting. The username to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will use 'test_' + USER. PASSWORD Default: None This is an Oracle-specific setting. The password to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will generate a random password. ORACLE_MANAGED_FILES Default: False This is an Oracle-specific setting. If set to True, Oracle Managed Files (OMF) tablespaces will be used. DATAFILE and DATAFILE_TMP will be ignored. TBLSPACE Default: None This is an Oracle-specific setting. The name of the tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER. TBLSPACE_TMP Default: None This is an Oracle-specific setting. The name of the temporary tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER + '_temp'. DATAFILE Default: None This is an Oracle-specific setting. The name of the datafile to use for the TBLSPACE. If not provided, Django will use TBLSPACE + '.dbf'. DATAFILE_TMP Default: None This is an Oracle-specific setting. The name of the datafile to use for the TBLSPACE_TMP. If not provided, Django will use TBLSPACE_TMP + '.dbf'. DATAFILE_MAXSIZE Default: '500M' This is an Oracle-specific setting. The maximum size that the DATAFILE is allowed to grow to. DATAFILE_TMP_MAXSIZE Default: '500M' This is an Oracle-specific setting. The maximum size that the DATAFILE_TMP is allowed to grow to. DATAFILE_SIZE Default: '50M' This is an Oracle-specific setting. The initial size of the DATAFILE. DATAFILE_TMP_SIZE Default: '50M' This is an Oracle-specific setting. The initial size of the DATAFILE_TMP. DATAFILE_EXTSIZE Default: '25M' This is an Oracle-specific setting. The amount by which the DATAFILE is extended when more space is required. DATAFILE_TMP_EXTSIZE Default: '25M' This is an Oracle-specific setting. The amount by which the DATAFILE_TMP is extended when more space is required. DATA_UPLOAD_MAX_MEMORY_SIZE Default: 2621440 (i.e. 2.5 MB). The maximum size in bytes that a request body may be before a SuspiciousOperation (RequestDataTooBig) is raised. The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data. You can set this to None to disable the check. Applications that are expected to receive unusually large form posts should tune this setting. The amount of request data is correlated to the amount of memory needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level. See also FILE_UPLOAD_MAX_MEMORY_SIZE. DATA_UPLOAD_MAX_NUMBER_FIELDS Default: 1000 The maximum number of parameters that may be received via GET or POST before a SuspiciousOperation (TooManyFields) is raised. You can set this to None to disable the check. Applications that are expected to receive an unusually large number of form fields should tune this setting. The number of request parameters is correlated to the amount of time needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level. DATABASE_ROUTERS Default: [] (Empty list) The list of routers that will be used to determine which database to use when performing a database query. See the documentation on automatic database routing in multi database configurations. DATE_FORMAT Default: 'N j, Y' (e.g. Feb. 4, 2003) The default formatting to use for displaying date fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATETIME_FORMAT, TIME_FORMAT and SHORT_DATE_FORMAT. DATE_INPUT_FORMATS Default: [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
]
A list of formats that will be accepted when inputting data on a date field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATETIME_INPUT_FORMATS and TIME_INPUT_FORMATS. DATETIME_FORMAT Default: 'N j, Y, P' (e.g. Feb. 4, 2003, 4 p.m.) The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATE_FORMAT, TIME_FORMAT and SHORT_DATETIME_FORMAT. DATETIME_INPUT_FORMATS Default: [
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
]
A list of formats that will be accepted when inputting data on a datetime field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. Date-only formats are not included as datetime fields will automatically try DATE_INPUT_FORMATS in last resort. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATE_INPUT_FORMATS and TIME_INPUT_FORMATS. DEBUG Default: False A boolean that turns on/off debug mode. Never deploy a site into production with DEBUG turned on. One of the main features of debug mode is the display of detailed error pages. If your app raises an exception when DEBUG is True, Django will display a detailed traceback, including a lot of metadata about your environment, such as all the currently defined Django settings (from settings.py). As a security measure, Django will not include settings that might be sensitive, such as SECRET_KEY. Specifically, it will exclude any setting whose name includes any of the following: 'API' 'KEY' 'PASS' 'SECRET' 'SIGNATURE' 'TOKEN' Note that these are partial matches. 'PASS' will also match PASSWORD, just as 'TOKEN' will also match TOKENIZED and so on. Still, note that there are always going to be sections of your debug output that are inappropriate for public consumption. File paths, configuration options and the like all give attackers extra information about your server. It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you’re debugging, but it’ll rapidly consume memory on a production server. Finally, if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”. Note The default settings.py file created by django-admin
startproject sets DEBUG = True for convenience. DEBUG_PROPAGATE_EXCEPTIONS Default: False If set to True, Django’s exception handling of view functions (handler500, or the debug view if DEBUG is True) and logging of 500 responses (django.request) is skipped and exceptions propagate upward. This can be useful for some test setups. It shouldn’t be used on a live site unless you want your web server (instead of Django) to generate “Internal Server Error” responses. In that case, make sure your server doesn’t show the stack trace or other sensitive information in the response. DECIMAL_SEPARATOR Default: '.' (Dot) Default decimal separator used when formatting decimal numbers. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also NUMBER_GROUPING, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR. DEFAULT_AUTO_FIELD New in Django 3.2. Default: 'django.db.models.AutoField' Default primary key field type to use for models that don’t have a field with primary_key=True. Migrating auto-created through tables The value of DEFAULT_AUTO_FIELD will be respected when creating new auto-created through tables for many-to-many relationships. Unfortunately, the primary keys of existing auto-created through tables cannot currently be updated by the migrations framework. This means that if you switch the value of DEFAULT_AUTO_FIELD and then generate migrations, the primary keys of the related models will be updated, as will the foreign keys from the through table, but the primary key of the auto-created through table will not be migrated. In order to address this, you should add a RunSQL operation to your migrations to perform the required ALTER TABLE step. You can check the existing table name through sqlmigrate, dbshell, or with the field’s remote_field.through._meta.db_table property. Explicitly defined through models are already handled by the migrations system. Allowing automatic migrations for the primary key of existing auto-created through tables may be implemented at a later date. DEFAULT_CHARSET Default: 'utf-8' Default charset to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used when constructing the Content-Type header. DEFAULT_EXCEPTION_REPORTER Default: 'django.views.debug.ExceptionReporter' Default exception reporter class to be used if none has been assigned to the HttpRequest instance yet. See Custom error reports. DEFAULT_EXCEPTION_REPORTER_FILTER Default: 'django.views.debug.SafeExceptionReporterFilter' Default exception reporter filter class to be used if none has been assigned to the HttpRequest instance yet. See Filtering error reports. DEFAULT_FILE_STORAGE Default: 'django.core.files.storage.FileSystemStorage' Default file storage class to be used for any file-related operations that don’t specify a particular storage system. See Managing files. DEFAULT_FROM_EMAIL Default: 'webmaster@localhost' Default email address to use for various automated correspondence from the site manager(s). This doesn’t include error messages sent to ADMINS and MANAGERS; for that, see SERVER_EMAIL. DEFAULT_INDEX_TABLESPACE Default: '' (Empty string) Default tablespace to use for indexes on fields that don’t specify one, if the backend supports it (see Tablespaces). DEFAULT_TABLESPACE Default: '' (Empty string) Default tablespace to use for models that don’t specify one, if the backend supports it (see Tablespaces). DISALLOWED_USER_AGENTS Default: [] (Empty list) List of compiled regular expression objects representing User-Agent strings that are not allowed to visit any page, systemwide. Use this for bots/crawlers. This is only used if CommonMiddleware is installed (see Middleware). EMAIL_BACKEND Default: 'django.core.mail.backends.smtp.EmailBackend' The backend to use for sending emails. For the list of available backends see Sending email. EMAIL_FILE_PATH Default: Not defined The directory used by the file email backend to store output files. EMAIL_HOST Default: 'localhost' The host to use for sending email. See also EMAIL_PORT. EMAIL_HOST_PASSWORD Default: '' (Empty string) Password to use for the SMTP server defined in EMAIL_HOST. This setting is used in conjunction with EMAIL_HOST_USER when authenticating to the SMTP server. If either of these settings is empty, Django won’t attempt authentication. See also EMAIL_HOST_USER. EMAIL_HOST_USER Default: '' (Empty string) Username to use for the SMTP server defined in EMAIL_HOST. If empty, Django won’t attempt authentication. See also EMAIL_HOST_PASSWORD. EMAIL_PORT Default: 25 Port to use for the SMTP server defined in EMAIL_HOST. EMAIL_SUBJECT_PREFIX Default: '[Django] ' Subject-line prefix for email messages sent with django.core.mail.mail_admins or django.core.mail.mail_managers. You’ll probably want to include the trailing space. EMAIL_USE_LOCALTIME Default: False Whether to send the SMTP Date header of email messages in the local time zone (True) or in UTC (False). EMAIL_USE_TLS Default: False Whether to use a TLS (secure) connection when talking to the SMTP server. This is used for explicit TLS connections, generally on port 587. If you are experiencing hanging connections, see the implicit TLS setting EMAIL_USE_SSL. EMAIL_USE_SSL Default: False Whether to use an implicit TLS (secure) connection when talking to the SMTP server. In most email documentation this type of TLS connection is referred to as SSL. It is generally used on port 465. If you are experiencing problems, see the explicit TLS setting EMAIL_USE_TLS. Note that EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set one of those settings to True. EMAIL_SSL_CERTFILE Default: None If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-formatted certificate chain file to use for the SSL connection. EMAIL_SSL_KEYFILE Default: None If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-formatted private key file to use for the SSL connection. Note that setting EMAIL_SSL_CERTFILE and EMAIL_SSL_KEYFILE doesn’t result in any certificate checking. They’re passed to the underlying SSL connection. Please refer to the documentation of Python’s ssl.wrap_socket() function for details on how the certificate chain file and private key file are handled. EMAIL_TIMEOUT Default: None Specifies a timeout in seconds for blocking operations like the connection attempt. FILE_UPLOAD_HANDLERS Default: [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
A list of handlers to use for uploading. Changing this setting allows complete customization – even replacement – of Django’s upload process. See Managing files for details. FILE_UPLOAD_MAX_MEMORY_SIZE Default: 2621440 (i.e. 2.5 MB). The maximum size (in bytes) that an upload will be before it gets streamed to the file system. See Managing files for details. See also DATA_UPLOAD_MAX_MEMORY_SIZE. FILE_UPLOAD_DIRECTORY_PERMISSIONS Default: None The numeric mode to apply to directories created in the process of uploading files. This setting also determines the default permissions for collected static directories when using the collectstatic management command. See collectstatic for details on overriding it. This value mirrors the functionality and caveats of the FILE_UPLOAD_PERMISSIONS setting. FILE_UPLOAD_PERMISSIONS Default: 0o644 The numeric mode (i.e. 0o644) to set newly uploaded files to. For more information about what these modes mean, see the documentation for os.chmod(). If None, you’ll get operating-system dependent behavior. On most platforms, temporary files will have a mode of 0o600, and files saved from memory will be saved using the system’s standard umask. For security reasons, these permissions aren’t applied to the temporary files that are stored in FILE_UPLOAD_TEMP_DIR. This setting also determines the default permissions for collected static files when using the collectstatic management command. See collectstatic for details on overriding it. Warning Always prefix the mode with 0o . If you’re not familiar with file modes, please note that the 0o prefix is very important: it indicates an octal number, which is the way that modes must be specified. If you try to use 644, you’ll get totally incorrect behavior. FILE_UPLOAD_TEMP_DIR Default: None The directory to store data to (typically files larger than FILE_UPLOAD_MAX_MEMORY_SIZE) temporarily while uploading files. If None, Django will use the standard temporary directory for the operating system. For example, this will default to /tmp on *nix-style operating systems. See Managing files for details. FIRST_DAY_OF_WEEK Default: 0 (Sunday) A number representing the first day of the week. This is especially useful when displaying a calendar. This value is only used when not using format internationalization, or when a format cannot be found for the current locale. The value must be an integer from 0 to 6, where 0 means Sunday, 1 means Monday and so on. FIXTURE_DIRS Default: [] (Empty list) List of directories searched for fixture files, in addition to the fixtures directory of each application, in search order. Note that these paths should use Unix-style forward slashes, even on Windows. See Providing data with fixtures and Fixture loading. FORCE_SCRIPT_NAME Default: None If not None, this will be used as the value of the SCRIPT_NAME environment variable in any HTTP request. This setting can be used to override the server-provided value of SCRIPT_NAME, which may be a rewritten version of the preferred value or not supplied at all. It is also used by django.setup() to set the URL resolver script prefix outside of the request/response cycle (e.g. in management commands and standalone scripts) to generate correct URLs when SCRIPT_NAME is not /. FORM_RENDERER Default: 'django.forms.renderers.DjangoTemplates' The class that renders forms and form widgets. It must implement the low-level render API. Included form renderers are:
'django.forms.renderers.DjangoTemplates'
'django.forms.renderers.Jinja2'
FORMAT_MODULE_PATH Default: None A full Python path to a Python package that contains custom format definitions for project locales. If not None, Django will check for a formats.py file, under the directory named as the current locale, and will use the formats defined in this file. For example, if FORMAT_MODULE_PATH is set to mysite.formats, and current language is en (English), Django will expect a directory tree like: mysite/
formats/
__init__.py
en/
__init__.py
formats.py
You can also set this setting to a list of Python paths, for example: FORMAT_MODULE_PATH = [
'mysite.formats',
'some_app.formats',
]
When Django searches for a certain format, it will go through all given Python paths until it finds a module that actually defines the given format. This means that formats defined in packages farther up in the list will take precedence over the same formats in packages farther down. Available formats are: DATE_FORMAT DATE_INPUT_FORMATS
DATETIME_FORMAT, DATETIME_INPUT_FORMATS DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK MONTH_DAY_FORMAT NUMBER_GROUPING SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT THOUSAND_SEPARATOR TIME_FORMAT TIME_INPUT_FORMATS YEAR_MONTH_FORMAT IGNORABLE_404_URLS Default: [] (Empty list) List of compiled regular expression objects describing URLs that should be ignored when reporting HTTP 404 errors via email (see How to manage error reporting). Regular expressions are matched against request's full paths (including query string, if any). Use this if your site does not provide a commonly requested file such as favicon.ico or robots.txt. This is only used if BrokenLinkEmailsMiddleware is enabled (see Middleware). INSTALLED_APPS Default: [] (Empty list) A list of strings designating all applications that are enabled in this Django installation. Each string should be a dotted Python path to: an application configuration class (preferred), or a package containing an application. Learn more about application configurations. Use the application registry for introspection Your code should never access INSTALLED_APPS directly. Use django.apps.apps instead. Application names and labels must be unique in INSTALLED_APPS Application names — the dotted Python path to the application package — must be unique. There is no way to include the same application twice, short of duplicating its code under another name. Application labels — by default the final part of the name — must be unique too. For example, you can’t include both django.contrib.auth and myproject.auth. However, you can relabel an application with a custom configuration that defines a different label. These rules apply regardless of whether INSTALLED_APPS references application configuration classes or application packages. When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence. INTERNAL_IPS Default: [] (Empty list) A list of IP addresses, as strings, that: Allow the debug() context processor to add some variables to the template context. Can use the admindocs bookmarklets even if not logged in as a staff user. Are marked as “internal” (as opposed to “EXTERNAL”) in AdminEmailHandler emails. LANGUAGE_CODE Default: 'en-us' A string representing the language code for this installation. This should be in standard language ID format. For example, U.S. English is "en-us". See also the list of language identifiers and Internationalization and localization. USE_I18N must be active for this setting to have any effect. It serves two purposes: If the locale middleware isn’t in use, it decides which translation is served to all users. If the locale middleware is active, it provides a fallback language in case the user’s preferred language can’t be determined or is not supported by the website. It also provides the fallback translation when a translation for a given literal doesn’t exist for the user’s preferred language. See How Django discovers language preference for more details. LANGUAGE_COOKIE_AGE Default: None (expires at browser close) The age of the language cookie, in seconds. LANGUAGE_COOKIE_DOMAIN Default: None The domain to use for the language cookie. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie. Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies that have the old domain will not be updated. This will result in site users being unable to switch the language as long as these cookies persist. The only safe and reliable option to perform the switch is to change the language cookie name permanently (via the LANGUAGE_COOKIE_NAME setting) and to add a middleware that copies the value from the old cookie to a new one and then deletes the old one. LANGUAGE_COOKIE_HTTPONLY Default: False Whether to use HttpOnly flag on the language cookie. If this is set to True, client-side JavaScript will not be able to access the language cookie. See SESSION_COOKIE_HTTPONLY for details on HttpOnly. LANGUAGE_COOKIE_NAME Default: 'django_language' The name of the cookie to use for the language cookie. This can be whatever you want (as long as it’s different from the other cookie names in your application). See Internationalization and localization. LANGUAGE_COOKIE_PATH Default: '/' The path set on the language cookie. This should either match the URL path of your Django installation or be a parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths and each instance will only see its own language cookie. Be cautious when updating this setting on a production site. If you update this setting to use a deeper path than it previously used, existing user cookies that have the old path will not be updated. This will result in site users being unable to switch the language as long as these cookies persist. The only safe and reliable option to perform the switch is to change the language cookie name permanently (via the LANGUAGE_COOKIE_NAME setting), and to add a middleware that copies the value from the old cookie to a new one and then deletes the one. LANGUAGE_COOKIE_SAMESITE Default: None The value of the SameSite flag on the language cookie. This flag prevents the cookie from being sent in cross-site requests. See SESSION_COOKIE_SAMESITE for details about SameSite. LANGUAGE_COOKIE_SECURE Default: False Whether to use a secure cookie for the language cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS connection. LANGUAGES Default: A list of all available languages. This list is continually growing and including a copy here would inevitably become rapidly out of date. You can see the current list of translated languages by looking in django/conf/global_settings.py. The list is a list of two-tuples in the format (language code, language name) – for example, ('ja', 'Japanese'). This specifies which languages are available for language selection. See Internationalization and localization. Generally, the default value should suffice. Only set this setting if you want to restrict language selection to a subset of the Django-provided languages. If you define a custom LANGUAGES setting, you can mark the language names as translation strings using the gettext_lazy() function. Here’s a sample settings file: from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('de', _('German')),
('en', _('English')),
]
LANGUAGES_BIDI Default: A list of all language codes that are written right-to-left. You can see the current list of these languages by looking in django/conf/global_settings.py. The list contains language codes for languages that are written right-to-left. Generally, the default value should suffice. Only set this setting if you want to restrict language selection to a subset of the Django-provided languages. If you define a custom LANGUAGES setting, the list of bidirectional languages may contain language codes which are not enabled on a given site. LOCALE_PATHS Default: [] (Empty list) A list of directories where Django looks for translation files. See How Django discovers translations. Example: LOCALE_PATHS = [
'/home/www/project/common_files/locale',
'/var/local/translations/locale',
]
Django will look within each of these paths for the <locale_code>/LC_MESSAGES directories containing the actual translation files. LOGGING Default: A logging configuration dictionary. A data structure containing configuration information. The contents of this data structure will be passed as the argument to the configuration method described in LOGGING_CONFIG. Among other things, the default logging configuration passes HTTP 500 server errors to an email log handler when DEBUG is False. See also Configuring logging. You can see the default logging configuration by looking in django/utils/log.py. LOGGING_CONFIG Default: 'logging.config.dictConfig' A path to a callable that will be used to configure logging in the Django project. Points at an instance of Python’s dictConfig configuration method by default. If you set LOGGING_CONFIG to None, the logging configuration process will be skipped. MANAGERS Default: [] (Empty list) A list in the same format as ADMINS that specifies who should get broken link notifications when BrokenLinkEmailsMiddleware is enabled. MEDIA_ROOT Default: '' (Empty string) Absolute filesystem path to the directory that will hold user-uploaded files. Example: "/var/www/example.com/media/" See also MEDIA_URL. Warning MEDIA_ROOT and STATIC_ROOT must have different values. Before STATIC_ROOT was introduced, it was common to rely or fallback on MEDIA_ROOT to also serve static files; however, since this can have serious security implications, there is a validation check to prevent it. MEDIA_URL Default: '' (Empty string) URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES. Example: "http://media.example.com/" Warning There are security risks if you are accepting uploaded content from untrusted users! See the security guide’s topic on User-uploaded content for mitigation details. Warning MEDIA_URL and STATIC_URL must have different values. See MEDIA_ROOT for more details. Note If MEDIA_URL is a relative path, then it will be prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This makes it easier to serve a Django application in a subpath without adding an extra configuration to the settings. MIDDLEWARE Default: None A list of middleware to use. See Middleware. MIGRATION_MODULES Default: {} (Empty dictionary) A dictionary specifying the package where migration modules can be found on a per-app basis. The default value of this setting is an empty dictionary, but the default package name for migration modules is migrations. Example: {'blog': 'blog.db_migrations'}
In this case, migrations pertaining to the blog app will be contained in the blog.db_migrations package. If you provide the app_label argument, makemigrations will automatically create the package if it doesn’t already exist. When you supply None as a value for an app, Django will consider the app as an app without migrations regardless of an existing migrations submodule. This can be used, for example, in a test settings file to skip migrations while testing (tables will still be created for the apps’ models). To disable migrations for all apps during tests, you can set the MIGRATE to False instead. If MIGRATION_MODULES is used in your general project settings, remember to use the migrate --run-syncdb option if you want to create tables for the app. MONTH_DAY_FORMAT Default: 'F j' The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the month and day are displayed. For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given day displays the day and month. Different locales have different formats. For example, U.S. English would say “January 1,” whereas Spanish might say “1 Enero.” Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and YEAR_MONTH_FORMAT. NUMBER_GROUPING Default: 0 Number of digits grouped together on the integer part of a number. Common use is to display a thousand separator. If this setting is 0, then no grouping will be applied to the number. If this setting is greater than 0, then THOUSAND_SEPARATOR will be used as the separator between those groups. Some locales use non-uniform digit grouping, e.g. 10,00,00,000 in en_IN. For this case, you can provide a sequence with the number of digit group sizes to be applied. The first number defines the size of the group preceding the decimal delimiter, and each number that follows defines the size of preceding groups. If the sequence is terminated with -1, no further grouping is performed. If the sequence terminates with a 0, the last group size is used for the remainder of the number. Example tuple for en_IN: NUMBER_GROUPING = (3, 2, 0)
Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also DECIMAL_SEPARATOR, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR. PREPEND_WWW Default: False Whether to prepend the “www.” subdomain to URLs that don’t have it. This is only used if CommonMiddleware is installed (see Middleware). See also APPEND_SLASH. ROOT_URLCONF Default: Not defined A string representing the full Python import path to your root URLconf, for example "mydjangoapps.urls". Can be overridden on a per-request basis by setting the attribute urlconf on the incoming HttpRequest object. See How Django processes a request for details. SECRET_KEY Default: '' (Empty string) A secret key for a particular Django installation. This is used to provide cryptographic signing, and should be set to a unique, unpredictable value. django-admin startproject automatically adds a randomly-generated SECRET_KEY to each new project. Uses of the key shouldn’t assume that it’s text or bytes. Every use should go through force_str() or force_bytes() to convert it to the desired type. Django will refuse to start if SECRET_KEY is not set. Warning Keep this value secret. Running Django with a known SECRET_KEY defeats many of Django’s security protections, and can lead to privilege escalation and remote code execution vulnerabilities. The secret key is used for: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. If you rotate your secret key, all of the above will be invalidated. Secret keys are not used for passwords of users and key rotation will not affect them. Note The default settings.py file created by django-admin
startproject creates a unique SECRET_KEY for convenience. SECURE_CONTENT_TYPE_NOSNIFF Default: True If True, the SecurityMiddleware sets the X-Content-Type-Options: nosniff header on all responses that do not already have it. SECURE_CROSS_ORIGIN_OPENER_POLICY New in Django 4.0. Default: 'same-origin' Unless set to None, the SecurityMiddleware sets the Cross-Origin Opener Policy header on all responses that do not already have it to the value provided. SECURE_HSTS_INCLUDE_SUBDOMAINS Default: False If True, the SecurityMiddleware adds the includeSubDomains directive to the HTTP Strict Transport Security header. It has no effect unless SECURE_HSTS_SECONDS is set to a non-zero value. Warning Setting this incorrectly can irreversibly (for the value of SECURE_HSTS_SECONDS) break your site. Read the HTTP Strict Transport Security documentation first. SECURE_HSTS_PRELOAD Default: False If True, the SecurityMiddleware adds the preload directive to the HTTP Strict Transport Security header. It has no effect unless SECURE_HSTS_SECONDS is set to a non-zero value. SECURE_HSTS_SECONDS Default: 0 If set to a non-zero integer value, the SecurityMiddleware sets the HTTP Strict Transport Security header on all responses that do not already have it. Warning Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first. SECURE_PROXY_SSL_HEADER Default: None A tuple representing an HTTP header/value combination that signifies a request is secure. This controls the behavior of the request object’s is_secure() method. By default, is_secure() determines if a request is secure by confirming that a requested URL uses https://. This method is important for Django’s CSRF protection, and it may be used by your own code or third-party apps. If your Django app is behind a proxy, though, the proxy may be “swallowing” whether the original request uses HTTPS or not. If there is a non-HTTPS connection between the proxy and Django then is_secure() would always return False – even for requests that were made via HTTPS by the end user. In contrast, if there is an HTTPS connection between the proxy and Django then is_secure() would always return True – even for requests that were made originally via HTTP. In this situation, configure your proxy to set a custom HTTP header that tells Django whether the request came in via HTTPS, and set SECURE_PROXY_SSL_HEADER so that Django knows what header to look for. Set a tuple with two elements – the name of the header to look for and the required value. For example: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
This tells Django to trust the X-Forwarded-Proto header that comes from our proxy, and any time its value is 'https', then the request is guaranteed to be secure (i.e., it originally came in via HTTPS). You should only set this setting if you control your proxy or have some other guarantee that it sets/strips this header appropriately. Note that the header needs to be in the format as used by request.META – all caps and likely starting with HTTP_. (Remember, Django automatically adds 'HTTP_' to the start of x-header names before making the header available in request.META.) Warning Modifying this setting can compromise your site’s security. Ensure you fully understand your setup before changing it. Make sure ALL of the following are true before setting this (assuming the values from the example above): Your Django app is behind a proxy. Your proxy strips the X-Forwarded-Proto header from all incoming requests. In other words, if end users include that header in their requests, the proxy will discard it. Your proxy sets the X-Forwarded-Proto header and sends it to Django, but only for requests that originally come in via HTTPS. If any of those are not true, you should keep this setting set to None and find another way of determining HTTPS, perhaps via custom middleware. SECURE_REDIRECT_EXEMPT Default: [] (Empty list) If a URL path matches a regular expression in this list, the request will not be redirected to HTTPS. The SecurityMiddleware strips leading slashes from URL paths, so patterns shouldn’t include them, e.g. SECURE_REDIRECT_EXEMPT = [r'^no-ssl/$', …]. If SECURE_SSL_REDIRECT is False, this setting has no effect. SECURE_REFERRER_POLICY Default: 'same-origin' If configured, the SecurityMiddleware sets the Referrer Policy header on all responses that do not already have it to the value provided. SECURE_SSL_HOST Default: None If a string (e.g. secure.example.com), all SSL redirects will be directed to this host rather than the originally-requested host (e.g. www.example.com). If SECURE_SSL_REDIRECT is False, this setting has no effect. SECURE_SSL_REDIRECT Default: False If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT). Note If turning this to True causes infinite redirects, it probably means your site is running behind a proxy and can’t tell which requests are secure and which are not. Your proxy likely sets a header to indicate secure requests; you can correct the problem by finding out what that header is and configuring the SECURE_PROXY_SSL_HEADER setting accordingly. SERIALIZATION_MODULES Default: Not defined A dictionary of modules containing serializer definitions (provided as strings), keyed by a string identifier for that serialization type. For example, to define a YAML serializer, use: SERIALIZATION_MODULES = {'yaml': 'path.to.yaml_serializer'}
SERVER_EMAIL Default: 'root@localhost' The email address that error messages come from, such as those sent to ADMINS and MANAGERS. Why are my emails sent from a different address? This address is used only for error messages. It is not the address that regular email messages sent with send_mail() come from; for that, see DEFAULT_FROM_EMAIL. SHORT_DATE_FORMAT Default: 'm/d/Y' (e.g. 12/31/2003) An available formatting that can be used for displaying date fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT and SHORT_DATETIME_FORMAT. SHORT_DATETIME_FORMAT Default: 'm/d/Y P' (e.g. 12/31/2003 4 p.m.) An available formatting that can be used for displaying datetime fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT and SHORT_DATE_FORMAT. SIGNING_BACKEND Default: 'django.core.signing.TimestampSigner' The backend used for signing cookies and other data. See also the Cryptographic signing documentation. SILENCED_SYSTEM_CHECKS Default: [] (Empty list) A list of identifiers of messages generated by the system check framework (i.e. ["models.W001"]) that you wish to permanently acknowledge and ignore. Silenced checks will not be output to the console. See also the System check framework documentation. TEMPLATES Default: [] (Empty list) A list containing the settings for all template engines to be used with Django. Each item of the list is a dictionary containing the options for an individual engine. Here’s a setup that tells the Django template engine to load templates from the templates subdirectory inside each installed application: TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
},
]
The following options are available for all backends. BACKEND Default: Not defined The template backend to use. The built-in template backends are: 'django.template.backends.django.DjangoTemplates' 'django.template.backends.jinja2.Jinja2' You can use a template backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path (i.e. 'mypackage.whatever.Backend'). NAME Default: see below The alias for this particular template engine. It’s an identifier that allows selecting an engine for rendering. Aliases must be unique across all configured template engines. It defaults to the name of the module defining the engine class, i.e. the next to last piece of BACKEND, when it isn’t provided. For example if the backend is 'mypackage.whatever.Backend' then its default name is 'whatever'. DIRS Default: [] (Empty list) Directories where the engine should look for template source files, in search order. APP_DIRS Default: False Whether the engine should look for template source files inside installed applications. Note The default settings.py file created by django-admin
startproject sets 'APP_DIRS': True. OPTIONS Default: {} (Empty dict) Extra parameters to pass to the template backend. Available parameters vary depending on the template backend. See DjangoTemplates and Jinja2 for the options of the built-in backends. TEST_RUNNER Default: 'django.test.runner.DiscoverRunner' The name of the class to use for starting the test suite. See Using different testing frameworks. TEST_NON_SERIALIZED_APPS Default: [] (Empty list) In order to restore the database state between tests for TransactionTestCases and database backends without transactions, Django will serialize the contents of all apps when it starts the test run so it can then reload from that copy before running tests that need it. This slows down the startup time of the test runner; if you have apps that you know don’t need this feature, you can add their full names in here (e.g. 'django.contrib.contenttypes') to exclude them from this serialization process. THOUSAND_SEPARATOR Default: ',' (Comma) Default thousand separator used when formatting numbers. This setting is used only when USE_THOUSAND_SEPARATOR is True and NUMBER_GROUPING is greater than 0. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also NUMBER_GROUPING, DECIMAL_SEPARATOR and USE_THOUSAND_SEPARATOR. TIME_FORMAT Default: 'P' (e.g. 4 p.m.) The default formatting to use for displaying time fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATE_FORMAT and DATETIME_FORMAT. TIME_INPUT_FORMATS Default: [
'%H:%M:%S', # '14:30:59'
'%H:%M:%S.%f', # '14:30:59.000200'
'%H:%M', # '14:30'
]
A list of formats that will be accepted when inputting data on a time field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATE_INPUT_FORMATS and DATETIME_INPUT_FORMATS. TIME_ZONE Default: 'America/Chicago' A string representing the time zone for this installation. See the list of time zones. Note Since Django was first released with the TIME_ZONE set to 'America/Chicago', the global setting (used if nothing is defined in your project’s settings.py) remains 'America/Chicago' for backwards compatibility. New project templates default to 'UTC'. Note that this isn’t necessarily the time zone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time zone setting. When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. On Unix environments (where time.tzset() is implemented), Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in this time zone. However, Django won’t set the TZ environment variable if you’re using the manual configuration option as described in manually configuring settings. If Django doesn’t set the TZ environment variable, it’s up to you to ensure your processes are running in the correct environment. Note Django cannot reliably use alternate time zones in a Windows environment. If you’re running Django on Windows, TIME_ZONE must be set to match the system time zone. USE_DEPRECATED_PYTZ New in Django 4.0. Default: False A boolean that specifies whether to use pytz, rather than zoneinfo, as the default time zone implementation. Deprecated since version 4.0: This transitional setting is deprecated. Support for using pytz will be removed in Django 5.0. USE_I18N Default: True A boolean that specifies whether Django’s translation system should be enabled. This provides a way to turn it off, for performance. If this is set to False, Django will make some optimizations so as not to load the translation machinery. See also LANGUAGE_CODE, USE_L10N and USE_TZ. Note The default settings.py file created by django-admin
startproject includes USE_I18N = True for convenience. USE_L10N Default: True A boolean that specifies if localized formatting of data will be enabled by default or not. If this is set to True, e.g. Django will display numbers and dates using the format of the current locale. See also LANGUAGE_CODE, USE_I18N and USE_TZ. Changed in Django 4.0: In older versions, the default value is False. Deprecated since version 4.0: This setting is deprecated. Starting with Django 5.0, localized formatting of data will always be enabled. For example Django will display numbers and dates using the format of the current locale. USE_THOUSAND_SEPARATOR Default: False A boolean that specifies whether to display numbers using a thousand separator. When set to True and USE_L10N is also True, Django will format numbers using the NUMBER_GROUPING and THOUSAND_SEPARATOR settings. These settings may also be dictated by the locale, which takes precedence. See also DECIMAL_SEPARATOR, NUMBER_GROUPING and THOUSAND_SEPARATOR. USE_TZ Default: False Note In Django 5.0, the default value will change from False to True. A boolean that specifies if datetimes will be timezone-aware by default or not. If this is set to True, Django will use timezone-aware datetimes internally. When USE_TZ is False, Django will use naive datetimes in local time, except when parsing ISO 8601 formatted strings, where timezone information will always be retained if present. See also TIME_ZONE, USE_I18N and USE_L10N. Note The default settings.py file created by django-admin startproject includes USE_TZ = True for convenience. USE_X_FORWARDED_HOST Default: False A boolean that specifies whether to use the X-Forwarded-Host header in preference to the Host header. This should only be enabled if a proxy which sets this header is in use. This setting takes priority over USE_X_FORWARDED_PORT. Per RFC 7239#section-5.3, the X-Forwarded-Host header can include the port number, in which case you shouldn’t use USE_X_FORWARDED_PORT. USE_X_FORWARDED_PORT Default: False A boolean that specifies whether to use the X-Forwarded-Port header in preference to the SERVER_PORT META variable. This should only be enabled if a proxy which sets this header is in use. USE_X_FORWARDED_HOST takes priority over this setting. WSGI_APPLICATION Default: None The full Python path of the WSGI application object that Django’s built-in servers (e.g. runserver) will use. The django-admin
startproject management command will create a standard wsgi.py file with an application callable in it, and point this setting to that application. If not set, the return value of django.core.wsgi.get_wsgi_application() will be used. In this case, the behavior of runserver will be identical to previous Django versions. YEAR_MONTH_FORMAT Default: 'F Y' The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the year and month are displayed. For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given month displays the month and the year. Different locales have different formats. For example, U.S. English would say “January 2006,” whereas another locale might say “2006/January.” Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and MONTH_DAY_FORMAT. X_FRAME_OPTIONS Default: 'DENY' The default value for the X-Frame-Options header used by XFrameOptionsMiddleware. See the clickjacking protection documentation. Auth Settings for django.contrib.auth. AUTHENTICATION_BACKENDS Default: ['django.contrib.auth.backends.ModelBackend'] A list of authentication backend classes (as strings) to use when attempting to authenticate a user. See the authentication backends documentation for details. AUTH_USER_MODEL Default: 'auth.User' The model to use to represent a User. See Substituting a custom User model. Warning You cannot change the AUTH_USER_MODEL setting during the lifetime of a project (i.e. once you have made and migrated models that depend on it) without serious effort. It is intended to be set at the project start, and the model it refers to must be available in the first migration of the app that it lives in. See Substituting a custom User model for more details. LOGIN_REDIRECT_URL Default: '/accounts/profile/' The URL or named URL pattern where requests are redirected after login when the LoginView doesn’t get a next GET parameter. LOGIN_URL Default: '/accounts/login/' The URL or named URL pattern where requests are redirected for login when using the login_required() decorator, LoginRequiredMixin, or AccessMixin. LOGOUT_REDIRECT_URL Default: None The URL or named URL pattern where requests are redirected after logout if LogoutView doesn’t have a next_page attribute. If None, no redirect will be performed and the logout view will be rendered. PASSWORD_RESET_TIMEOUT Default: 259200 (3 days, in seconds) The number of seconds a password reset link is valid for. Used by the PasswordResetConfirmView. Note Reducing the value of this timeout doesn’t make any difference to the ability of an attacker to brute-force a password reset token. Tokens are designed to be safe from brute-forcing without any timeout. This timeout exists to protect against some unlikely attack scenarios, such as someone gaining access to email archives that may contain old, unused password reset tokens. PASSWORD_HASHERS See How Django stores passwords. Default: [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS Default: [] (Empty list) The list of validators that are used to check the strength of user’s passwords. See Password validation for more details. By default, no validation is performed and all passwords are accepted. Messages Settings for django.contrib.messages. MESSAGE_LEVEL Default: messages.INFO Sets the minimum message level that will be recorded by the messages framework. See message levels for more details. Important If you override MESSAGE_LEVEL in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.: from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG
If desired, you may specify the numeric values for the constants directly according to the values in the above constants table. MESSAGE_STORAGE Default: 'django.contrib.messages.storage.fallback.FallbackStorage' Controls where Django stores message data. Valid values are: 'django.contrib.messages.storage.fallback.FallbackStorage' 'django.contrib.messages.storage.session.SessionStorage' 'django.contrib.messages.storage.cookie.CookieStorage' See message storage backends for more details. The backends that use cookies – CookieStorage and FallbackStorage – use the value of SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE and SESSION_COOKIE_HTTPONLY when setting their cookies. MESSAGE_TAGS Default: {
messages.DEBUG: 'debug',
messages.INFO: 'info',
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
messages.ERROR: 'error',
}
This sets the mapping of message level to message tag, which is typically rendered as a CSS class in HTML. If you specify a value, it will extend the default. This means you only have to specify those values which you need to override. See Displaying messages above for more details. Important If you override MESSAGE_TAGS in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.: from django.contrib.messages import constants as message_constants
MESSAGE_TAGS = {message_constants.INFO: ''}
If desired, you may specify the numeric values for the constants directly according to the values in the above constants table. Sessions Settings for django.contrib.sessions. SESSION_CACHE_ALIAS Default: 'default' If you’re using cache-based session storage, this selects the cache to use. SESSION_COOKIE_AGE Default: 1209600 (2 weeks, in seconds) The age of session cookies, in seconds. SESSION_COOKIE_DOMAIN Default: None The domain to use for session cookies. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie. To use cross-domain cookies with CSRF_USE_SESSIONS, you must include a leading dot (e.g. ".example.com") to accommodate the CSRF middleware’s referer checking. Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies will be set to the old domain. This may result in them being unable to log in as long as these cookies persist. This setting also affects cookies set by django.contrib.messages. SESSION_COOKIE_HTTPONLY Default: True Whether to use HttpOnly flag on the session cookie. If this is set to True, client-side JavaScript will not be able to access the session cookie. HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265#section-4.1.2.6 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data. This makes it less trivial for an attacker to escalate a cross-site scripting vulnerability into full hijacking of a user’s session. There aren’t many good reasons for turning this off. Your code shouldn’t read session cookies from JavaScript. SESSION_COOKIE_NAME Default: 'sessionid' The name of the cookie to use for sessions. This can be whatever you want (as long as it’s different from the other cookie names in your application). SESSION_COOKIE_PATH Default: '/' The path set on the session cookie. This should either match the URL path of your Django installation or be parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own session cookie. SESSION_COOKIE_SAMESITE Default: 'Lax' The value of the SameSite flag on the session cookie. This flag prevents the cookie from being sent in cross-site requests thus preventing CSRF attacks and making some methods of stealing session cookie impossible. Possible values for the setting are:
'Strict': prevents the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link. For example, for a GitHub-like website this would mean that if a logged-in user follows a link to a private GitHub project posted on a corporate discussion forum or email, GitHub will not receive the session cookie and the user won’t be able to access the project. A bank website, however, most likely doesn’t want to allow any transactional pages to be linked from external sites so the 'Strict' flag would be appropriate.
'Lax' (default): provides a balance between security and usability for websites that want to maintain user’s logged-in session after the user arrives from an external link. In the GitHub scenario, the session cookie would be allowed when following a regular link from an external website and be blocked in CSRF-prone request methods (e.g. POST).
'None' (string): the session cookie will be sent with all same-site and cross-site requests.
False: disables the flag. Note Modern browsers provide a more secure default policy for the SameSite flag and will assume Lax for cookies without an explicit value set. SESSION_COOKIE_SECURE Default: False Whether to use a secure cookie for the session cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS connection. Leaving this setting off isn’t a good idea because an attacker could capture an unencrypted session cookie with a packet sniffer and use the cookie to hijack the user’s session. SESSION_ENGINE Default: 'django.contrib.sessions.backends.db' Controls where Django stores session data. Included engines are: 'django.contrib.sessions.backends.db' 'django.contrib.sessions.backends.file' 'django.contrib.sessions.backends.cache' 'django.contrib.sessions.backends.cached_db' 'django.contrib.sessions.backends.signed_cookies' See Configuring the session engine for more details. SESSION_EXPIRE_AT_BROWSER_CLOSE Default: False Whether to expire the session when the user closes their browser. See Browser-length sessions vs. persistent sessions. SESSION_FILE_PATH Default: None If you’re using file-based session storage, this sets the directory in which Django will store session data. When the default value (None) is used, Django will use the standard temporary directory for the system. SESSION_SAVE_EVERY_REQUEST Default: False Whether to save the session data on every request. If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted. Empty sessions won’t be created, even if this setting is active. SESSION_SERIALIZER Default: 'django.contrib.sessions.serializers.JSONSerializer' Full import path of a serializer class to use for serializing session data. Included serializers are: 'django.contrib.sessions.serializers.PickleSerializer' 'django.contrib.sessions.serializers.JSONSerializer' See Session serialization for details, including a warning regarding possible remote code execution when using PickleSerializer. Sites Settings for django.contrib.sites. SITE_ID Default: Not defined The ID, as an integer, of the current site in the django_site database table. This is used so that application data can hook into specific sites and a single database can manage content for multiple sites. Static Files Settings for django.contrib.staticfiles. STATIC_ROOT Default: None The absolute path to the directory where collectstatic will collect static files for deployment. Example: "/var/www/example.com/static/" If the staticfiles contrib app is enabled (as in the default project template), the collectstatic management command will collect static files into this directory. See the how-to on managing static files for more details about usage. Warning This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will be found by staticfiles’s finders, which by default, are 'static/' app sub-directories and any directories you include in STATICFILES_DIRS). STATIC_URL Default: None URL to use when referring to static files located in STATIC_ROOT. Example: "static/" or "http://static.example.com/" If not None, this will be used as the base path for asset definitions (the Media class) and the staticfiles app. It must end in a slash if set to a non-empty value. You may need to configure these files to be served in development and will definitely need to do so in production. Note If STATIC_URL is a relative path, then it will be prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This makes it easier to serve a Django application in a subpath without adding an extra configuration to the settings. STATICFILES_DIRS Default: [] (Empty list) This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view. This should be set to a list of strings that contain full paths to your additional files directory(ies) e.g.: STATICFILES_DIRS = [
"/home/special.polls.com/polls/static",
"/home/polls.com/polls/static",
"/opt/webfiles/common",
]
Note that these paths should use Unix-style forward slashes, even on Windows (e.g. "C:/Users/user/mysite/extra_static_content"). Prefixes (optional) In case you want to refer to files in one of the locations with an additional namespace, you can optionally provide a prefix as (prefix, path) tuples, e.g.: STATICFILES_DIRS = [
# ...
("downloads", "/opt/webfiles/stats"),
]
For example, assuming you have STATIC_URL set to 'static/', the collectstatic management command would collect the “stats” files in a 'downloads' subdirectory of STATIC_ROOT. This would allow you to refer to the local file '/opt/webfiles/stats/polls_20101022.tar.gz' with '/static/downloads/polls_20101022.tar.gz' in your templates, e.g.: <a href="{% static 'downloads/polls_20101022.tar.gz' %}">
STATICFILES_STORAGE Default: 'django.contrib.staticfiles.storage.StaticFilesStorage' The file storage engine to use when collecting static files with the collectstatic management command. A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib.staticfiles.storage.staticfiles_storage. For an example, see Serving static files from a cloud service or CDN. STATICFILES_FINDERS Default: [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
The list of finder backends that know how to find static files in various locations. The default will find files stored in the STATICFILES_DIRS setting (using django.contrib.staticfiles.finders.FileSystemFinder) and in a static subdirectory of each app (using django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple files with the same name are present, the first file that is found will be used. One finder is disabled by default: django.contrib.staticfiles.finders.DefaultStorageFinder. If added to your STATICFILES_FINDERS setting, it will look for static files in the default file storage as defined by the DEFAULT_FILE_STORAGE setting. Note When using the AppDirectoriesFinder finder, make sure your apps can be found by staticfiles by adding the app to the INSTALLED_APPS setting of your site. Static file finders are currently considered a private interface, and this interface is thus undocumented. Core Settings Topical Index Cache CACHES CACHE_MIDDLEWARE_ALIAS CACHE_MIDDLEWARE_KEY_PREFIX CACHE_MIDDLEWARE_SECONDS Database DATABASES DATABASE_ROUTERS DEFAULT_INDEX_TABLESPACE DEFAULT_TABLESPACE Debugging DEBUG DEBUG_PROPAGATE_EXCEPTIONS Email ADMINS DEFAULT_CHARSET DEFAULT_FROM_EMAIL EMAIL_BACKEND EMAIL_FILE_PATH EMAIL_HOST EMAIL_HOST_PASSWORD EMAIL_HOST_USER EMAIL_PORT EMAIL_SSL_CERTFILE EMAIL_SSL_KEYFILE EMAIL_SUBJECT_PREFIX EMAIL_TIMEOUT EMAIL_USE_LOCALTIME EMAIL_USE_TLS MANAGERS SERVER_EMAIL Error reporting DEFAULT_EXCEPTION_REPORTER DEFAULT_EXCEPTION_REPORTER_FILTER IGNORABLE_404_URLS MANAGERS SILENCED_SYSTEM_CHECKS File uploads DEFAULT_FILE_STORAGE FILE_UPLOAD_HANDLERS FILE_UPLOAD_MAX_MEMORY_SIZE FILE_UPLOAD_PERMISSIONS FILE_UPLOAD_TEMP_DIR MEDIA_ROOT MEDIA_URL Forms FORM_RENDERER Globalization (i18n/l10n) DATE_FORMAT DATE_INPUT_FORMATS DATETIME_FORMAT DATETIME_INPUT_FORMATS DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK FORMAT_MODULE_PATH LANGUAGE_CODE LANGUAGE_COOKIE_AGE LANGUAGE_COOKIE_DOMAIN LANGUAGE_COOKIE_HTTPONLY LANGUAGE_COOKIE_NAME LANGUAGE_COOKIE_PATH LANGUAGE_COOKIE_SAMESITE LANGUAGE_COOKIE_SECURE LANGUAGES LANGUAGES_BIDI LOCALE_PATHS MONTH_DAY_FORMAT NUMBER_GROUPING SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT THOUSAND_SEPARATOR TIME_FORMAT TIME_INPUT_FORMATS TIME_ZONE USE_I18N USE_L10N USE_THOUSAND_SEPARATOR USE_TZ YEAR_MONTH_FORMAT HTTP DATA_UPLOAD_MAX_MEMORY_SIZE DATA_UPLOAD_MAX_NUMBER_FIELDS DEFAULT_CHARSET DISALLOWED_USER_AGENTS FORCE_SCRIPT_NAME INTERNAL_IPS MIDDLEWARE Security SECURE_CONTENT_TYPE_NOSNIFF SECURE_CROSS_ORIGIN_OPENER_POLICY SECURE_HSTS_INCLUDE_SUBDOMAINS SECURE_HSTS_PRELOAD SECURE_HSTS_SECONDS SECURE_PROXY_SSL_HEADER SECURE_REDIRECT_EXEMPT SECURE_REFERRER_POLICY SECURE_SSL_HOST SECURE_SSL_REDIRECT SIGNING_BACKEND USE_X_FORWARDED_HOST USE_X_FORWARDED_PORT WSGI_APPLICATION Logging LOGGING LOGGING_CONFIG Models ABSOLUTE_URL_OVERRIDES FIXTURE_DIRS INSTALLED_APPS Security Cross Site Request Forgery Protection CSRF_COOKIE_DOMAIN CSRF_COOKIE_NAME CSRF_COOKIE_PATH CSRF_COOKIE_SAMESITE CSRF_COOKIE_SECURE CSRF_FAILURE_VIEW CSRF_HEADER_NAME CSRF_TRUSTED_ORIGINS CSRF_USE_SESSIONS SECRET_KEY X_FRAME_OPTIONS Serialization DEFAULT_CHARSET SERIALIZATION_MODULES Templates TEMPLATES Testing Database: TEST
TEST_NON_SERIALIZED_APPS TEST_RUNNER URLs APPEND_SLASH PREPEND_WWW ROOT_URLCONF | |
doc_29284 | See Migration guide for more details. tf.compat.v1.raw_ops.ResourceGatherNd
tf.raw_ops.ResourceGatherNd(
resource, indices, dtype, name=None
)
Args
resource A Tensor of type resource.
indices A Tensor. Must be one of the following types: int32, int64.
dtype A tf.DType.
name A name for the operation (optional).
Returns A Tensor of type dtype. | |
doc_29285 |
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y. | |
doc_29286 |
Applies a softmax function. Softmax is defined as: Softmax(xi)=exp(xi)∑jexp(xj)\text{Softmax}(x_{i}) = \frac{exp(x_i)}{\sum_j exp(x_j)} where i,ji, j run over sparse tensor indices and unspecified entries are ignores. This is equivalent to defining unspecified entries as negative infinity so that exp(xk)=0exp(x_k) = 0 when the entry with index kk has not specified. It is applied to all slices along dim, and will re-scale them so that the elements lie in the range [0, 1] and sum to 1. Parameters
input (Tensor) – input
dim (int) – A dimension along which softmax will be computed.
dtype (torch.dtype, optional) – the desired data type of returned tensor. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. Default: None | |
doc_29287 | tkinter.WRITABLE
tkinter.EXCEPTION
Constants used in the mask arguments. | |
doc_29288 | tf.saved_model.LoadOptions(
experimental_io_device=None
)
This function may be used in the options argument in functions that load a SavedModel (tf.saved_model.load, tf.keras.models.load_model).
Args
experimental_io_device string. Applies in a distributed setting. Tensorflow device to use to access the filesystem. If None (default) then for each variable the filesystem is accessed from the CPU:0 device of the host where that variable is assigned. If specified, the filesystem is instead accessed from that device for all variables. This is for example useful if you want to load from a local directory, such as "/tmp" when running in a distributed setting. In that case pass a device for the host where the "/tmp" directory is accessible.
Class Variables
experimental_io_device | |
doc_29289 |
Compute decision function of X for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples, which corresponds to the raw values predicted from the trees of the ensemble . The classes corresponds to that in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes. | |
doc_29290 | The following exception is defined:
exception webbrowser.Error
Exception raised when a browser control error occurs.
The following functions are defined:
webbrowser.open(url, new=0, autoraise=True)
Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable). Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable. Raises an auditing event webbrowser.open with argument url.
webbrowser.open_new(url)
Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window.
webbrowser.open_new_tab(url)
Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new().
webbrowser.get(using=None)
Return a controller object for the browser type using. If using is None, return a controller for a default browser appropriate to the caller’s environment.
webbrowser.register(name, constructor, instance=None, *, preferred=False)
Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None. Setting preferred to True makes this browser a preferred result for a get() call with no argument. Otherwise, this entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare. Changed in version 3.7: preferred keyword-only parameter was added.
A number of browser types are predefined. This table gives the type names that may be passed to the get() function and the corresponding instantiations for the controller classes, all defined in this module.
Type Name Class Name Notes
'mozilla' Mozilla('mozilla')
'firefox' Mozilla('mozilla')
'netscape' Mozilla('netscape')
'galeon' Galeon('galeon')
'epiphany' Galeon('epiphany')
'skipstone' BackgroundBrowser('skipstone')
'kfmclient' Konqueror() (1)
'konqueror' Konqueror() (1)
'kfm' Konqueror() (1)
'mosaic' BackgroundBrowser('mosaic')
'opera' Opera()
'grail' Grail()
'links' GenericBrowser('links')
'elinks' Elinks('elinks')
'lynx' GenericBrowser('lynx')
'w3m' GenericBrowser('w3m')
'windows-default' WindowsDefault (2)
'macosx' MacOSX('default') (3)
'safari' MacOSX('safari') (3)
'google-chrome' Chrome('google-chrome')
'chrome' Chrome('chrome')
'chromium' Chromium('chromium')
'chromium-browser' Chromium('chromium-browser') Notes: “Konqueror” is the file manager for the KDE desktop environment for Unix, and only makes sense to use if KDE is running. Some way of reliably detecting KDE would be nice; the KDEDIR variable is not sufficient. Note also that the name “kfm” is used even when using the konqueror command with KDE 2 — the implementation selects the best strategy for running Konqueror. Only on Windows platforms. Only on Mac OS X platform. New in version 3.3: Support for Chrome/Chromium has been added. Here are some simple examples: url = 'http://docs.python.org/'
# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
Browser Controller Objects Browser controllers provide these methods which parallel three of the module-level convenience functions:
controller.open(url, new=0, autoraise=True)
Display url using the browser handled by this controller. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible.
controller.open_new(url)
Open url in a new window of the browser handled by this controller, if possible, otherwise, open url in the only browser window. Alias open_new().
controller.open_new_tab(url)
Open url in a new page (“tab”) of the browser handled by this controller, if possible, otherwise equivalent to open_new().
Footnotes
1
Executables named here without a full path will be searched in the directories given in the PATH environment variable. | |
doc_29291 | See InlineModelAdmin objects below as well as ModelAdmin.get_formsets_with_inlines(). | |
doc_29292 | tf.image.decode_bmp Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_bmp, tf.compat.v1.io.decode_bmp
tf.io.decode_bmp(
contents, channels=0, name=None
)
The attr channels indicates the desired number of color channels for the decoded image. Accepted values are: 0: Use the number of channels in the BMP-encoded image. 3: output an RGB image. 4: output an RGBA image.
Args
contents A Tensor of type string. 0-D. The BMP-encoded image.
channels An optional int. Defaults to 0.
name A name for the operation (optional).
Returns A Tensor of type uint8. | |
doc_29293 |
Top level Artist, which holds all plot elements. Many methods are implemented in FigureBase. SubFigure
A logical figure inside a figure, usually added to a figure (or parent SubFigure) with Figure.add_subfigure or Figure.subfigures methods (provisional API v3.4). SubplotParams
Control the default spacing between subplots. classmatplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, *, layout=None, **kwargs)[source]
The top level container for all the plot elements. The Figure instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance. The events you can connect to are 'dpi_changed', and the callback will be called with func(fig) where fig is the Figure instance. Attributes
patch
The Rectangle instance representing the figure background patch. suppressComposite
For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is a boolean, this will override the renderer. Parameters
figsize2-tuple of floats, default: rcParams["figure.figsize"] (default: [6.4, 4.8])
Figure dimension (width, height) in inches.
dpifloat, default: rcParams["figure.dpi"] (default: 100.0)
Dots per inch.
facecolordefault: rcParams["figure.facecolor"] (default: 'white')
The figure patch facecolor.
edgecolordefault: rcParams["figure.edgecolor"] (default: 'white')
The figure patch edge color.
linewidthfloat
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
frameonbool, default: rcParams["figure.frameon"] (default: True)
If False, suppress drawing the figure background patch.
subplotparsSubplotParams
Subplot parameters. If not given, the default subplot parameters rcParams["figure.subplot.*"] are used.
tight_layoutbool or dict, default: rcParams["figure.autolayout"] (default: False)
Whether to use the tight layout mechanism. See set_tight_layout. Discouraged The use of this parameter is discouraged. Please use layout='tight' instead for the common case of tight_layout=True and use set_tight_layout otherwise.
constrained_layoutbool, default: rcParams["figure.constrained_layout.use"] (default: False)
This is equal to layout='constrained'. Discouraged The use of this parameter is discouraged. Please use layout='constrained' instead.
layout{'constrained', 'tight'}, optional
The layout mechanism for positioning of plot elements. Supported values:
'constrained': The constrained layout solver usually gives the best layout results and is thus recommended. However, it is computationally expensive and can be slow for complex figures with many elements. See Constrained Layout Guide for examples. 'tight': Use the tight layout mechanism. This is a relatively simple algorithm, that adjusts the subplot parameters so that decorations like tick labels, axis labels and titles have enough space. See Figure.set_tight_layout for further details. If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults rcParams["figure.autolayout"] (default: False) and rcParams["figure.constrained_layout.use"] (default: False). Other Parameters
**kwargsFigure properties, optional
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
canvas FigureCanvas
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
constrained_layout bool or dict or None
constrained_layout_pads float, default: rcParams["figure.constrained_layout.w_pad"] (default: 0.04167)
dpi float
edgecolor color
facecolor color
figheight float
figure Figure
figwidth float
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
size_inches (float, float) or float
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
tight_layout bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
transform Transform
url str
visible bool
zorder float add_artist(artist, clip=False)[source]
Add an Artist to the figure. Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead. Parameters
artistArtist
The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure.
clipbool, default: False
Whether the added artist should be clipped by the figure patch. Returns
Artist
The added artist.
add_axes(*args, **kwargs)[source]
Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
rectsequence of float
The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
Axes, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_subplot
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_axobserver(func)[source]
Whenever the Axes state change, func(self) will be called.
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
add_gridspec(nrows=1, ncols=1, **kwargs)[source]
Return a GridSpec that has this figure as a parent. This allows complex layout of Axes in the figure. Parameters
nrowsint, default: 1
Number of rows in grid.
ncolsint, default: 1
Number or columns in grid. Returns
GridSpec
Other Parameters
**kwargs
Keyword arguments are passed to GridSpec. See also matplotlib.pyplot.subplots
Examples Adding a subplot that spans two rows: fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subfigure(subplotspec, **kwargs)[source]
Add a SubFigure to the figure as part of a subplot arrangement. Parameters
subplotspecgridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed. Returns
figure.SubFigure
Other Parameters
**kwargs
Are passed to the SubFigure object. See also Figure.subfigures
add_subplot(*args, **kwargs)[source]
Add an Axes to the figure as part of a subplot arrangement. Call signatures: add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)
The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec. In rare circumstances, add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
axes.SubplotBase, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned Axes is then a subplot subclass of the base class. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_axes
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Examples fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
fig.add_subplot(232, frameon=False) # subplot with no frame
fig.add_subplot(233, projection='polar') # polar subplot
fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red") # red subplot
ax1.remove() # delete ax1 from the figure
fig.add_subplot(ax1) # add ax1 back to the figure
align_labels(axs=None)[source]
Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the labels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_ylabels
align_xlabels(axs=None)[source]
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters
axslist of Axes
Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(axs=None)[source]
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the ylabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with large yticks labels: fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source]
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters
bottomfloat, default: 0.2
The bottom of the subplots for subplots_adjust.
rotationfloat, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha{'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which{'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate.
propertyaxes
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list. Do not modify the list itself. Instead, use add_axes, add_subplot or delaxes to add or remove an Axes. Note: The Figure.axes property and get_axes method are equivalent.
clear(keep_observers=False)[source]
Clear the figure -- synonym for clf.
clf(keep_observers=False)[source]
Clear the figure. Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]
Add a colorbar to a plot. Parameters
mappable
The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image. Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
caxAxes, optional
Axes into which the colorbar will be drawn.
axAxes, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
use_gridspecbool, optional
If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module. Returns
colorbarColorbar
Notes Additional keyword arguments are of two kinds: axes properties: locationNone or {'left', 'right', 'top', 'bottom'}
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15
Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0
Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20
Ratio of long to short dimensions. padfloat, default: 0.05 if vertical, 0.15 if horizontal
Fraction of original axes between colorbar and new image axes. anchor(float, float), optional
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal. colorbar properties:
Property Description
extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks None or list of ticks or Locator If None, ticks are determined automatically from the input.
format None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead.
drawedges bool Whether to draw lines at color boundaries.
label str The label on the colorbar's long axis. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property Description
boundaries None or a sequence
values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. If mappable is a ContourSet, its extend kwarg is included automatically. The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments: cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
contains(mouseevent)[source]
Test whether the mouse event occurred on the figure. Returns
bool, {}
convert_xunits(x)[source]
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_yunits(y)[source]
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.
delaxes(ax)[source]
Remove the Axes ax from the figure; update the current Axes.
propertydpi
The resolution in dots per inch.
draw(renderer)[source]
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). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
draw_artist(a)[source]
Draw Artist a only. This method can only be used after an initial draw of the figure, because that creates and caches the renderer needed here.
draw_without_rendering()[source]
Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text).
execute_constrained_layout(renderer=None)[source]
Use layoutgrid to determine pos positions within Axes. See also set_constrained_layout_pads. Returns
layoutgridprivate debugging object
figimage(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs)[source]
Add a non-resampled image to the figure. The image is attached to the lower or upper left corner depending on origin. Parameters
X
The image data. This is an array of one of the following shapes: MxN: luminance (grayscale) values MxNx3: RGB values MxNx4: RGBA values
xo, yoint
The x/y image offset in pixels.
alphaNone or float
The alpha blending value.
normmatplotlib.colors.Normalize
A Normalize instance to map the luminance to the interval [0, 1].
cmapstr or matplotlib.colors.Colormap, default: rcParams["image.cmap"] (default: 'viridis')
The colormap to use.
vmin, vmaxfloat
If norm is not given, these values set the data limits for the colormap.
origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')
Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes.
resizebool
If True, resize the figure to match the given image size. Returns
matplotlib.image.FigureImage
Other Parameters
**kwargs
Additional kwargs are Artist kwargs passed on to FigureImage. Notes figimage complements the Axes image (imshow) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an Axes with extent [0, 0, 1, 1]. Examples f = plt.figure()
nx = int(f.get_figwidth() * f.dpi)
ny = int(f.get_figheight() * f.dpi)
data = np.random.random((ny, nx))
f.figimage(data)
plt.show()
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
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 get_cursor_data
propertyframeon
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
gca(**kwargs)[source]
Get the current Axes. If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.) The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_axes()[source]
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list. Do not modify the list itself. Instead, use add_axes, add_subplot or delaxes to add or remove an Axes. Note: The Figure.axes property and get_axes method are equivalent.
get_children()[source]
Get a list of artists contained in the figure.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_constrained_layout()[source]
Return whether constrained layout is being used. See Constrained Layout Guide.
get_constrained_layout_pads(relative=False)[source]
Get padding for constrained_layout. Returns a list of w_pad, h_pad in inches and wspace and hspace as fractions of the subplot. See Constrained Layout Guide. Parameters
relativebool
If True, then convert from inches to figure relative.
get_cursor_data(event)[source]
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. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_default_bbox_extra_artists()[source]
get_dpi()[source]
Return the resolution in dots per inch as a float.
get_edgecolor()[source]
Get the edge color of the Figure rectangle.
get_facecolor()[source]
Get the face color of the Figure rectangle.
get_figheight()[source]
Return the figure height in inches.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_figwidth()[source]
Return the figure width in inches.
get_frameon()[source]
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
get_gid()[source]
Return the group id.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_label()[source]
Return the label used for this artist in the legend.
get_linewidth()[source]
Get the line width of the Figure rectangle.
get_path_effects()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_size_inches()[source]
Return the current size of the figure in inches. Returns
ndarray
The size (width, height) of the figure in inches. See also matplotlib.figure.Figure.set_size_inches
matplotlib.figure.Figure.get_figwidth
matplotlib.figure.Figure.get_figheight
Notes The size in pixels can be obtained by multiplying with Figure.dpi.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tight_layout()[source]
Return whether tight_layout is called when drawing.
get_tightbbox(renderer, bbox_extra_artists=None)[source]
Return a (tight) bounding box of the figure in inches. Note that FigureBase differs from all other artists, which return their Bbox in pixels. Artists that have artist.set_in_layout(False) are not included in the bbox. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())
bbox_extra_artistslist of Artist or None
List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box. Returns
BboxBase
containing the bounding box (in figure inches).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_url()[source]
Return the url.
get_visible()[source]
Return the visibility.
get_window_extent(*args, **kwargs)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)[source]
Blocking call to interact with a figure. Wait until the user clicks n times on the figure, and return the coordinates of each click in a list. There are three possible interactions: Add a point. Remove the most recently added point. Stop the interaction and return the points added so far. The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop. Parameters
nint, default: 1
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
timeoutfloat, default: 30 seconds
Number of seconds to wait before timing out. If zero or negative will never timeout.
show_clicksbool, default: True
If True, show a red cross at the location of each click.
mouse_addMouseButton or None, default: MouseButton.LEFT
Mouse button used to add points.
mouse_popMouseButton or None, default: MouseButton.RIGHT
Mouse button used to remove the most recently added point.
mouse_stopMouseButton or None, default: MouseButton.MIDDLE
Mouse button used to stop input. Returns
list of tuples
A list of the clicked (x, y) coordinates. Notes The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
legend(*args, **kwargs)[source]
Place a legend on the figure. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label')
fig.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.legend(handles=[line1, line2])
4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example: fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.legend(['the blues', 'the reds'])
Parameters
handleslist of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns
Legend
Other Parameters
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)
The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolint, default: 1
The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
frameonbool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)
Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
bbox_transformNone or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None
The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)
The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)
The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)
The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)
The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)
The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)
The spacing between columns, in font-size units.
handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Axes.legend
Notes Some artists are not supported by this function. See Legend guide for details.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
savefig(fname, *, transparent=None, **kwargs)[source]
Save the current figure. Call signature: savefig(fname, *, dpi='figure', format=None, metadata=None,
bbox_inches=None, pad_inches=0.1,
facecolor='auto', edgecolor='auto',
backend=None, **kwargs
)
The available output formats depend on the backend being used. Parameters
fnamestr or path-like or binary file-like
A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages. If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended. If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"] (default: 'png') and the appropriate extension is appended to fname. Other Parameters
dpifloat or 'figure', default: rcParams["savefig.dpi"] (default: 'figure')
The resolution in dots per inch. If 'figure', use the figure's dpi value.
formatstr
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
metadatadict, optional
Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend: 'png' with Agg backend: See the parameter metadata of print_png. 'pdf' with pdf backend: See the parameter metadata of PdfPages. 'svg' with svg backend: See the parameter metadata of print_svg. 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
bbox_inchesstr or Bbox, default: rcParams["savefig.bbox"] (default: None)
Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.
pad_inchesfloat, default: rcParams["savefig.pad_inches"] (default: 0.1)
Amount of padding around the figure when bbox_inches is 'tight'.
facecolorcolor or 'auto', default: rcParams["savefig.facecolor"] (default: 'auto')
The facecolor of the figure. If 'auto', use the current figure facecolor.
edgecolorcolor or 'auto', default: rcParams["savefig.edgecolor"] (default: 'auto')
The edgecolor of the figure. If 'auto', use the current figure edgecolor.
backendstr, optional
Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See The builtin backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".
orientation{'landscape', 'portrait'}
Currently only supported by the postscript backend.
papertypestr
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.
transparentbool
If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used). The transparency of these patches will be restored to their original values upon exit of this function. This is useful, for example, for displaying a plot on top of a colored background on a web page.
bbox_extra_artistslist of Artist, optional
A list of extra artists that will be considered when the tight bbox is calculated.
pil_kwargsdict, optional
Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.
sca(a)[source]
Set the current Axes to be a and return a.
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, canvas=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, constrained_layout=<UNSET>, constrained_layout_pads=<UNSET>, dpi=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, figheight=<UNSET>, figwidth=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, size_inches=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, tight_layout=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
canvas FigureCanvas
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
constrained_layout bool or dict or None
constrained_layout_pads float, default: rcParams["figure.constrained_layout.w_pad"] (default: 0.04167)
dpi float
edgecolor color
facecolor color
figheight float
figure Figure
figwidth float
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
size_inches (float, float) or float
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
tight_layout bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
transform Transform
url str
visible bool
zorder float
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphascalar or None
alpha must be within the 0-1 range, inclusive.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_canvas(canvas)[source]
Set the canvas that contains the figure Parameters
canvasFigureCanvas
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_constrained_layout(constrained)[source]
Set whether constrained_layout is used upon drawing. If None, rcParams["figure.constrained_layout.use"] (default: False) value will be used. When providing a dict containing the keys w_pad, h_pad the default constrained_layout paddings will be overridden. These pads are in inches and default to 3.0/72.0. w_pad is the width padding and h_pad is the height padding. See Constrained Layout Guide. Parameters
constrainedbool or dict or None
set_constrained_layout_pads(*, w_pad=None, h_pad=None, wspace=None, hspace=None)[source]
Set padding for constrained_layout. Tip: The parameters can be passed from a dictionary by using fig.set_constrained_layout(**pad_dict). See Constrained Layout Guide. Parameters
w_padfloat, default: rcParams["figure.constrained_layout.w_pad"] (default: 0.04167)
Width padding in inches. This is the pad around Axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches
h_padfloat, default: rcParams["figure.constrained_layout.h_pad"] (default: 0.04167)
Height padding in inches. Defaults to 3 pts.
wspacefloat, default: rcParams["figure.constrained_layout.wspace"] (default: 0.02)
Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace.
hspacefloat, default: rcParams["figure.constrained_layout.hspace"] (default: 0.02)
Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace.
set_dpi(val)[source]
Set the resolution of the figure in dots-per-inch. Parameters
valfloat
set_edgecolor(color)[source]
Set the edge color of the Figure rectangle. Parameters
colorcolor
set_facecolor(color)[source]
Set the face color of the Figure rectangle. Parameters
colorcolor
set_figheight(val, forward=True)[source]
Set the height of the figure in inches. Parameters
valfloat
forwardbool
See set_size_inches. See also matplotlib.figure.Figure.set_figwidth
matplotlib.figure.Figure.set_size_inches
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_figwidth(val, forward=True)[source]
Set the width of the figure in inches. Parameters
valfloat
forwardbool
See set_size_inches. See also matplotlib.figure.Figure.set_figheight
matplotlib.figure.Figure.set_size_inches
set_frameon(b)[source]
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters
bbool
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linewidth(linewidth)[source]
Set the line width of the Figure rectangle. Parameters
linewidthnumber
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_size_inches(w, h=None, forward=True)[source]
Set the figure size in inches. Call signatures: fig.set_size_inches(w, h) # OR
fig.set_size_inches((w, h))
Parameters
w(float, float) or float
Width and height in inches (if height not specified as a separate argument) or width.
hfloat
Height in inches.
forwardbool, default: True
If True, the canvas size is automatically updated, e.g., you can resize the figure window from the shell. See also matplotlib.figure.Figure.get_size_inches
matplotlib.figure.Figure.set_figwidth
matplotlib.figure.Figure.set_figheight
Notes To transform from pixels to inches divide by Figure.dpi.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_tight_layout(tight)[source]
Set whether and how tight_layout is called when drawing. Parameters
tightbool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
If a bool, sets whether to call tight_layout upon drawing. If None, use rcParams["figure.autolayout"] (default: False) instead. If a dict, pass it as kwargs to tight_layout, overriding the default paddings.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
show(warn=True)[source]
If using a GUI backend with pyplot, display the figure window. If the figure was not created using figure, it will lack a FigureManagerBase, and this method will raise an AttributeError. Warning This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop. Proper use cases for Figure.show include running this from a GUI application or an IPython shell. If you're running a pure python shell or executing a non-GUI python script, you should use matplotlib.pyplot.show instead, which takes care of managing the event loop for you. Parameters
warnbool, default: True
If True and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend.
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)[source]
Add a subfigure to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subfigure grid.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of subfigures.
wspace, hspacefloat, default: None
The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from a figure or rcParams when necessary.
width_ratiosarray-like of length ncols, optional
Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width.
height_ratiosarray-like of length nrows, optional
Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height.
subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.')[source]
Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters
mosaiclist of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 Axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form '''
AAE
C.E
'''
where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;: 'AB;CC'
The string notation allows only single character Axes labels and does not support nesting but is very terse.
sharex, shareybool, default: False
If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent.
subplot_kwdict, optional
Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
empty_sentinelobject, optional
Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. Returns
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source]
Add a set of subplots to this figure. This utility wrapper makes it convenient to create common layouts of subplots in a single call. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subplot grid.
sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of x-axis (sharex) or y-axis (sharey): True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional
Dict with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns
Axes or array of Axes
Either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. See also pyplot.subplots
Figure.add_subplot
pyplot.subplot
Examples # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat, optional
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat, optional
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat, optional
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat, optional
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat, optional
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat, optional
The height of the padding between subplots, as a fraction of the average Axes height.
suptitle(t, **kwargs)[source]
Add a centered suptitle to the figure. Parameters
tstr
The suptitle text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the suptitle. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supxlabel(t, **kwargs)[source]
Add a centered supxlabel to the figure. Parameters
tstr
The supxlabel text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.01
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: bottom
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supxlabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supylabel(t, **kwargs)[source]
Add a centered supylabel to the figure. Parameters
tstr
The supylabel text.
xfloat, default: 0.02
The x location of the text in figure coordinates.
yfloat, default: 0.5
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: left
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: center
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supylabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
text(x, y, s, fontdict=None, **kwargs)[source]
Add text to figure. Parameters
x, yfloat
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
sstr
The text string.
fontdictdict, optional
A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict. Returns
Text
Other Parameters
**kwargsText properties
Other miscellaneous text parameters.
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box unknown
clip_on unknown
clip_path unknown
color or c color
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path
fontsize or size float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
math_fontfamily str
multialignment or ma {'left', 'right', 'center'}
parse_math bool
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool
rotation float or {'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
transform_rotates_text bool
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float See also Axes.text
pyplot.text
tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]
Adjust the padding between and around subplots. To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set a.set_in_layout(False) for that artist. Parameters
padfloat, default: 1.08
Padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad, w_padfloat, default: pad
Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
recttuple (left, bottom, right, top), default: (0, 0, 1, 1)
A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. See also Figure.set_tight_layout
pyplot.tight_layout
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
waitforbuttonpress(timeout=- 1)[source]
Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.
zorder=0
classmatplotlib.figure.FigureBase(**kwargs)[source]
Base class for figure.Figure and figure.SubFigure containing the methods that add artists to the figure or subfigure, create Axes, etc. add_artist(artist, clip=False)[source]
Add an Artist to the figure. Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead. Parameters
artistArtist
The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure.
clipbool, default: False
Whether the added artist should be clipped by the figure patch. Returns
Artist
The added artist.
add_axes(*args, **kwargs)[source]
Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
rectsequence of float
The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
Axes, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_subplot
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
add_gridspec(nrows=1, ncols=1, **kwargs)[source]
Return a GridSpec that has this figure as a parent. This allows complex layout of Axes in the figure. Parameters
nrowsint, default: 1
Number of rows in grid.
ncolsint, default: 1
Number or columns in grid. Returns
GridSpec
Other Parameters
**kwargs
Keyword arguments are passed to GridSpec. See also matplotlib.pyplot.subplots
Examples Adding a subplot that spans two rows: fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subfigure(subplotspec, **kwargs)[source]
Add a SubFigure to the figure as part of a subplot arrangement. Parameters
subplotspecgridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed. Returns
figure.SubFigure
Other Parameters
**kwargs
Are passed to the SubFigure object. See also Figure.subfigures
add_subplot(*args, **kwargs)[source]
Add an Axes to the figure as part of a subplot arrangement. Call signatures: add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)
The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec. In rare circumstances, add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
axes.SubplotBase, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned Axes is then a subplot subclass of the base class. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_axes
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Examples fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
fig.add_subplot(232, frameon=False) # subplot with no frame
fig.add_subplot(233, projection='polar') # polar subplot
fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red") # red subplot
ax1.remove() # delete ax1 from the figure
fig.add_subplot(ax1) # add ax1 back to the figure
align_labels(axs=None)[source]
Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the labels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_ylabels
align_xlabels(axs=None)[source]
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters
axslist of Axes
Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(axs=None)[source]
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the ylabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with large yticks labels: fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source]
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters
bottomfloat, default: 0.2
The bottom of the subplots for subplots_adjust.
rotationfloat, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha{'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which{'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate.
propertyaxes
The Axes instance the artist resides in, or None.
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]
Add a colorbar to a plot. Parameters
mappable
The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image. Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
caxAxes, optional
Axes into which the colorbar will be drawn.
axAxes, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
use_gridspecbool, optional
If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module. Returns
colorbarColorbar
Notes Additional keyword arguments are of two kinds: axes properties: locationNone or {'left', 'right', 'top', 'bottom'}
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15
Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0
Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20
Ratio of long to short dimensions. padfloat, default: 0.05 if vertical, 0.15 if horizontal
Fraction of original axes between colorbar and new image axes. anchor(float, float), optional
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal. colorbar properties:
Property Description
extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks None or list of ticks or Locator If None, ticks are determined automatically from the input.
format None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead.
drawedges bool Whether to draw lines at color boundaries.
label str The label on the colorbar's long axis. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property Description
boundaries None or a sequence
values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. If mappable is a ContourSet, its extend kwarg is included automatically. The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments: cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
contains(mouseevent)[source]
Test whether the mouse event occurred on the figure. Returns
bool, {}
convert_xunits(x)[source]
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_yunits(y)[source]
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.
delaxes(ax)[source]
Remove the Axes ax from the figure; update the current Axes.
draw(renderer)[source]
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). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
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 get_cursor_data
propertyframeon
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
gca(**kwargs)[source]
Get the current Axes. If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.) The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_children()[source]
Get a list of artists contained in the figure.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cursor_data(event)[source]
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. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_default_bbox_extra_artists()[source]
get_edgecolor()[source]
Get the edge color of the Figure rectangle.
get_facecolor()[source]
Get the face color of the Figure rectangle.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_frameon()[source]
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
get_gid()[source]
Return the group id.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_label()[source]
Return the label used for this artist in the legend.
get_linewidth()[source]
Get the line width of the Figure rectangle.
get_path_effects()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer, bbox_extra_artists=None)[source]
Return a (tight) bounding box of the figure in inches. Note that FigureBase differs from all other artists, which return their Bbox in pixels. Artists that have artist.set_in_layout(False) are not included in the bbox. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())
bbox_extra_artistslist of Artist or None
List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box. Returns
BboxBase
containing the bounding box (in figure inches).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_url()[source]
Return the url.
get_visible()[source]
Return the visibility.
get_window_extent(*args, **kwargs)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
legend(*args, **kwargs)[source]
Place a legend on the figure. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label')
fig.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.legend(handles=[line1, line2])
4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example: fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.legend(['the blues', 'the reds'])
Parameters
handleslist of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns
Legend
Other Parameters
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)
The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolint, default: 1
The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
frameonbool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)
Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
bbox_transformNone or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None
The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)
The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)
The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)
The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)
The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)
The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)
The spacing between columns, in font-size units.
handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Axes.legend
Notes Some artists are not supported by this function. See Legend guide for details.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
sca(a)[source]
Set the current Axes to be a and return a.
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
edgecolor color
facecolor color
figure Figure
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphascalar or None
alpha must be within the 0-1 range, inclusive.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_edgecolor(color)[source]
Set the edge color of the Figure rectangle. Parameters
colorcolor
set_facecolor(color)[source]
Set the face color of the Figure rectangle. Parameters
colorcolor
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_frameon(b)[source]
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters
bbool
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linewidth(linewidth)[source]
Set the line width of the Figure rectangle. Parameters
linewidthnumber
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)[source]
Add a subfigure to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subfigure grid.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of subfigures.
wspace, hspacefloat, default: None
The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from a figure or rcParams when necessary.
width_ratiosarray-like of length ncols, optional
Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width.
height_ratiosarray-like of length nrows, optional
Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height.
subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.')[source]
Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters
mosaiclist of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 Axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form '''
AAE
C.E
'''
where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;: 'AB;CC'
The string notation allows only single character Axes labels and does not support nesting but is very terse.
sharex, shareybool, default: False
If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent.
subplot_kwdict, optional
Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
empty_sentinelobject, optional
Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. Returns
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source]
Add a set of subplots to this figure. This utility wrapper makes it convenient to create common layouts of subplots in a single call. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subplot grid.
sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of x-axis (sharex) or y-axis (sharey): True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional
Dict with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns
Axes or array of Axes
Either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. See also pyplot.subplots
Figure.add_subplot
pyplot.subplot
Examples # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat, optional
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat, optional
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat, optional
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat, optional
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat, optional
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat, optional
The height of the padding between subplots, as a fraction of the average Axes height.
suptitle(t, **kwargs)[source]
Add a centered suptitle to the figure. Parameters
tstr
The suptitle text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the suptitle. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supxlabel(t, **kwargs)[source]
Add a centered supxlabel to the figure. Parameters
tstr
The supxlabel text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.01
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: bottom
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supxlabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supylabel(t, **kwargs)[source]
Add a centered supylabel to the figure. Parameters
tstr
The supylabel text.
xfloat, default: 0.02
The x location of the text in figure coordinates.
yfloat, default: 0.5
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: left
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: center
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supylabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
text(x, y, s, fontdict=None, **kwargs)[source]
Add text to figure. Parameters
x, yfloat
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
sstr
The text string.
fontdictdict, optional
A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict. Returns
Text
Other Parameters
**kwargsText properties
Other miscellaneous text parameters.
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box unknown
clip_on unknown
clip_path unknown
color or c color
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path
fontsize or size float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
math_fontfamily str
multialignment or ma {'left', 'right', 'center'}
parse_math bool
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool
rotation float or {'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
transform_rotates_text bool
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float See also Axes.text
pyplot.text
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
zorder=0
classmatplotlib.figure.SubFigure(parent, subplotspec, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, **kwargs)[source]
Logical figure that can be placed inside a figure. Typically instantiated using Figure.add_subfigure or SubFigure.add_subfigure, or SubFigure.subfigures. A subfigure has the same methods as a figure except for those particularly tied to the size or dpi of the figure, and is confined to a prescribed region of the figure. For example the following puts two subfigures side-by-side: fig = plt.figure()
sfigs = fig.subfigures(1, 2)
axsL = sfigs[0].subplots(1, 2)
axsR = sfigs[1].subplots(2, 1)
See Figure subfigures Parameters
parentfigure.Figure or figure.SubFigure
Figure or subfigure that contains the SubFigure. SubFigures can be nested.
subplotspecgridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed.
facecolordefault: rcParams["figure.facecolor"] (default: 'white')
The figure patch face color.
edgecolordefault: rcParams["figure.edgecolor"] (default: 'white')
The figure patch edge color.
linewidthfloat
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
frameonbool, default: rcParams["figure.frameon"] (default: True)
If False, suppress drawing the figure background patch. Other Parameters
**kwargsSubFigure properties, optional
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
edgecolor color
facecolor color
figure Figure
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float add_artist(artist, clip=False)[source]
Add an Artist to the figure. Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead. Parameters
artistArtist
The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure.
clipbool, default: False
Whether the added artist should be clipped by the figure patch. Returns
Artist
The added artist.
add_axes(*args, **kwargs)[source]
Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
rectsequence of float
The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
Axes, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_subplot
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
add_gridspec(nrows=1, ncols=1, **kwargs)[source]
Return a GridSpec that has this figure as a parent. This allows complex layout of Axes in the figure. Parameters
nrowsint, default: 1
Number of rows in grid.
ncolsint, default: 1
Number or columns in grid. Returns
GridSpec
Other Parameters
**kwargs
Keyword arguments are passed to GridSpec. See also matplotlib.pyplot.subplots
Examples Adding a subplot that spans two rows: fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subfigure(subplotspec, **kwargs)[source]
Add a SubFigure to the figure as part of a subplot arrangement. Parameters
subplotspecgridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed. Returns
figure.SubFigure
Other Parameters
**kwargs
Are passed to the SubFigure object. See also Figure.subfigures
add_subplot(*args, **kwargs)[source]
Add an Axes to the figure as part of a subplot arrangement. Call signatures: add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)
The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec. In rare circumstances, add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
axes.SubplotBase, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned Axes is then a subplot subclass of the base class. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_axes
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Examples fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
fig.add_subplot(232, frameon=False) # subplot with no frame
fig.add_subplot(233, projection='polar') # polar subplot
fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red") # red subplot
ax1.remove() # delete ax1 from the figure
fig.add_subplot(ax1) # add ax1 back to the figure
align_labels(axs=None)[source]
Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the labels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_ylabels
align_xlabels(axs=None)[source]
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters
axslist of Axes
Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(axs=None)[source]
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the ylabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with large yticks labels: fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source]
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters
bottomfloat, default: 0.2
The bottom of the subplots for subplots_adjust.
rotationfloat, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha{'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which{'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate.
propertyaxes
List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list. Do not modify the list itself. Instead, use add_axes, add_subplot or delaxes to add or remove an Axes. Note: The SubFigure.axes property and get_axes method are equivalent.
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]
Add a colorbar to a plot. Parameters
mappable
The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image. Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
caxAxes, optional
Axes into which the colorbar will be drawn.
axAxes, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
use_gridspecbool, optional
If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module. Returns
colorbarColorbar
Notes Additional keyword arguments are of two kinds: axes properties: locationNone or {'left', 'right', 'top', 'bottom'}
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15
Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0
Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20
Ratio of long to short dimensions. padfloat, default: 0.05 if vertical, 0.15 if horizontal
Fraction of original axes between colorbar and new image axes. anchor(float, float), optional
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal. colorbar properties:
Property Description
extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks None or list of ticks or Locator If None, ticks are determined automatically from the input.
format None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead.
drawedges bool Whether to draw lines at color boundaries.
label str The label on the colorbar's long axis. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property Description
boundaries None or a sequence
values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. If mappable is a ContourSet, its extend kwarg is included automatically. The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments: cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
contains(mouseevent)[source]
Test whether the mouse event occurred on the figure. Returns
bool, {}
convert_xunits(x)[source]
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_yunits(y)[source]
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.
delaxes(ax)[source]
Remove the Axes ax from the figure; update the current Axes.
propertydpi
draw(renderer)[source]
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). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
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 get_cursor_data
propertyframeon
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
gca(**kwargs)[source]
Get the current Axes. If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.) The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_axes()[source]
List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list. Do not modify the list itself. Instead, use add_axes, add_subplot or delaxes to add or remove an Axes. Note: The SubFigure.axes property and get_axes method are equivalent.
get_children()[source]
Get a list of artists contained in the figure.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_constrained_layout()[source]
Return whether constrained layout is being used. See Constrained Layout Guide.
get_constrained_layout_pads(relative=False)[source]
Get padding for constrained_layout. Returns a list of w_pad, h_pad in inches and wspace and hspace as fractions of the subplot. See Constrained Layout Guide. Parameters
relativebool
If True, then convert from inches to figure relative.
get_cursor_data(event)[source]
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. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_default_bbox_extra_artists()[source]
get_edgecolor()[source]
Get the edge color of the Figure rectangle.
get_facecolor()[source]
Get the face color of the Figure rectangle.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_frameon()[source]
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
get_gid()[source]
Return the group id.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_label()[source]
Return the label used for this artist in the legend.
get_linewidth()[source]
Get the line width of the Figure rectangle.
get_path_effects()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer, bbox_extra_artists=None)[source]
Return a (tight) bounding box of the figure in inches. Note that FigureBase differs from all other artists, which return their Bbox in pixels. Artists that have artist.set_in_layout(False) are not included in the bbox. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())
bbox_extra_artistslist of Artist or None
List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box. Returns
BboxBase
containing the bounding box (in figure inches).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_url()[source]
Return the url.
get_visible()[source]
Return the visibility.
get_window_extent(*args, **kwargs)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
legend(*args, **kwargs)[source]
Place a legend on the figure. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label')
fig.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.legend(handles=[line1, line2])
4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example: fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.legend(['the blues', 'the reds'])
Parameters
handleslist of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns
Legend
Other Parameters
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)
The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolint, default: 1
The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
frameonbool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)
Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
bbox_transformNone or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None
The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)
The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)
The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)
The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)
The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)
The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)
The spacing between columns, in font-size units.
handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Axes.legend
Notes Some artists are not supported by this function. See Legend guide for details.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
sca(a)[source]
Set the current Axes to be a and return a.
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
edgecolor color
facecolor color
figure Figure
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphascalar or None
alpha must be within the 0-1 range, inclusive.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_edgecolor(color)[source]
Set the edge color of the Figure rectangle. Parameters
colorcolor
set_facecolor(color)[source]
Set the face color of the Figure rectangle. Parameters
colorcolor
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_frameon(b)[source]
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters
bbool
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linewidth(linewidth)[source]
Set the line width of the Figure rectangle. Parameters
linewidthnumber
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)[source]
Add a subfigure to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subfigure grid.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of subfigures.
wspace, hspacefloat, default: None
The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from a figure or rcParams when necessary.
width_ratiosarray-like of length ncols, optional
Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width.
height_ratiosarray-like of length nrows, optional
Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height.
subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.')[source]
Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters
mosaiclist of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 Axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form '''
AAE
C.E
'''
where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;: 'AB;CC'
The string notation allows only single character Axes labels and does not support nesting but is very terse.
sharex, shareybool, default: False
If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent.
subplot_kwdict, optional
Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
empty_sentinelobject, optional
Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. Returns
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source]
Add a set of subplots to this figure. This utility wrapper makes it convenient to create common layouts of subplots in a single call. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subplot grid.
sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of x-axis (sharex) or y-axis (sharey): True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional
Dict with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns
Axes or array of Axes
Either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. See also pyplot.subplots
Figure.add_subplot
pyplot.subplot
Examples # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat, optional
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat, optional
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat, optional
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat, optional
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat, optional
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat, optional
The height of the padding between subplots, as a fraction of the average Axes height.
suptitle(t, **kwargs)[source]
Add a centered suptitle to the figure. Parameters
tstr
The suptitle text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the suptitle. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supxlabel(t, **kwargs)[source]
Add a centered supxlabel to the figure. Parameters
tstr
The supxlabel text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.01
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: bottom
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supxlabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supylabel(t, **kwargs)[source]
Add a centered supylabel to the figure. Parameters
tstr
The supylabel text.
xfloat, default: 0.02
The x location of the text in figure coordinates.
yfloat, default: 0.5
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: left
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: center
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supylabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
text(x, y, s, fontdict=None, **kwargs)[source]
Add text to figure. Parameters
x, yfloat
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
sstr
The text string.
fontdictdict, optional
A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict. Returns
Text
Other Parameters
**kwargsText properties
Other miscellaneous text parameters.
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box unknown
clip_on unknown
clip_path unknown
color or c color
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path
fontsize or size float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
math_fontfamily str
multialignment or ma {'left', 'right', 'center'}
parse_math bool
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool
rotation float or {'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
transform_rotates_text bool
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float See also Axes.text
pyplot.text
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
zorder=0
classmatplotlib.figure.SubplotParams(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
A class to hold the parameters for a subplot. Defaults are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat
The height of the padding between subplots, as a fraction of the average Axes height. update(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Update the dimensions of the passed parameters. None means unchanged.
propertyvalidate[source]
matplotlib.figure.figaspect(arg)[source]
Calculate the width and height for a figure with a specified aspect ratio. While the height is taken from rcParams["figure.figsize"] (default: [6.4, 4.8]), the width is adjusted to match the desired aspect ratio. Additionally, it is ensured that the width is in the range [4., 16.] and the height is in the range [2., 16.]. If necessary, the default height is adjusted to ensure this. Parameters
argfloat or 2D array
If a float, this defines the aspect ratio (i.e. the ratio height / width). In case of an array the aspect ratio is number of rows / number of columns, so that the array could be fitted in the figure undistorted. Returns
width, heightfloat
The figure size in inches. Notes If you want to create an Axes within the figure, that still preserves the aspect ratio, be sure to create it with equal width and height. See examples below. Thanks to Fernando Perez for this function. Examples Make a figure twice as tall as it is wide: w, h = figaspect(2.)
fig = Figure(figsize=(w, h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
Make a figure with the proper aspect for an array: A = rand(5, 3)
w, h = figaspect(A)
fig = Figure(figsize=(w, h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs) | |
doc_29294 |
Resample arrays or sparse matrices in a consistent way. The default strategy implements one step of the bootstrapping procedure. Parameters
*arrayssequence of array-like of shape (n_samples,) or (n_samples, n_outputs)
Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension.
replacebool, default=True
Implements resampling with replacement. If False, this will implement (sliced) random permutations.
n_samplesint, default=None
Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. If replace is False it should not be larger than the length of arrays.
random_stateint, RandomState instance or None, default=None
Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See Glossary.
stratifyarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
If not None, data is split in a stratified fashion, using this as the class labels. Returns
resampled_arrayssequence of array-like of shape (n_samples,) or (n_samples, n_outputs)
Sequence of resampled copies of the collections. The original arrays are not impacted. See also
shuffle
Examples It is possible to mix sparse and dense arrays in the same run: >>> X = np.array([[1., 0.], [2., 1.], [0., 0.]])
>>> y = np.array([0, 1, 2])
>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)
>>> from sklearn.utils import resample
>>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
>>> X
array([[1., 0.],
[2., 1.],
[1., 0.]])
>>> X_sparse
<3x2 sparse matrix of type '<... 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> X_sparse.toarray()
array([[1., 0.],
[2., 1.],
[1., 0.]])
>>> y
array([0, 1, 0])
>>> resample(y, n_samples=2, random_state=0)
array([0, 1])
Example using stratification: >>> y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
>>> resample(y, n_samples=5, replace=False, stratify=y,
... random_state=0)
[1, 1, 1, 0, 1] | |
doc_29295 | Gets or sets the red value of the Color. r -> int The red value of the Color. | |
doc_29296 | Alias for numel() | |
doc_29297 | Set the tty attributes for file descriptor fd from the attributes, which is a list like the one returned by tcgetattr(). The when argument determines when the attributes are changed: TCSANOW to change immediately, TCSADRAIN to change after transmitting all queued output, or TCSAFLUSH to change after transmitting all queued output and discarding all queued input. | |
doc_29298 | Return the string obtained by doing backslash substitution on the template string template, as done by the sub() method. Escapes such as \n are converted to the appropriate characters, and numeric backreferences (\1, \2) and named backreferences (\g<1>, \g<name>) are replaced by the contents of the corresponding group. Changed in version 3.5: Unmatched groups are replaced with an empty string. | |
doc_29299 |
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.