In [91]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
a = np.array([0, 2, 1.2])
la = plt.plot(a)[0]
la.
Out[91]:
<matplotlib.lines.Line2D at 0x7fa2491ffbd0>
plot() puede representar cualquier secuencia de números, aunque lo normal es utilizarlo para arrays:
In [77]:
random_data = np.random.rand(200)
plt.plot(random_data)
Out[77]:
[<matplotlib.lines.Line2D at 0x7fa249a54d50>]
In [20]:
print(plt.plot.__doc__[:469])
Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following is
legal::
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
In [21]:
plt.plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
plt.plot([1,2,3], [1,4,9], 'rs', label='line 2')
plt.axis([0, 4, 0, 10])
plt.legend()
Out[21]:
<matplotlib.legend.Legend at 0x7fa24ecee290>
Los ejemplos anteriores muestran valores almacenados en un array. Pero lógicamente, esos valores pueden ser el resultado de aplicar una función.
In [82]:
x = np.linspace(0, 10, num=50)
plt.plot(x, np.abs(np.sin(x)), "bo--")
Out[82]:
[<matplotlib.lines.Line2D at 0x7fa249710e10>]
In [83]:
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), 'b--')
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
Out[83]:
(0.0, 6.2831853071795862, -0.99987412767387507, 0.99987412767387507)
Cuando se añade una entrada, la función plot devuelve un valor un objeto que representa la gráfica.
In [84]:
x = np.linspace(0, 2 * np.pi, 100)
line = plt.plot(x, np.sin(x))[0]
print(line)
line.set_color("red")
line.
Line2D(_line0)
In [25]:
fig_random = plt.figure("random")
help(fig_random)
Help on Figure in module matplotlib.figure object:
class Figure(matplotlib.artist.Artist)
| The Figure instance supports callbacks through a *callbacks*
| attribute which is a :class:`matplotlib.cbook.CallbackRegistry`
| instance. The events you can connect to are 'dpi_changed', and
| the callback will be called with ``func(fig)`` where fig is the
| :class:`Figure` instance.
|
| *patch*
| The figure patch is drawn by a
| :class:`matplotlib.patches.Rectangle` instance
|
| *suppressComposite*
| For multiple figure images, the figure will make composite
| images depending on the renderer option_image_nocomposite
| function. If suppressComposite is True|False, this will
| override the renderer.
|
| Method resolution order:
| Figure
| matplotlib.artist.Artist
| __builtin__.object
|
| Methods defined here:
|
| __getstate__(self)
|
| __init__(self, figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)
| *figsize*
| w,h tuple in inches
|
| *dpi*
| Dots per inch
|
| *facecolor*
| The figure patch facecolor; defaults to rc ``figure.facecolor``
|
| *edgecolor*
| The figure patch edge color; defaults to rc ``figure.edgecolor``
|
| *linewidth*
| The figure patch edge linewidth; the default linewidth of the frame
|
| *frameon*
| If *False*, suppress drawing the figure frame
|
| *subplotpars*
| A :class:`SubplotParams` instance, defaults to rc
|
| *tight_layout*
| If *False* use *subplotpars*; if *True* adjust subplot
| parameters using :meth:`tight_layout` with default padding.
| When providing a dict containing the keys `pad`, `w_pad`, `h_pad`
| and `rect`, the default :meth:`tight_layout` paddings will be
| overridden.
| Defaults to rc ``figure.autolayout``.
|
| __setstate__(self, state)
|
| __str__(self)
|
| add_axes(self, *args, **kwargs)
| Add an axes at position *rect* [*left*, *bottom*, *width*,
| *height*] where all quantities are in fractions of figure
| width and height. kwargs are legal
| :class:`~matplotlib.axes.Axes` kwargs plus *projection* which
| sets the projection type of the axes. (For backward
| compatibility, ``polar=True`` may also be provided, which is
| equivalent to ``projection='polar'``). Valid values for
| *projection* are: ['aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear']. Some of these
| projections support additional kwargs, which may be provided
| to :meth:`add_axes`. Typical usage::
|
| rect = l,b,w,h
| fig.add_axes(rect)
| fig.add_axes(rect, frameon=False, axisbg='g')
| fig.add_axes(rect, polar=True)
| fig.add_axes(rect, projection='polar')
| fig.add_axes(ax)
|
| If the figure already has an axes with the same parameters,
| then it will simply make that axes current and return it. If
| you do not want this behavior, e.g., you want to force the
| creation of a new Axes, you must use a unique set of args and
| kwargs. The axes :attr:`~matplotlib.axes.Axes.label`
| attribute has been exposed for this purpose. e.g., if you want
| two axes that are otherwise identical to be added to the
| figure, make sure you give them unique labels::
|
| fig.add_axes(rect, label='axes1')
| fig.add_axes(rect, label='axes2')
|
| 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. For example,
| if an axes has been removed with :meth:`delaxes`, it can
| be restored with::
|
| fig.add_axes(ax)
|
| In all cases, the :class:`~matplotlib.axes.Axes` instance
| will be returned.
|
| In addition to *projection*, the following kwargs are supported:
|
| adjustable: [ 'box' | 'datalim' | 'box-forced']
| agg_filter: unknown
| alpha: float (0.0 transparent through 1.0 opaque)
| anchor: unknown
| animated: [True | False]
| aspect: unknown
| autoscale_on: unknown
| autoscalex_on: unknown
| autoscaley_on: unknown
| axes: an :class:`~matplotlib.axes.Axes` instance
| axes_locator: unknown
| axis_bgcolor: any matplotlib color - see :func:`~matplotlib.pyplot.colors`
| axisbelow: [ *True* | *False* ]
| clip_box: a :class:`matplotlib.transforms.Bbox` instance
| clip_on: [True | False]
| clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
| color_cycle: unknown
| contains: a callable function
| figure: unknown
| frame_on: [ *True* | *False* ]
| gid: an id string
| label: string or anything printable with '%s' conversion.
| lod: [True | False]
| navigate: [ *True* | *False* ]
| navigate_mode: unknown
| path_effects: unknown
| picker: [None|float|boolean|callable]
| position: unknown
| rasterization_zorder: unknown
| rasterized: [True | False | None]
| sketch_params: unknown
| snap: unknown
| title: unknown
| transform: :class:`~matplotlib.transforms.Transform` instance
| url: a url string
| visible: [True | False]
| xbound: unknown
| xlabel: unknown
| xlim: length 2 sequence of floats
| xmargin: unknown
| xscale: ['linear' | 'log' | 'symlog']
| xticklabels: sequence of strings
| xticks: sequence of floats
| ybound: unknown
| ylabel: unknown
| ylim: length 2 sequence of floats
| ymargin: unknown
| yscale: ['linear' | 'log' | 'symlog']
| yticklabels: sequence of strings
| yticks: sequence of floats
| zorder: any number
|
| add_axobserver(self, func)
| whenever the axes state change, ``func(self)`` will be called
|
| add_subplot(self, *args, **kwargs)
| Add a subplot. Examples::
|
| fig.add_subplot(111)
|
| # equivalent but more general
| fig.add_subplot(1,1,1)
|
| # add subplot with red background
| fig.add_subplot(212, axisbg='r')
|
| # add a polar subplot
| fig.add_subplot(111, projection='polar')
|
| # add Subplot instance sub
| fig.add_subplot(sub)
|
| *kwargs* are legal :class:`~matplotlib.axes.Axes` kwargs plus
| *projection*, which chooses a projection type for the axes.
| (For backward compatibility, *polar=True* may also be
| provided, which is equivalent to *projection='polar'*). Valid
| values for *projection* are: ['aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear']. Some of
| these projections
| support additional *kwargs*, which may be provided to
| :meth:`add_axes`.
|
| The :class:`~matplotlib.axes.Axes` instance will be returned.
|
| If the figure already has a subplot with key (*args*,
| *kwargs*) then it will simply make that subplot current and
| return it.
|
| The following kwargs are supported:
|
| adjustable: [ 'box' | 'datalim' | 'box-forced']
| agg_filter: unknown
| alpha: float (0.0 transparent through 1.0 opaque)
| anchor: unknown
| animated: [True | False]
| aspect: unknown
| autoscale_on: unknown
| autoscalex_on: unknown
| autoscaley_on: unknown
| axes: an :class:`~matplotlib.axes.Axes` instance
| axes_locator: unknown
| axis_bgcolor: any matplotlib color - see :func:`~matplotlib.pyplot.colors`
| axisbelow: [ *True* | *False* ]
| clip_box: a :class:`matplotlib.transforms.Bbox` instance
| clip_on: [True | False]
| clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
| color_cycle: unknown
| contains: a callable function
| figure: unknown
| frame_on: [ *True* | *False* ]
| gid: an id string
| label: string or anything printable with '%s' conversion.
| lod: [True | False]
| navigate: [ *True* | *False* ]
| navigate_mode: unknown
| path_effects: unknown
| picker: [None|float|boolean|callable]
| position: unknown
| rasterization_zorder: unknown
| rasterized: [True | False | None]
| sketch_params: unknown
| snap: unknown
| title: unknown
| transform: :class:`~matplotlib.transforms.Transform` instance
| url: a url string
| visible: [True | False]
| xbound: unknown
| xlabel: unknown
| xlim: length 2 sequence of floats
| xmargin: unknown
| xscale: ['linear' | 'log' | 'symlog']
| xticklabels: sequence of strings
| xticks: sequence of floats
| ybound: unknown
| ylabel: unknown
| ylim: length 2 sequence of floats
| ymargin: unknown
| yscale: ['linear' | 'log' | 'symlog']
| yticklabels: sequence of strings
| yticks: sequence of floats
| zorder: any number
|
| autofmt_xdate(self, bottom=0.2, rotation=30, ha='right')
| 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 xaxes 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.
|
| *bottom*
| The bottom of the subplots for :meth:`subplots_adjust`
|
| *rotation*
| The rotation of the xtick labels
|
| *ha*
| The horizontal alignment of the xticklabels
|
| clear(self)
| Clear the figure -- synonym for :meth:`clf`.
|
| clf(self, keep_observers=False)
| Clear the figure.
|
| Set *keep_observers* to True if, for example,
| a gui widget is tracking the axes in the figure.
|
| colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw)
| Create a colorbar for a ScalarMappable instance, *mappable*.
|
| Documentation for the pylab thin wrapper:
|
|
| Add a colorbar to a plot.
|
| Function signatures for the :mod:`~matplotlib.pyplot` interface; all
| but the first are also method signatures for the
| :meth:`~matplotlib.figure.Figure.colorbar` method::
|
| colorbar(**kwargs)
| colorbar(mappable, **kwargs)
| colorbar(mappable, cax=cax, **kwargs)
| colorbar(mappable, ax=ax, **kwargs)
|
| arguments:
|
| *mappable*
| the :class:`~matplotlib.image.Image`,
| :class:`~matplotlib.contour.ContourSet`, etc. to
| which the colorbar applies; this argument is mandatory for the
| :meth:`~matplotlib.figure.Figure.colorbar` method but optional for the
| :func:`~matplotlib.pyplot.colorbar` function, which sets the
| default to the current image.
|
| keyword arguments:
|
| *cax*
| None | axes object into which the colorbar will be drawn
| *ax*
| None | parent axes object(s) from which space for a new
| colorbar axes will be stolen. If a list of axes is given
| they will all be resized to make room for the colorbar axes.
| *use_gridspec*
| False | 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
| grid_spec module.
|
|
| Additional keyword arguments are of two kinds:
|
| axes properties:
|
|
| ============= ====================================================
| Property Description
| ============= ====================================================
| *orientation* vertical or horizontal
| *fraction* 0.15; fraction of original axes to use for colorbar
| *pad* 0.05 if vertical, 0.15 if horizontal; fraction
| of original axes between colorbar and new image axes
| *shrink* 1.0; fraction by which to shrink the colorbar
| *aspect* 20; ratio of long to short dimensions
| *anchor* (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal;
| the anchor point of the colorbar axes
| *panchor* (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal;
| the anchor point of the colorbar parent axes. If
| False, the parent axes' anchor will be unchanged
| ============= ====================================================
|
|
| 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* [ *False* | *True* ]
| 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 | list of ticks | Locator object ]
| If None, ticks are determined automatically from the
| input.
| *format* [ None | format string | Formatter object ]
| If None, the
| :class:`~matplotlib.ticker.ScalarFormatter` is used.
| If a format string is given, e.g., '%.3f', that is
| used. An alternative
| :class:`~matplotlib.ticker.Formatter` object may be
| given instead.
| *drawedges* [ False | True ] If true, draw lines at color
| boundaries.
| ============ ====================================================
|
| 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
| color mapped to the corresponding value in values
| will be used.
| ============ ===================================================
|
|
|
| If *mappable* is a :class:`~matplotlib.contours.ContourSet`, its *extend*
| kwarg is included automatically.
|
| Note that the *shrink* kwarg provides a simple way to keep a vertical
| colorbar, for example, from being taller than the axes of the mappable
| to which the colorbar is attached; but it is a manual method requiring
| some trial and error. If the colorbar is too tall (or a horizontal
| colorbar is too wide) use a smaller value of *shrink*.
|
| 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 viewer (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. Particularly
| with semi transparent images (alpha < 1) and colorbar extensions and is not
| enabled by default see (issue #1188).
|
| returns:
| :class:`~matplotlib.colorbar.Colorbar` instance; see also its base class,
| :class:`~matplotlib.colorbar.ColorbarBase`. Call the
| :meth:`~matplotlib.colorbar.ColorbarBase.set_label` method
| to label the colorbar.
|
| contains(self, mouseevent)
| Test whether the mouse event occurred on the figure.
|
| Returns True,{}
|
| delaxes(self, a)
| remove a from the figure and update the current axes
|
| draw(artist, renderer, *args, **kwargs)
| Render the figure using :class:`matplotlib.backend_bases.RendererBase`
| instance *renderer*.
|
| draw_artist(self, a)
| draw :class:`matplotlib.artist.Artist` instance *a* only --
| this is available only after the figure is drawn
|
| figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, **kwargs)
| Adds a non-resampled image to the figure.
|
| call signatures::
|
| figimage(X, **kwargs)
|
| adds a non-resampled array *X* to the figure.
|
| ::
|
| figimage(X, xo, yo)
|
| with pixel offsets *xo*, *yo*,
|
| *X* must be a float array:
|
| * If *X* is MxN, assume luminance (grayscale)
| * If *X* is MxNx3, assume RGB
| * If *X* is MxNx4, assume RGBA
|
| Optional keyword arguments:
|
| ========= =========================================================
| Keyword Description
| ========= =========================================================
| xo or yo An integer, the *x* and *y* image offset in pixels
| cmap a :class:`matplotlib.colors.Colormap` instance, eg
| cm.jet. If *None*, default to the rc ``image.cmap``
| value
| norm a :class:`matplotlib.colors.Normalize` instance. The
| default is normalization(). This scales luminance -> 0-1
| vmin|vmax are used to scale a luminance image to 0-1. If either
| is *None*, the min and max of the luminance values will
| be used. Note if you pass a norm instance, the settings
| for *vmin* and *vmax* will be ignored.
| alpha the alpha blending value, default is *None*
| origin [ 'upper' | 'lower' ] Indicates where the [0,0] index of
| the array is in the upper left or lower left corner of
| the axes. Defaults to the rc image.origin value
| ========= =========================================================
|
| figimage complements the axes image
| (:meth:`~matplotlib.axes.Axes.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
| :class:`~matplotlib.axes.Axes` with size [0,1,0,1].
|
| An :class:`matplotlib.image.FigureImage` instance is returned.
|
| .. plot:: mpl_examples/pylab_examples/figimage_demo.py
|
|
| Additional kwargs are Artist kwargs passed on to
| :class:`~matplotlib.image.FigureImage`
|
| gca(self, **kwargs)
| Return the current axes, creating one if necessary
|
| 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:
|
| adjustable: [ 'box' | 'datalim' | 'box-forced']
| agg_filter: unknown
| alpha: float (0.0 transparent through 1.0 opaque)
| anchor: unknown
| animated: [True | False]
| aspect: unknown
| autoscale_on: unknown
| autoscalex_on: unknown
| autoscaley_on: unknown
| axes: an :class:`~matplotlib.axes.Axes` instance
| axes_locator: unknown
| axis_bgcolor: any matplotlib color - see :func:`~matplotlib.pyplot.colors`
| axisbelow: [ *True* | *False* ]
| clip_box: a :class:`matplotlib.transforms.Bbox` instance
| clip_on: [True | False]
| clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
| color_cycle: unknown
| contains: a callable function
| figure: unknown
| frame_on: [ *True* | *False* ]
| gid: an id string
| label: string or anything printable with '%s' conversion.
| lod: [True | False]
| navigate: [ *True* | *False* ]
| navigate_mode: unknown
| path_effects: unknown
| picker: [None|float|boolean|callable]
| position: unknown
| rasterization_zorder: unknown
| rasterized: [True | False | None]
| sketch_params: unknown
| snap: unknown
| title: unknown
| transform: :class:`~matplotlib.transforms.Transform` instance
| url: a url string
| visible: [True | False]
| xbound: unknown
| xlabel: unknown
| xlim: length 2 sequence of floats
| xmargin: unknown
| xscale: ['linear' | 'log' | 'symlog']
| xticklabels: sequence of strings
| xticks: sequence of floats
| ybound: unknown
| ylabel: unknown
| ylim: length 2 sequence of floats
| ymargin: unknown
| yscale: ['linear' | 'log' | 'symlog']
| yticklabels: sequence of strings
| yticks: sequence of floats
| zorder: any number
|
| get_axes(self)
|
| get_children(self)
| get a list of artists contained in the figure
|
| get_default_bbox_extra_artists(self)
|
| get_dpi(self)
| Return the dpi as a float
|
| get_edgecolor(self)
| Get the edge color of the Figure rectangle
|
| get_facecolor(self)
| Get the face color of the Figure rectangle
|
| get_figheight(self)
| Return the figheight as a float
|
| get_figwidth(self)
| Return the figwidth as a float
|
| get_frameon(self)
| get the boolean indicating frameon
|
| get_size_inches(self)
|
| get_tight_layout(self)
| Return the Boolean flag, True to use :meth`tight_layout` when drawing.
|
| get_tightbbox(self, renderer)
| Return a (tight) bounding box of the figure in inches.
|
| It only accounts axes title, axis labels, and axis
| ticklabels. Needs improvement.
|
| get_window_extent(self, *args, **kwargs)
| get the figure bounding box in display space; kwargs are void
|
| ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
| Call signature::
|
| ginput(self, n=1, timeout=30, show_clicks=True,
| mouse_add=1, mouse_pop=3, mouse_stop=2)
|
| Blocking call to interact with the figure.
|
| This will wait for *n* clicks from the user and return a list of the
| coordinates of each click.
|
| If *timeout* is zero or negative, does not timeout.
|
| If *n* is zero or negative, accumulate clicks until a middle click
| (or potentially both mouse buttons at once) terminates the input.
|
| Right clicking cancels last input.
|
| The buttons used for the various actions (adding points, removing
| points, terminating the inputs) can be overriden via the
| arguments *mouse_add*, *mouse_pop* and *mouse_stop*, that give
| the associated mouse button: 1 for left, 2 for middle, 3 for
| right.
|
| 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.
|
| hold(self, b=None)
| Set the hold state. If hold is None (default), toggle the
| hold state. Else set the hold state to boolean value b.
|
| e.g.::
|
| hold() # toggle hold
| hold(True) # hold is on
| hold(False) # hold is off
|
| legend(self, handles, labels, *args, **kwargs)
| Place a legend in the figure. Labels are a sequence of
| strings, handles is a sequence of
| :class:`~matplotlib.lines.Line2D` or
| :class:`~matplotlib.patches.Patch` instances, and loc can be a
| string or an integer specifying the legend location
|
| USAGE::
|
| legend( (line1, line2, line3),
| ('label1', 'label2', 'label3'),
| 'upper right')
|
| The *loc* location codes are::
|
| 'best' : 0, (currently not supported for figure legends)
| '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,
|
| *loc* can also be an (x,y) tuple in figure coords, which
| specifies the lower left of the legend box. figure coords are
| (0,0) is the left, bottom of the figure and 1,1 is the right,
| top.
|
| Keyword arguments:
|
| *prop*: [ *None* | FontProperties | dict ]
| A :class:`matplotlib.font_manager.FontProperties`
| instance. If *prop* is a dictionary, a new instance will be
| created with *prop*. If *None*, use rc settings.
|
| *numpoints*: integer
| The number of points in the legend line, default is 4
|
| *scatterpoints*: integer
| The number of points in the legend line, default is 4
|
| *scatteryoffsets*: list of floats
| a list of yoffsets for scatter symbols in legend
|
| *markerscale*: [ *None* | scalar ]
| The relative size of legend markers vs. original. If *None*, use rc
| settings.
|
| *fancybox*: [ *None* | *False* | *True* ]
| if *True*, draw a frame with a round fancybox. If *None*, use rc
|
| *shadow*: [ *None* | *False* | *True* ]
| If *True*, draw a shadow behind legend. If *None*, use rc settings.
|
| *ncol* : integer
| number of columns. default is 1
|
| *mode* : [ "expand" | *None* ]
| if mode is "expand", the legend will be horizontally expanded
| to fill the axes area (or *bbox_to_anchor*)
|
| *title* : string
| the legend title
|
| Padding and spacing between various elements use following keywords
| parameters. The dimensions of these values are given as a fraction
| of the fontsize. Values from rcParams will be used if None.
|
| ================ ====================================================
| Keyword Description
| ================ ====================================================
| borderpad the fractional whitespace inside the legend border
| labelspacing the vertical space between the legend entries
| handlelength the length of the legend handles
| handletextpad the pad between the legend handle and text
| borderaxespad the pad between the axes and legend border
| columnspacing the spacing between columns
| ================ ====================================================
|
| .. Note:: Not all kinds of artist are supported by the legend.
| See LINK (FIXME) for details.
|
| **Example:**
|
| .. plot:: mpl_examples/pylab_examples/figlegend_demo.py
|
| savefig(self, *args, **kwargs)
| Save the current figure.
|
| Call signature::
|
| savefig(fname, dpi=None, facecolor='w', edgecolor='w',
| orientation='portrait', papertype=None, format=None,
| transparent=False, bbox_inches=None, pad_inches=0.1,
| frameon=None)
|
| The output formats available depend on the backend being used.
|
| Arguments:
|
| *fname*:
| A string containing a path to a filename, or a Python
| file-like object, or possibly some backend-dependent object
| such as :class:`~matplotlib.backends.backend_pdf.PdfPages`.
|
| If *format* is *None* and *fname* is a string, the output
| format is deduced from the extension of the filename. If
| the filename has no extension, the value of the rc parameter
| ``savefig.format`` is used.
|
| If *fname* is not a string, remember to specify *format* to
| ensure that the correct backend is used.
|
| Keyword arguments:
|
| *dpi*: [ *None* | ``scalar > 0`` ]
| The resolution in dots per inch. If *None* it will default to
| the value ``savefig.dpi`` in the matplotlibrc file.
|
| *facecolor*, *edgecolor*:
| the colors of the figure rectangle
|
| *orientation*: [ 'landscape' | 'portrait' ]
| not supported on all backends; currently only on postscript output
|
| *papertype*:
| One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
| 'a10', 'b0' through 'b10'. Only supported for postscript
| output.
|
| *format*:
| One of the file extensions supported by the active
| backend. Most backends support png, pdf, ps, eps and svg.
|
| *transparent*:
| 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.
| This is useful, for example, for displaying
| a plot on top of a colored background on a web page. The
| transparency of these patches will be restored to their
| original values upon exit of this function.
|
| *frameon*:
| If *True*, the figure patch will be colored, if *False*, the
| figure background will be transparent. If not provided, the
| rcParam 'savefig.frameon' will be used.
|
| *bbox_inches*:
| Bbox in inches. Only the given portion of the figure is
| saved. If 'tight', try to figure out the tight bbox of
| the figure.
|
| *pad_inches*:
| Amount of padding around the figure when bbox_inches is
| 'tight'.
|
| *bbox_extra_artists*:
| A list of extra artists that will be considered when the
| tight bbox is calculated.
|
| sca(self, a)
| Set the current axes to be a and return a
|
| set_canvas(self, canvas)
| Set the canvas the contains the figure
|
| ACCEPTS: a FigureCanvas instance
|
| set_dpi(self, val)
| Set the dots-per-inch of the figure
|
| ACCEPTS: float
|
| set_edgecolor(self, color)
| Set the edge color of the Figure rectangle
|
| ACCEPTS: any matplotlib color - see help(colors)
|
| set_facecolor(self, color)
| Set the face color of the Figure rectangle
|
| ACCEPTS: any matplotlib color - see help(colors)
|
| set_figheight(self, val)
| Set the height of the figure in inches
|
| ACCEPTS: float
|
| set_figwidth(self, val)
| Set the width of the figure in inches
|
| ACCEPTS: float
|
| set_frameon(self, b)
| Set whether the figure frame (background) is displayed or invisible
|
| ACCEPTS: boolean
|
| set_size_inches(self, *args, **kwargs)
| set_size_inches(w,h, forward=False)
|
| Set the figure size in inches
|
| Usage::
|
| fig.set_size_inches(w,h) # OR
| fig.set_size_inches((w,h) )
|
| optional kwarg *forward=True* will cause the canvas size to be
| automatically updated; eg you can resize the figure window
| from the shell
|
| ACCEPTS: a w,h tuple with w,h in inches
|
| set_tight_layout(self, tight)
| Set whether :meth:`tight_layout` is used upon drawing.
| If None, the rcParams['figure.autolayout'] value will be set.
|
| When providing a dict containing the keys `pad`, `w_pad`, `h_pad`
| and `rect`, the default :meth:`tight_layout` paddings will be
| overridden.
|
| ACCEPTS: [True | False | dict | None ]
|
| show(self, warn=True)
| If using a GUI backend with pyplot, display the figure window.
|
| If the figure was not created using
| :func:`~matplotlib.pyplot.figure`, it will lack a
| :class:`~matplotlib.backend_bases.FigureManagerBase`, and
| will raise an AttributeError.
|
| For non-GUI backends, this does nothing, in which case
| a warning will be issued if *warn* is True (default).
|
| subplots_adjust(self, *args, **kwargs)
| Call signature::
|
| subplots_adjust(left=None, bottom=None, right=None, top=None,
| wspace=None, hspace=None)
|
| Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when
| *None*) and update the subplot locations
|
| suptitle(self, t, **kwargs)
| Add a centered title to the figure.
|
| kwargs are :class:`matplotlib.text.Text` properties. Using figure
| coordinates, the defaults are:
|
| *x* : 0.5
| The x location of the text in figure coords
|
| *y* : 0.98
| The y location of the text in figure coords
|
| *horizontalalignment* : 'center'
| The horizontal alignment of the text
|
| *verticalalignment* : 'top'
| The vertical alignment of the text
|
| A :class:`matplotlib.text.Text` instance is returned.
|
| Example::
|
| fig.suptitle('this is the figure title', fontsize=12)
|
| text(self, x, y, s, *args, **kwargs)
| Add text to figure.
|
| Call signature::
|
| text(x, y, s, fontdict=None, **kwargs)
|
| Add text to figure at location *x*, *y* (relative 0-1
| coords). See :func:`~matplotlib.pyplot.text` for the meaning
| of the other arguments.
|
| kwargs control the :class:`~matplotlib.text.Text` properties:
|
| agg_filter: unknown
| alpha: float (0.0 transparent through 1.0 opaque)
| animated: [True | False]
| axes: an :class:`~matplotlib.axes.Axes` instance
| backgroundcolor: any matplotlib color
| bbox: rectangle prop dict
| clip_box: a :class:`matplotlib.transforms.Bbox` instance
| clip_on: [True | False]
| clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
| color: any matplotlib color
| contains: a callable function
| family or fontfamily or fontname or name: [FONTNAME | 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]
| figure: a :class:`matplotlib.figure.Figure` instance
| fontproperties or font_properties: a :class:`matplotlib.font_manager.FontProperties` instance
| gid: an id string
| horizontalalignment or ha: [ 'center' | 'right' | 'left' ]
| label: string or anything printable with '%s' conversion.
| linespacing: float (multiple of font size)
| lod: [True | False]
| multialignment: ['left' | 'right' | 'center' ]
| path_effects: unknown
| picker: [None|float|boolean|callable]
| position: (x,y)
| rasterized: [True | False | None]
| rotation: [ angle in degrees | 'vertical' | 'horizontal' ]
| rotation_mode: unknown
| size or fontsize: [size in points | 'xx-small' | 'x-small' | 'small' | 'medium' | 'large' | 'x-large' | 'xx-large' ]
| sketch_params: unknown
| snap: unknown
| stretch or fontstretch: [a numeric value in range 0-1000 | 'ultra-condensed' | 'extra-condensed' | 'condensed' | 'semi-condensed' | 'normal' | 'semi-expanded' | 'expanded' | 'extra-expanded' | 'ultra-expanded' ]
| style or fontstyle: [ 'normal' | 'italic' | 'oblique']
| text: string or anything printable with '%s' conversion.
| transform: :class:`~matplotlib.transforms.Transform` instance
| url: a url string
| variant or fontvariant: [ 'normal' | 'small-caps' ]
| verticalalignment or va or ma: [ 'center' | 'top' | 'bottom' | 'baseline' ]
| visible: [True | False]
| weight or fontweight: [a numeric value in range 0-1000 | 'ultralight' | 'light' | 'normal' | 'regular' | 'book' | 'medium' | 'roman' | 'semibold' | 'demibold' | 'demi' | 'bold' | 'heavy' | 'extra bold' | 'black' ]
| x: float
| y: float
| zorder: any number
|
| tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None)
| Adjust subplot parameters to give specified padding.
|
| Parameters:
|
| *pad* : float
| padding between the figure edge and the edges of subplots,
| as a fraction of the font-size.
| *h_pad*, *w_pad* : float
| padding (height/width) between edges of adjacent subplots.
| Defaults to `pad_inches`.
| *rect* : if rect is given, it is interpreted as a rectangle
| (left, bottom, right, top) in the normalized figure
| coordinate that the whole subplots area (including
| labels) will fit into. Default is (0, 0, 1, 1).
|
| waitforbuttonpress(self, timeout=-1)
| Call signature::
|
| waitforbuttonpress(self, timeout=-1)
|
| Blocking call to interact with the figure.
|
| This will return True is a key was pressed, False if a mouse
| button was pressed and None if *timeout* was reached without
| either being pressed.
|
| If *timeout* is negative, does not timeout.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| axes
| Read-only: list of axes in Figure
|
| dpi
|
| ----------------------------------------------------------------------
| Methods inherited from matplotlib.artist.Artist:
|
| add_callback(self, func)
| Adds a callback function that will be called whenever one of
| the :class:`Artist`'s properties changes.
|
| Returns an *id* that is useful for removing the callback with
| :meth:`remove_callback` later.
|
| convert_xunits(self, x)
| For artists in an axes, if the xaxis has units support,
| convert *x* using xaxis unit type
|
| convert_yunits(self, y)
| For artists in an axes, if the yaxis has units support,
| convert *y* using yaxis unit type
|
| findobj(self, match=None, include_self=True)
| Find artist objects.
|
| Recursively find all :class:`~matplotlib.artist.Artist` instances
| contained in self.
|
| *match* can be
|
| - None: return all objects contained in artist.
|
| - function with signature ``boolean = match(artist)``
| used to filter matches
|
| - class instance: e.g., Line2D. Only return artists of class type.
|
| If *include_self* is True (default), include self in the list to be
| checked for a match.
|
| get_agg_filter(self)
| return filter function to be used for agg filter
|
| get_alpha(self)
| Return the alpha value used for blending - not supported on all
| backends
|
| get_animated(self)
| Return the artist's animated state
|
| get_clip_box(self)
| Return artist clipbox
|
| get_clip_on(self)
| Return whether artist uses clipping
|
| get_clip_path(self)
| Return artist clip path
|
| get_contains(self)
| Return the _contains test used by the artist, or *None* for default.
|
| get_figure(self)
| Return the :class:`~matplotlib.figure.Figure` instance the
| artist belongs to.
|
| get_gid(self)
| Returns the group id
|
| get_label(self)
| Get the label used for this artist in the legend.
|
| get_path_effects(self)
|
| get_picker(self)
| Return the picker object used by this artist
|
| get_rasterized(self)
| return True if the artist is to be rasterized
|
| get_sketch_params(self)
| Returns the sketch parameters for the artist.
|
| Returns
| -------
| sketch_params : 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.
|
| May return `None` if no sketch parameters were set.
|
| get_snap(self)
| Returns the snap setting which may be:
|
| * True: snap vertices to the nearest pixel center
|
| * False: leave vertices as-is
|
| * None: (auto) If the path contains only rectilinear line
| segments, round to the nearest pixel center
|
| Only supported by the Agg and MacOSX backends.
|
| get_transform(self)
| Return the :class:`~matplotlib.transforms.Transform`
| instance used by this artist.
|
| get_transformed_clip_path_and_affine(self)
| Return the clip path with the non-affine part of its
| transformation applied, and the remaining affine part of its
| transformation.
|
| get_url(self)
| Returns the url
|
| get_visible(self)
| Return the artist's visiblity
|
| get_zorder(self)
| Return the :class:`Artist`'s zorder.
|
| have_units(self)
| Return *True* if units are set on the *x* or *y* axes
|
| hitlist(self, event)
| List the children of the artist which contain the mouse event *event*.
|
| is_figure_set(self)
| Returns True if the artist is assigned to a
| :class:`~matplotlib.figure.Figure`.
|
| is_transform_set(self)
| Returns *True* if :class:`Artist` has a transform explicitly
| set.
|
| pchanged(self)
| Fire an event when property changed, calling all of the
| registered callbacks.
|
| pick(self, mouseevent)
| call signature::
|
| pick(mouseevent)
|
| each child artist will fire a pick event if *mouseevent* is over
| the artist and the artist has picker set
|
| pickable(self)
| Return *True* if :class:`Artist` is pickable.
|
| properties(self)
| return a dictionary mapping property name -> value for all Artist props
|
| remove(self)
| Remove the artist from the figure if possible. The effect
| will not be visible until the figure is redrawn, e.g., with
| :meth:`matplotlib.axes.Axes.draw_idle`. Call
| :meth:`matplotlib.axes.Axes.relim` to update the axes limits
| if desired.
|
| Note: :meth:`~matplotlib.axes.Axes.relim` will not see
| collections even if the collection was added to axes with
| *autolim* = True.
|
| Note: there is no support for removing the artist's legend entry.
|
| remove_callback(self, oid)
| Remove a callback based on its *id*.
|
| .. seealso::
|
| :meth:`add_callback`
| For adding callbacks
|
| set(self, **kwargs)
| A tkstyle set command, pass *kwargs* to set properties
|
| set_agg_filter(self, filter_func)
| set agg_filter fuction.
|
| set_alpha(self, alpha)
| Set the alpha value used for blending - not supported on
| all backends.
|
| ACCEPTS: float (0.0 transparent through 1.0 opaque)
|
| set_animated(self, b)
| Set the artist's animation state.
|
| ACCEPTS: [True | False]
|
| set_axes(self, axes)
| Set the :class:`~matplotlib.axes.Axes` instance in which the
| artist resides, if any.
|
| ACCEPTS: an :class:`~matplotlib.axes.Axes` instance
|
| set_clip_box(self, clipbox)
| Set the artist's clip :class:`~matplotlib.transforms.Bbox`.
|
| ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance
|
| set_clip_on(self, b)
| Set whether artist uses clipping.
|
| ACCEPTS: [True | False]
|
| set_clip_path(self, path, transform=None)
| Set the artist's clip path, which may be:
|
| * a :class:`~matplotlib.patches.Patch` (or subclass) instance
|
| * a :class:`~matplotlib.path.Path` instance, in which case
| an optional :class:`~matplotlib.transforms.Transform`
| instance may be provided, which will be applied to the
| path before using it for clipping.
|
| * *None*, to remove the clipping path
|
| For efficiency, if the path happens to be an axis-aligned
| rectangle, this method will set the clipping box to the
| corresponding rectangle and set the clipping path to *None*.
|
| ACCEPTS: [ (:class:`~matplotlib.path.Path`,
| :class:`~matplotlib.transforms.Transform`) |
| :class:`~matplotlib.patches.Patch` | None ]
|
| set_contains(self, picker)
| Replace the contains test used by this artist. The new picker
| should be a callable function which determines whether the
| artist is hit by the mouse event::
|
| hit, props = picker(artist, mouseevent)
|
| If the mouse event is over the artist, return *hit* = *True*
| and *props* is a dictionary of properties you want returned
| with the contains test.
|
| ACCEPTS: a callable function
|
| set_figure(self, fig)
| Set the :class:`~matplotlib.figure.Figure` instance the artist
| belongs to.
|
| ACCEPTS: a :class:`matplotlib.figure.Figure` instance
|
| set_gid(self, gid)
| Sets the (group) id for the artist
|
| ACCEPTS: an id string
|
| set_label(self, s)
| Set the label to *s* for auto legend.
|
| ACCEPTS: string or anything printable with '%s' conversion.
|
| set_lod(self, on)
| Set Level of Detail on or off. If on, the artists may examine
| things like the pixel width of the axes and draw a subset of
| their contents accordingly
|
| ACCEPTS: [True | False]
|
| set_path_effects(self, path_effects)
| set path_effects, which should be a list of instances of
| matplotlib.patheffect._Base class or its derivatives.
|
| set_picker(self, picker)
| Set the epsilon for picking used by this artist
|
| *picker* 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 it's 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.
|
| ACCEPTS: [None|float|boolean|callable]
|
| set_rasterized(self, rasterized)
| Force rasterized (bitmap) drawing in vector backend output.
|
| Defaults to None, which implies the backend's default behavior
|
| ACCEPTS: [True | False | None]
|
| set_sketch_params(self, scale=None, length=None, randomness=None)
| Sets the the sketch parameters.
|
| Parameters
| ----------
|
| scale : float, 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.
|
| length : float, optional
| The length of the wiggle along the line, in pixels
| (default 128.0)
|
| randomness : float, optional
| The scale factor by which the length is shrunken or
| expanded (default 16.0)
|
| set_snap(self, snap)
| Sets the snap setting which may be:
|
| * True: snap vertices to the nearest pixel center
|
| * False: leave vertices as-is
|
| * None: (auto) If the path contains only rectilinear line
| segments, round to the nearest pixel center
|
| Only supported by the Agg and MacOSX backends.
|
| set_transform(self, t)
| Set the :class:`~matplotlib.transforms.Transform` instance
| used by this artist.
|
| ACCEPTS: :class:`~matplotlib.transforms.Transform` instance
|
| set_url(self, url)
| Sets the url for the artist
|
| ACCEPTS: a url string
|
| set_visible(self, b)
| Set the artist's visiblity.
|
| ACCEPTS: [True | False]
|
| set_zorder(self, level)
| Set the zorder for the artist. Artists with lower zorder
| values are drawn first.
|
| ACCEPTS: any number
|
| update(self, props)
| Update the properties of this :class:`Artist` from the
| dictionary *prop*.
|
| update_from(self, other)
| Copy properties from *other* to *self*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from matplotlib.artist.Artist:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from matplotlib.artist.Artist:
|
| aname = 'Artist'
|
| zorder = 0
<matplotlib.figure.Figure at 0x7fa24ed6a210>
In [26]:
plt.plot(random_data)
plt.figure("linear")
plt.plot(np.arange(100))
Out[26]:
[<matplotlib.lines.Line2D at 0x7fa24eb5fb50>]
In [27]:
print(plt.subplot.__doc__[:140])
x = np.linspace(0,10)
plt.subplot(1,2,1).plot(x, x ** 2)
plt.subplot(1,2,2).plot(np.random.normal(2, 0.2, 1000))
Return a subplot axes positioned by the given grid definition.
Typical call signature::
subplot(nrows, ncols, plot_number)
Out[27]:
[<matplotlib.lines.Line2D at 0x7fa24ea76650>]
In [28]:
a = np.array([[3,4], [2,1], [1,2]])
b = a.transpose()
print(b)
plt.plot(b[0], b[1], 'bo')
plt.xlim(0, 5)
plt.ylim(0, 5)
[[3 2 1]
[4 1 2]]
Out[28]:
(0, 5)
In [88]:
points = np.random.randn(2, 1000) * 10
plt.plot(points[0], points[1], '.')
Out[88]:
[<matplotlib.lines.Line2D at 0x7fa2493fe890>]
In [49]:
def f(x):
return np.sin(4 * np.pi * x) * np.exp(-5 * x)
x = np.linspace(0, 1, 200)
plt.plot(x, f(x), label=r"$y = sin(4 \pi x) e^{-5x}$")
plt.axhline(0, color='red')
plt.legend()
Out[49]:
<matplotlib.legend.Legend at 0x7fa24d687f10>
In [64]:
n = np.array([0,1,2,3,4,5])
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(n, n + 0.25 * np.random.randn(len(n)))
axes[1].step(n, n**2, lw=2)
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)
Out[64]:
<matplotlib.collections.PolyCollection at 0x7fa24c1b8dd0>
In [69]:
xvec = np.linspace(-5.,5.,100)
x,y = np.meshgrid(xvec, xvec)
z = np.hypot(x, y)
plt.contourf(x, y, z, 100)
plt.colorbar()
Out[69]:
<matplotlib.colorbar.Colorbar instance at 0x7fa249d11bd8>
Content source: davidvilla/python-course
Similar notebooks: