Matplotlib pyplot python plot

matplotlib.pyplot.plot#

The coordinates of the points or line nodes are given by x, y.

The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It’s a shortcut string notation described in the Notes section below.

>>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses 

You can use Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12) >>> plot(x, y, color='green', marker='o', linestyle='dashed', . linewidth=2, markersize=12) 

When conflicting with fmt, keyword arguments take precedence.

Plotting labelled data

There’s a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj[‘y’] ). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

>>> plot('xlabel', 'ylabel', data=obj) 

All indexable objects are supported. This could e.g. be a dict , a pandas.DataFrame or a structured numpy array.

Plotting multiple sets of data

There are various ways to plot multiple sets of data.

    The most straight forward way is just to call plot multiple times. Example:

>>> plot(x1, y1, 'bo') >>> plot(x2, y2, 'go') 
>>> x = [1, 2, 3] >>> y = np.array([[1, 2], [3, 4], [5, 6]]) >>> plot(x, y) 
>>> for col in range(y.shape[1]): . plot(x, y[:, col]) 

By default, each line is assigned a different style specified by a ‘style cycle’. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ).

Parameters : x, y array-like or scalar

The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)) .

Commonly, these parameters are 1D arrays.

They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

These arguments cannot be passed as keywords.

fmt str, optional

A format string, e.g. ‘ro’ for red circles. See the Notes section for a full description of the format strings.

Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.

This argument cannot be passed as keyword.

data indexable object, optional

An object with labelled data. If given, provide the label names to plot in x and y.

Technically there’s a slight ambiguity in calls where the second label is a valid fmt. plot(‘n’, ‘o’, data=obj) could be plt(x, y) or plt(y, fmt) . In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot(‘n’, ‘o’, », data=obj) .

A list of lines representing the plotted data.

Other Parameters : scalex, scaley bool, default: True

These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view .

**kwargs Line2D properties, optional

kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:

>>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') 

If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.

Here is a list of available Line2D properties:

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

Источник

matplotlib.pyplot #

matplotlib.pyplot is a state-based interface to matplotlib. It provides an implicit, MATLAB-like, way of plotting. It also opens figures on your screen, and acts as the figure GUI manager.

pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation:

import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1) y = np.sin(x) plt.plot(x, y) 

The explicit object-oriented API is recommended for complex plots, though pyplot is still usually used to create the figure and often the axes in the figure. See pyplot.figure , pyplot.subplots , and pyplot.subplot_mosaic to create figures, and Axes API for the plotting methods on an Axes:

import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1) y = np.sin(x) fig, ax = plt.subplots() ax.plot(x, y) 

See Matplotlib Application Interfaces (APIs) for an explanation of the tradeoffs between the implicit and explicit interfaces.

Managing Figure and Axes#

Add an Axes to the current figure and make it the current Axes.

Remove an Axes (defaulting to the current axes) from its figure.

Return whether the figure with the given id exists.

Create a new figure, or activate an existing figure.

Return a list of existing figure labels.

Return a list of existing figure numbers.

Set the current Axes to ax and the current Figure to the parent of ax.

Add an Axes to the current figure or retrieve an existing Axes.

Create a subplot at a specific location inside a regular grid.

Build a layout of Axes based on ASCII art or nested lists.

Create a figure and a set of subplots.

Make and return a second axes that shares the x-axis.

Make and return a second axes that shares the y-axis.

Adding data to the plot#

Basic#

Plot y versus x as lines and/or markers.

Plot y versus x as lines and/or markers with attached errorbars.

[Discouraged] Plot coercing the axis to treat floats as dates.

Make a plot with log scaling on both the x- and y-axis.

Make a plot with log scaling on the x-axis.

Make a plot with log scaling on the y-axis.

Fill the area between two horizontal curves.

Fill the area between two vertical curves.

Make a horizontal bar plot.

Plot identical parallel lines at the given positions.

Plot a horizontal sequence of rectangles.

Plot vertical lines at each x from ymin to ymax.

Plot horizontal lines at each y from xmin to xmax.

Spans#

Add a horizontal line across the Axes.

Add a horizontal span (rectangle) across the Axes.

Add a vertical line across the Axes.

Add a vertical span (rectangle) across the Axes.

Add an infinitely long straight line.

Spectral#

Plot the autocorrelation of x.

Plot the coherence between x and y.

Plot the cross-spectral density.

Plot the magnitude spectrum.

Plot the power spectral density.

Plot the cross correlation between x and y.

Statistics#

Draw a box and whisker plot.

Binned#

Make a 2D hexagonal binning plot of points x, y.

Compute and plot a histogram.

A stepwise constant function as a line with bounding edges or a filled plot.

Contours#

2D arrays#

Display data as an image, i.e., on a 2D regular raster.

Display an array as a matrix in a new figure window.

Create a pseudocolor plot with a non-regular rectangular grid.

Create a pseudocolor plot with a non-regular rectangular grid.

Plot the sparsity pattern of a 2D array.

Add a non-resampled image to the figure.

Unstructured triangles#

Draw an unstructured triangular grid as lines and/or markers.

Create a pseudocolor plot of an unstructured triangular grid.

Draw contour lines on an unstructured triangular grid.

Draw contour regions on an unstructured triangular grid.

Text and annotations#

Annotate the point xy with text text.

Place a legend on the figure.

Place a legend on the Axes.

Vector fields#

Plot a 2D field of arrows.

Add a key to a quiver plot.

Draw streamlines of a vector flow.

Axis configuration#

Autoscale the axis view to the data (toggle).

Convenience method to get or set some axis properties.

Turn the axes box on or off on the current axes.

Control behavior of major tick locators.

Remove minor ticks from the Axes.

Display minor ticks on the Axes.

Get or set the radial gridlines on the current polar plot.

Get or set the theta gridlines on the current polar plot.

Change the appearance of ticks, tick labels, and gridlines.

Configure the ScalarFormatter used by default for linear Axes.

Set the label for the x-axis.

Get or set the x limits of the current axes.

Get or set the current tick locations and labels of the x-axis.

Set the label for the y-axis.

Get or set the y-limits of the current axes.

Get or set the current tick locations and labels of the y-axis.

Add a centered suptitle to the figure.

Layout#

Set or retrieve autoscaling margins.

Adjust the subplot layout parameters.

Launch a subplot tool window for a figure.

Adjust the padding between and around subplots.

Colormapping#

Set the color limits of the current image.

Get the current colorable artist.

Get a colormap instance, defaulting to rc values if name is None.

Set the default colormap, and applies it to the current image if any.

Read an image from a file into an array.

Colormap and save an array as an image file.

Colormaps are available via the colormap registry matplotlib.colormaps . For convenience this registry is available in pyplot as

Container for colormaps that are known to Matplotlib by name.

The universal registry instance is matplotlib.colormaps . There should be no need for users to instantiate ColormapRegistry themselves.

Read access uses a dict-like interface mapping names to Colormap s:

import matplotlib as mpl cmap = mpl.colormaps['viridis'] 

Returned Colormap s are copies, so that their modification does not change the global definition of the colormap.

Additional colormaps can be added via ColormapRegistry.register :

mpl.colormaps.register(my_colormap) 

Additionally, there are shortcut functions to set builtin colormaps; e.g. plt.viridis() is equivalent to plt.set_cmap(‘viridis’) .

Container for sequences of colors that are known to Matplotlib by name.

The universal registry instance is matplotlib.color_sequences . There should be no need for users to instantiate ColorSequenceRegistry themselves.

Read access uses a dict-like interface mapping names to lists of colors:

import matplotlib as mpl cmap = mpl.color_sequences['tab10'] 

The returned lists are copies, so that their modification does not change the global definition of the color sequence.

Additional color sequences can be added via ColorSequenceRegistry.register :

mpl.color_sequences.register('rgb', ['r', 'g', 'b']) 

Configuration#

Set the current rcParams . group is the grouping for the rc, e.g., for lines.linewidth the group is lines , for axes.facecolor , the group is axes , and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.

Return a context manager for temporarily changing rcParams.

Restore the rcParams from Matplotlib’s internal default style.

Output#

Redraw the current figure.

Redraw the current figure if in interactive mode.

Connect to the display hook of the current shell.

Return whether plots are updated after every plotting command.

Run the GUI event loop for interval seconds.

Disconnect from the display hook of the current shell.

Other#

Bind function func to event s.

Disconnect the callback with id cid.

Return the value of an Artist ‘s property, or print all of them.

Return the value of an Artist ‘s property, or print all of them.

Return the figure manager of the current figure.

Blocking call to interact with a figure.

Create a new figure manager instance.

Configure Matplotlib’s logging levels.

Set one or more properties on an Artist , or list allowed values.

Blocking call to interact with the figure.

Turn on xkcd sketch-style drawing mode.

Источник

Читайте также:  Web pages made with php
Оцените статью