Plotting and visualization through matplotlib and pandas
Plotting and visualization through matplotlib and pandas
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
A brief matplotlib API primer
data=np.arange(10)
plt.plot(data)
<IPython.core.display.Javascript object>
[<matplotlib.lines.Line2D at 0x2ead7585128>]
Figures and subplots
Plots in matplotlib reside within a Figure
object.You can create a new figure with plt.figure
.
fig=plt.figure()
<IPython.core.display.Javascript object>
plt.figure
has a number of options;notably,figsize
will guarantee the figure.You have to create one or more subplots
using add_subplot
:
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
One nuance of using notebooks is that plots are reset after each cell is evaluated,so for more complex plots you must put all of the plotting commands in a single notebook cell.
plt.plot(np.random.randn(50).cumsum(),'k--')
[<matplotlib.lines.Line2D at 0x2ead7616828>]
When you issue a plotting command like plt.plot
,matplotlib draws on the last figure and subplot used(creating one if necessary),thus hiding the figure and subplot creation.
The objects returned by fig.add_subplot
here are AxesSsubplot
objects.
ax1.hist(np.random.randn(100),bins=20,color='k',alpha=0.3)
(array([ 1., 0., 0., 2., 3., 5., 3., 5., 5., 11., 8., 7., 10.,
9., 13., 5., 7., 4., 1., 1.]),
array([-3.18837272, -2.9047759 , -2.62117907, -2.33758224, -2.05398542,
-1.77038859, -1.48679177, -1.20319494, -0.91959811, -0.63600129,
-0.35240446, -0.06880763, 0.21478919, 0.49838602, 0.78198284,
1.06557967, 1.3491765 , 1.63277332, 1.91637015, 2.19996697,
2.4835638 ]),
<a list of 20 Patch objects>)
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))
<matplotlib.collections.PathCollection at 0x2ead7622320>
- Creating a figure with a grid of subplots is a very common task,so matplotlib includes a convenience method,
plot.subplots
,that creates a new figure and returns a numpy array containing the created subplot objects:
fig,axes=plt.subplots(2,2,sharex=True,sharey=True)
<IPython.core.display.Javascript object>
for i in range(2):
for j in range(2):
axes[i,j].hist(np.random.randn(500),bins=50,color='k',alpha=0.5)
You can change the spacing using the subplots_adjust
method on Figure
objects,also available as a top-level function.
help(plt.subplots_adjust)
Help on function subplots_adjust in module matplotlib.pyplot:
subplots_adjust(*args, **kwargs)
Tune the subplot layout.
call signature::
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
The parameter meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for space between subplots,
# expressed as a fraction of the average axis width
hspace = 0.2 # the amount of height reserved for space between subplots,
# expressed as a fraction of the average axis height
The actual defaults are controlled by the rc file
plt.subplots_adjust(wspace=0,hspace=0)
Colors,markers,and line styles
Matplotlib's main plot
function accepts array of x and y coordinates and optionally a string abrreviation indicating color and line style.
fig=plt.figure()
<IPython.core.display.Javascript object>
plt.plot(np.random.randn(30).cumsum(),'ko--')
[<matplotlib.lines.Line2D at 0x2ead790a7b8>]
plt.plot(np.random.randn(30).cumsum(),'ro--')
[<matplotlib.lines.Line2D at 0x2ead790a8d0>]
Ticks,Labels,and Legends
help(plt.xlim)
Help on function xlim in module matplotlib.pyplot:
xlim(*args, **kwargs)
Get or set the x limits of the current axes.
Call signatures::
xmin, xmax = xlim() # return the current xlim
xlim((xmin, xmax)) # set the xlim to xmin, xmax
xlim(xmin, xmax) # set the xlim to xmin, xmax
If you do not specify args, you can pass *xmin* or *xmax* as kwargs, i.e.::
xlim(xmax=3) # adjust the max leaving min unchanged
xlim(xmin=1) # adjust the min leaving max unchanged
Setting limits turns autoscaling off for the x-axis.
Returns
-------
xmin, xmax
A tuple of the new x-axis limits.
Notes
-----
Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
equivalent of calling `~.Axes.get_xlim` on the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xlim` on the current axes. All arguments are passed though.
plt.xlim([-10,30])
(-10, 30)
The pyplot
interface,designed for interactive use,consist of methods like xlim``xticks
and xticklabels
.These control the plot range,tick locations and tick labels,respectively.Thet can be used in two ways:
-
Called with no arguments returns the current parameter value(e.g.,
plt.xlim()
returns the current x-axis plotting range). -
Called with parameters sets the parameter value(e.g.,
plt.xlim([0,10])
sets the x-axis range to (0,10))
All such methods act on the active or most recently created AxesSubplot
.Each of them corresponds to two methods on the subplot object itself. In the case of xlim
these are ax.set_xlim
and ax.get_xlim
.
type(plt)
module
type(fig)
matplotlib.figure.Figure
type(ax1)
matplotlib.axes._subplots.AxesSubplot
fig,ax=plt.subplots(2,2)
<IPython.core.display.Javascript object>
type(ax[0][0])
matplotlib.axes._subplots.AxesSubplot
So what the figure.add_subplot
returns and the plt.subplots
returns are all object AxesSubplot
a=np.random.randn(100)
help(a.cumsum)
Help on built-in function cumsum:
cumsum(...) method of numpy.ndarray instance
a.cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis.
Refer to `numpy.cumsum` for full documentation.
See Also
--------
numpy.cumsum : equivalent function
np.arange(101).cumsum()
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231,
253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528,
561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946,
990, 1035, 1081, 1128, 1176, 1225, 1275, 1326, 1378, 1431, 1485,
1540, 1596, 1653, 1711, 1770, 1830, 1891, 1953, 2016, 2080, 2145,
2211, 2278, 2346, 2415, 2485, 2556, 2628, 2701, 2775, 2850, 2926,
3003, 3081, 3160, 3240, 3321, 3403, 3486, 3570, 3655, 3741, 3828,
3916, 4005, 4095, 4186, 4278, 4371, 4465, 4560, 4656, 4753, 4851,
4950, 5050], dtype=int32)
Setting the title,axis labels,ticks and ticklabels
fig=plt.figure() # not Figure
<IPython.core.display.Javascript object>
plt.Figure ==plt.figure # Attention please!
False
ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum())
[<matplotlib.lines.Line2D at 0x2ead79fc4a8>]
ticks=ax.set_xticks([0,250,500,750,1000])
labels=ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small')
The rotation
option sets the x tick labels at a 30-degree rotation.Lastly,set_xlabel
gives a name to the x-axis and set_title
the subplot title.
ax.set_title('My first matplotlib plot')
Text(0.5,1,'My first matplotlib plot')
ax.set_xlabel('Stages')
Text(0.5,0,'Stages')
Modifying the y-axis consists of the same process,substituting y
for x in the above.The axes class has a set
method that allows batch setting of plot properties.
props={'title':'my first matplotlib plot',
'xlabel':'stages'}
ax.set(**props)
[Text(0.5,0,'stages'), Text(0.5,1,'my first matplotlib plot')]
Adding legends
fig=plt.figure()
<IPython.core.display.Javascript object>
ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum(),'k',label='one')
[<matplotlib.lines.Line2D at 0x2ead7a430b8>]
ax.plot(np.random.randn(1000).cumsum(),'k--',label='two')
[<matplotlib.lines.Line2D at 0x2ead7a43630>]
ax.plot(np.random.randn(1000).cumsum(),'k.',label='_nolegend_')
[<matplotlib.lines.Line2D at 0x2ead7a43c18>]
ax.legend(loc='best')
<matplotlib.legend.Legend at 0x2ead7a435c0>
help(ax.legend)
Help on method legend in module matplotlib.axes._axes:
legend(*args, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
Places a legend on the axes.
Call signatures::
legend()
legend(labels)
legend(handles, labels)
The call signatures correspond to three different ways how 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
:meth:`~.Artist.set_label` method on the artist::
line, = ax.plot([1, 2, 3], label='Inline label')
ax.legend()
or::
line.set_label('Label via method')
line, = ax.plot([1, 2, 3])
ax.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 `Axes.legend` without
any arguments and without setting the labels manually will result in
no legend being drawn.
**2. Labeling existing plot elements**
To make a legend for lines which already exist on the axes
(via plot for instance), simply call this function with an iterable
of strings, one for each legend item. For example::
ax.plot([1, 2, 3])
ax.legend(['A simple line'])
Note: This way of using is discouraged, because the relation between
plot elements and labels is only implicit by their order and can
easily be mixed up.
**3. Explicitly defining the elements 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::
legend((line1, line2, line3), ('label1', 'label2', 'label3'))
Parameters
----------
handles : sequence 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.
labels : sequence of strings, 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.
Other Parameters
----------------
loc : int or string or pair of floats, default: 'upper right'
The location of the legend. Possible codes are:
=============== =============
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
=============== =============
Alternatively can be a 2-tuple giving ``x, y`` of the lower-left
corner of the legend in axes coordinates (in which case
``bbox_to_anchor`` will be ignored).
bbox_to_anchor : `.BboxBase` or pair of floats
Specify any arbitrary location for the legend in `bbox_transform`
coordinates (default Axes coordinates).
For example, to put the legend's upper right hand corner in the
center of the axes the following keywords can be used::
loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncol : integer
The number of columns that the legend has. Default is 1.
prop : None or :class:`matplotlib.font_manager.FontProperties` or dict
The font properties of the legend. If None (default), the current
:data:`matplotlib.rcParams` will be used.
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
Controls 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.
numpoints : None or int
The number of marker points in the legend when creating a legend
entry for a `.Line2D` (line).
Default is ``None``, which will take the value from
:rc:`legend.numpoints`.
scatterpoints : None or int
The number of marker points in the legend when creating
a legend entry for a `.PathCollection` (scatter plot).
Default is ``None``, which will take the value from
:rc:`legend.scatterpoints`.
scatteryoffsets : iterable of floats
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]``. Default is ``[0.375, 0.5, 0.3125]``.
markerscale : None or int or float
The relative size of legend markers compared with the originally
drawn ones.
Default is ``None``, which will take the value from
:rc:`legend.markerscale`.
markerfirst : bool
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.
Default is *True*.
frameon : None or bool
Control whether the legend should be drawn on a patch
(frame).
Default is ``None``, which will take the value from
:rc:`legend.frameon`.
fancybox : None or bool
Control whether round edges should be enabled around the
:class:`~matplotlib.patches.FancyBboxPatch` which makes up the
legend's background.
Default is ``None``, which will take the value from
:rc:`legend.fancybox`.
shadow : None or bool
Control whether to draw a shadow behind the legend.
Default is ``None``, which will take the value from
:rc:`legend.shadow`.
framealpha : None or float
Control the alpha transparency of the legend's background.
Default is ``None``, which will take the value from
:rc:`legend.framealpha`. If shadow is activated and
*framealpha* is ``None``, the default value is ignored.
facecolor : None or "inherit" or a color spec
Control the legend's background color.
Default is ``None``, which will take the value from
:rc:`legend.facecolor`. If ``"inherit"``, it will take
:rc:`axes.facecolor`.
edgecolor : None or "inherit" or a color spec
Control the legend's background patch edge color.
Default is ``None``, which will take the value from
:rc:`legend.edgecolor` If ``"inherit"``, it will take
:rc:`axes.edgecolor`.
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_transform : None or :class:`matplotlib.transforms.Transform`
The transform for the bounding box (`bbox_to_anchor`). For a value
of ``None`` (default) the Axes'
:data:`~matplotlib.axes.Axes.transAxes` transform will be used.
title : str or None
The legend's title. Default is no title (``None``).
borderpad : float or None
The fractional whitespace inside the legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderpad`.
labelspacing : float or None
The vertical space between the legend entries.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.labelspacing`.
handlelength : float or None
The length of the legend handles.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handlelength`.
handletextpad : float or None
The pad between the legend handle and text.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handletextpad`.
borderaxespad : float or None
The pad between the axes and legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderaxespad`.
columnspacing : float or None
The spacing between columns.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.columnspacing`.
handler_map : dict or None
The custom dictionary mapping instances or types to a legend
handler. This `handler_map` updates the default handler map
found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
Returns
-------
:class:`matplotlib.legend.Legend` instance
Notes
-----
Not all kinds of artist are supported by the legend command. See
:doc:`/tutorials/intermediate/legend_guide` for details.
Examples
--------
.. plot:: gallery/api/legend.py
- To exclude one or more elements from the legend,pass no label or label='nolegend')
Annotations and drawing on a subplot
In addition to the standard plot types,you may wish to draw your own plot annotations,which could consist of text,arrows,or other shapes.You can add annotations and text using the text
,arrow
and annotate
functions.text
draws text at given coordinates(x,y) on the plot with optional custom styling.
from datetime import datetime
fig=plt.figure()
<IPython.core.display.Javascript object>
ax=fig.add_subplot(1,1,1)
import pandas as pd
data=pd.read_csv(r'.\pydata-book-2nd-edition\examples\spx.csv',index_col=0,parse_dates=True)
type(data)
pandas.core.frame.DataFrame
data.head()
SPX | |
---|---|
1990-02-01 | 328.79 |
1990-02-02 | 330.92 |
1990-02-05 | 331.85 |
1990-02-06 | 329.66 |
1990-02-07 | 333.75 |
spx=data['SPX']
spx.plot(ax=ax,style='k-')
<matplotlib.axes._subplots.AxesSubplot at 0x2ead7a5ada0>
crisis_data=[(datetime(2007,10,11),'peak of bull market'),
(datetime(2008,3,12),'Bear stearns fails'),
(datetime(2008,9,15),'Lehman Bankruptcy')]
for date,label in crisis_data:
ax.annotate(label,xy=(date,spx.asof(date)+75),xytext=(date,spx.asof(date)+225),
arrowprops=dict(facecolor='black',headwidth=4,width=2,headlength=4),
horizontalalignment='left',
verticalalignment='top')
ax.set_xlim(['1/1/2007','1/1/2011'])
(732677.0, 734138.0)
ax.set_ylim([600,1800])
(600, 1800)
ax.set_title('Important dates in the 2008-2009 financial crisis')
Text(0.5,1,'Important dates in the 2008-2009 financial crisis')
help(ax.annotate)
Help on method annotate in module matplotlib.axes._axes:
annotate(*args, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
Annotate the point ``xy`` with text ``s``.
Additional kwargs are passed to `~matplotlib.text.Text`.
Parameters
----------
s : str
The text of the annotation
xy : iterable
Length 2 sequence specifying the *(x,y)* point to annotate
xytext : iterable, optional
Length 2 sequence specifying the *(x,y)* to place the text
at. If None, defaults to ``xy``.
xycoords : str, Artist, Transform, callable or tuple, optional
The coordinate system that ``xy`` is given in.
For a `str` the allowed values are:
================= ===============================================
Property Description
================= ===============================================
'figure points' points from the lower left of the figure
'figure pixels' pixels from the lower left of the figure
'figure fraction' fraction of figure from lower left
'axes points' points from lower left corner of axes
'axes pixels' pixels from lower left corner of axes
'axes fraction' fraction of axes from lower left
'data' use the coordinate system of the object being
annotated (default)
'polar' *(theta,r)* if not native 'data' coordinates
================= ===============================================
If a `~matplotlib.artist.Artist` object is passed in the units are
fraction if it's bounding box.
If a `~matplotlib.transforms.Transform` object is passed
in use that to transform ``xy`` to screen coordinates
If a callable it must take a
`~matplotlib.backend_bases.RendererBase` object as input
and return a `~matplotlib.transforms.Transform` or
`~matplotlib.transforms.Bbox` object
If a `tuple` must be length 2 tuple of str, `Artist`,
`Transform` or callable objects. The first transform is
used for the *x* coordinate and the second for *y*.
See :ref:`plotting-guide-annotation` for more details.
Defaults to ``'data'``
textcoords : str, `Artist`, `Transform`, callable or tuple, optional
The coordinate system that ``xytext`` is given, which
may be different than the coordinate system used for
``xy``.
All ``xycoords`` values are valid as well as the following
strings:
================= =========================================
Property Description
================= =========================================
'offset points' offset (in points) from the *xy* value
'offset pixels' offset (in pixels) from the *xy* value
================= =========================================
defaults to the input of ``xycoords``
arrowprops : dict, optional
If not None, properties used to draw a
`~matplotlib.patches.FancyArrowPatch` arrow between ``xy`` and
``xytext``.
If `arrowprops` does not contain the key ``'arrowstyle'`` the
allowed keys are:
========== ======================================================
Key Description
========== ======================================================
width the width of the arrow in points
headwidth the width of the base of the arrow head in points
headlength the length of the arrow head in points
shrink fraction of total length to 'shrink' from both ends
? any key to :class:`matplotlib.patches.FancyArrowPatch`
========== ======================================================
If the `arrowprops` contains the key ``'arrowstyle'`` the
above keys are forbidden. The allowed values of
``'arrowstyle'`` are:
============ =============================================
Name Attrs
============ =============================================
``'-'`` None
``'->'`` head_length=0.4,head_width=0.2
``'-['`` widthB=1.0,lengthB=0.2,angleB=None
``'|-|'`` widthA=1.0,widthB=1.0
``'-|>'`` head_length=0.4,head_width=0.2
``'<-'`` head_length=0.4,head_width=0.2
``'<->'`` head_length=0.4,head_width=0.2
``'<|-'`` head_length=0.4,head_width=0.2
``'<|-|>'`` head_length=0.4,head_width=0.2
``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4
``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2
``'wedge'`` tail_width=0.3,shrink_factor=0.5
============ =============================================
Valid keys for `~matplotlib.patches.FancyArrowPatch` are:
=============== ==================================================
Key Description
=============== ==================================================
arrowstyle the arrow style
connectionstyle the connection style
relpos default is (0.5, 0.5)
patchA default is bounding box of the text
patchB default is None
shrinkA default is 2 points
shrinkB default is 2 points
mutation_scale default is text size (in points)
mutation_aspect default is 1.
? any key for :class:`matplotlib.patches.PathPatch`
=============== ==================================================
Defaults to None
annotation_clip : bool, optional
Controls the visibility of the annotation when it goes
outside the axes area.
If `True`, the annotation will only be drawn when the
``xy`` is inside the axes. If `False`, the annotation will
always be drawn regardless of its position.
The default is `None`, which behave as `True` only if
*xycoords* is "data".
Returns
-------
Annotation
help(spx.asof)
Help on method asof in module pandas.core.generic:
asof(where, subset=None) method of pandas.core.series.Series instance
The last row without any NaN is taken (or the last row without
NaN considering only the subset of columns in the case of a DataFrame)
.. versionadded:: 0.19.0 For DataFrame
If there is no good value, NaN is returned for a Series
a Series of NaN values for a DataFrame
Parameters
----------
where : date or array of dates
subset : string or list of strings, default None
if not None use these columns for NaN propagation
Notes
-----
Dates are assumed to be sorted
Raises if this is not the case
Returns
-------
where is scalar
- value or NaN if input is Series
- Series if input is DataFrame
where is Index: same shape object as input
See Also
--------
merge_asof
spx.asof('1990-02-01')
328.79
spx
1990-02-01 328.79
1990-02-02 330.92
1990-02-05 331.85
1990-02-06 329.66
1990-02-07 333.75
1990-02-08 332.96
1990-02-09 333.62
1990-02-12 330.08
1990-02-13 331.02
1990-02-14 332.01
1990-02-15 334.89
1990-02-16 332.72
1990-02-20 327.99
1990-02-21 327.67
1990-02-22 325.70
1990-02-23 324.15
1990-02-26 328.67
1990-02-27 330.26
1990-02-28 331.89
1990-03-01 332.74
1990-03-02 335.54
1990-03-05 333.74
1990-03-06 337.93
1990-03-07 336.95
1990-03-08 340.27
1990-03-09 337.93
1990-03-12 338.67
1990-03-13 336.00
1990-03-14 336.87
1990-03-15 338.07
...
2011-09-02 1173.97
2011-09-06 1165.24
2011-09-07 1198.62
2011-09-08 1185.90
2011-09-09 1154.23
2011-09-12 1162.27
2011-09-13 1172.87
2011-09-14 1188.68
2011-09-15 1209.11
2011-09-16 1216.01
2011-09-19 1204.09
2011-09-20 1202.09
2011-09-21 1166.76
2011-09-22 1129.56
2011-09-23 1136.43
2011-09-26 1162.95
2011-09-27 1175.38
2011-09-28 1151.06
2011-09-29 1160.40
2011-09-30 1131.42
2011-10-03 1099.23
2011-10-04 1123.95
2011-10-05 1144.03
2011-10-06 1164.97
2011-10-07 1155.46
2011-10-10 1194.89
2011-10-11 1195.54
2011-10-12 1207.25
2011-10-13 1203.66
2011-10-14 1224.58
Name: SPX, Length: 5472, dtype: float64
datetime(1991,5,3)
datetime.datetime(1991, 5, 3, 0, 0)
Drawing shapes requires some more care.matplotlib has objects that represent many common shapes,referred to as patches
.Some of these ,like Rectangle
,and Circle
,are found in matplotlib.pyplot
,but the full set is located in matplotlib.patches
.
To add a shape to a plot,you can create the patch object shp
,and add it to a subplot by calling ax.add_patch(shp)
.
fig=plt.figure()
<IPython.core.display.Javascript object>
ax=fig.add_subplot(1,1,1)
help(plt.Rectangle)
Help on class Rectangle in module matplotlib.patches:
class Rectangle(Patch)
| Rectangle(xy, width, height, angle=0.0, **kwargs)
|
| Draw a rectangle with lower left at *xy* = (*x*, *y*) with
| specified *width*, *height* and rotation *angle*.
|
| Method resolution order:
| Rectangle
| Patch
| matplotlib.artist.Artist
| builtins.object
|
| Methods defined here:
|
| __init__(self, xy, width, height, angle=0.0, **kwargs)
| Parameters
| ----------
| xy: length-2 tuple
| The bottom and left rectangle coordinates
| width:
| Rectangle width
| height:
| Rectangle height
| angle: float, optional
| rotation in degrees anti-clockwise about *xy* (default is 0.0)
| fill: bool, optional
| Whether to fill the rectangle (default is ``True``)
|
| Notes
| -----
| Valid kwargs are:
| 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: float or None
| animated: bool
| antialiased or aa: bool or None
| capstyle: ['butt' | 'round' | 'projecting']
| clip_box: a `.Bbox` instance
| clip_on: bool
| clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
| color: matplotlib color spec
| contains: a callable function
| edgecolor or ec: mpl color spec, None, 'none', or 'auto'
| facecolor or fc: mpl color spec, or None for default, or 'none' for no color
| figure: a `.Figure` instance
| fill: bool
| gid: an id string
| hatch: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
| joinstyle: ['miter' | 'round' | 'bevel']
| label: object
| linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
| linewidth or lw: float or None for default
| path_effects: `.AbstractPathEffect`
| picker: [None | bool | float | callable]
| rasterized: bool or None
| sketch_params: (scale: float, length: float, randomness: float)
| snap: bool or None
| transform: `.Transform`
| url: a url string
| visible: bool
| zorder: float
|
| __str__(self)
| Return str(self).
|
| get_bbox(self)
|
| get_height(self)
| Return the height of the rectangle
|
| get_patch_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| takes patch coordinates to data coordinates.
|
| For example, one may define a patch of a circle which represents a
| radius of 5 by providing coordinates for a unit circle, and a
| transform which scales the coordinates (the patch coordinate) by 5.
|
| get_path(self)
| Return the vertices of the rectangle
|
| get_width(self)
| Return the width of the rectangle
|
| get_x(self)
| Return the left coord of the rectangle
|
| get_xy(self)
| Return the left and bottom coords of the rectangle
|
| get_y(self)
| Return the bottom coord of the rectangle
|
| set_bounds(self, *args)
| Set the bounds of the rectangle: l,b,w,h
|
| ACCEPTS: (left, bottom, width, height)
|
| set_height(self, h)
| Set the height of the rectangle
|
| set_width(self, w)
| Set the width of the rectangle
|
| set_x(self, x)
| Set the left coord of the rectangle
|
| set_xy(self, xy)
| Set the left and bottom coords of the rectangle
|
| ACCEPTS: 2-item sequence
|
| set_y(self, y)
| Set the bottom coord of the rectangle
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| xy
| Return the left and bottom coords of the rectangle
|
| ----------------------------------------------------------------------
| Methods inherited from Patch:
|
| contains(self, mouseevent, radius=None)
| Test whether the mouse event occurred in the patch.
|
| Returns T/F, {}
|
| contains_point(self, point, radius=None)
| Returns ``True`` if the given *point* is inside the path
| (transformed with its transform attribute).
|
| *radius* allows the path to be made slightly larger or smaller.
|
| contains_points(self, points, radius=None)
| Returns a bool array which is ``True`` if the (closed) path
| contains the corresponding point.
| (transformed with its transform attribute).
|
| *points* must be Nx2 array.
| *radius* allows the path to be made slightly larger or smaller.
|
| draw(self, renderer)
| Draw the :class:`Patch` to the given *renderer*.
|
| get_aa = get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_capstyle(self)
| Return the current capstyle
|
| get_data_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| maps data coordinates to physical coordinates.
|
| get_ec = get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_extents(self)
| Return a :class:`~matplotlib.transforms.Bbox` object defining
| the axis-aligned extents of the :class:`Patch`.
|
| get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fc = get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fill(self)
| return whether fill is set
|
| get_hatch(self)
| Return the current hatching pattern
|
| get_joinstyle(self)
| Return the current joinstyle
|
| get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_linewidth(self)
| Return the line width in points.
|
| get_ls = get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_lw = get_linewidth(self)
| Return the line width in points.
|
| get_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` applied
| to the :class:`Patch`.
|
| get_verts(self)
| Return a copy of the vertices used in this patch
|
| If the patch contains Bezier curves, the curves will be
| interpolated by line segments. To access the curves as
| curves, use :meth:`get_path`.
|
| get_window_extent(self, renderer=None)
| Get the axes bounding box in display space.
| 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.
|
| set_aa(self, aa)
| alias for set_antialiased
|
| set_alpha(self, alpha)
| Set the alpha tranparency of the patch.
|
| ACCEPTS: float or None
|
| set_antialiased(self, aa)
| Set whether to use antialiased rendering.
|
| Parameters
| ----------
| b : bool or None
| .. ACCEPTS: bool or None
|
| set_capstyle(self, s)
| Set the patch capstyle
|
| ACCEPTS: ['butt' | 'round' | 'projecting']
|
| set_color(self, c)
| Set both the edgecolor and the facecolor.
|
| ACCEPTS: matplotlib color spec
|
| .. seealso::
|
| :meth:`set_facecolor`, :meth:`set_edgecolor`
| For setting the edge or face color individually.
|
| set_ec(self, color)
| alias for set_edgecolor
|
| set_edgecolor(self, color)
| Set the patch edge color
|
| ACCEPTS: mpl color spec, None, 'none', or 'auto'
|
| set_facecolor(self, color)
| Set the patch face color
|
| ACCEPTS: mpl color spec, or None for default, or 'none' for no color
|
| set_fc(self, color)
| alias for set_facecolor
|
| set_fill(self, b)
| Set whether to fill the patch.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_hatch(self, hatch)
| Set the hatching pattern
|
| *hatch* can be one of::
|
| / - diagonal hatching
| \ - back diagonal
| | - vertical
| - - horizontal
| + - crossed
| x - crossed diagonal
| o - small circle
| O - large circle
| . - dots
| * - stars
|
| Letters can be combined, in which case all the specified
| hatchings are done. If same letter repeats, it increases the
| density of hatching of that pattern.
|
| Hatching is supported in the PostScript, PDF, SVG and Agg
| backends only.
|
| ACCEPTS: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
|
| set_joinstyle(self, s)
| Set the patch joinstyle
|
| ACCEPTS: ['miter' | 'round' | 'bevel']
|
| set_linestyle(self, ls)
| Set the patch linestyle
|
| =========================== =================
| linestyle description
| =========================== =================
| ``'-'`` or ``'solid'`` solid line
| ``'--'`` or ``'dashed'`` dashed line
| ``'-.'`` or ``'dashdot'`` dash-dotted line
| ``':'`` or ``'dotted'`` dotted line
| =========================== =================
|
| Alternatively a dash tuple of the following form can be provided::
|
| (offset, onoffseq),
|
| where ``onoffseq`` is an even length tuple of on and off ink
| in points.
|
| ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |
| (offset, on-off-dash-seq) |
| ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |
| ``' '`` | ``''``]
|
| Parameters
| ----------
| ls : { '-', '--', '-.', ':'} and more see description
| The line style.
|
| set_linewidth(self, w)
| Set the patch linewidth in points
|
| ACCEPTS: float or None for default
|
| set_ls(self, ls)
| alias for set_linestyle
|
| set_lw(self, lw)
| alias for set_linewidth
|
| update_from(self, other)
| Updates this :class:`Patch` from the properties of *other*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Patch:
|
| fill
| return whether fill is set
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Patch:
|
| validCap = ('butt', 'round', 'projecting')
|
| validJoin = ('miter', 'round', 'bevel')
|
| zorder = 1
|
| ----------------------------------------------------------------------
| Methods inherited from matplotlib.artist.Artist:
|
| __getstate__(self)
|
| 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.
|
| format_cursor_data(self, data)
| Return *cursor data* string formatted.
|
| 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_children(self)
| Return a list of the child :class:`Artist`s this
| :class:`Artist` contains.
|
| 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_cursor_data(self, event)
| Get the cursor data for a given event.
|
| get_figure(self)
| Return the `.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 whether 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_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 artist's zorder.
|
| have_units(self)
| Return *True* if units are set on the *x* or *y* axes
|
| hitlist(self, event)
| .. deprecated:: 2.2
| The hitlist function was deprecated in version 2.2.
|
| List the children of the artist which contain the mouse event *event*.
|
| is_figure_set(self)
| .. deprecated:: 2.2
| artist.figure is not None
|
| Returns whether the artist is assigned to a `.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)
| Process pick event
|
| 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 property batch setter. Pass *kwargs* to set properties.
|
| set_agg_filter(self, filter_func)
| Set the agg filter.
|
| Parameters
| ----------
| filter_func : callable
| A filter function, which takes a (m, n, 3) float array and a dpi
| value, and returns a (m, n, 3) array.
|
| .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
| and a dpi value, and returns a (m, n, 3) array
|
| set_animated(self, b)
| Set the artist's animation state.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_box(self, clipbox)
| Set the artist's clip `.Bbox`.
|
| Parameters
| ----------
| clipbox : `.Bbox`
| .. ACCEPTS: a `.Bbox` instance
|
| set_clip_on(self, b)
| Set whether artist uses clipping.
|
| When False artists will be visible out side of the axes which
| can lead to unexpected results.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_path(self, path, transform=None)
| Set the artist's clip path, which may be:
|
| - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
| - a :class:`~matplotlib.path.Path` instance, in which case a
| :class:`~matplotlib.transforms.Transform` instance, which will be
| applied to the path before using it for clipping, must be provided;
| or
| - ``None``, to remove a previously set 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: [(`~matplotlib.path.Path`, `.Transform`) | `.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.
|
| Parameters
| ----------
| picker : callable
| .. ACCEPTS: a callable function
|
| set_figure(self, fig)
| Set the `.Figure` instance the artist belongs to.
|
| Parameters
| ----------
| fig : `.Figure`
| .. ACCEPTS: a `.Figure` instance
|
| set_gid(self, gid)
| Sets the (group) id for the artist.
|
| Parameters
| ----------
| gid : str
| .. ACCEPTS: an id string
|
| set_label(self, s)
| Set the label to *s* for auto legend.
|
| Parameters
| ----------
| s : object
| *s* will be converted to a string by calling `str` (`unicode` on
| Py2).
|
| .. ACCEPTS: object
|
| set_path_effects(self, path_effects)
| Set the path effects.
|
| Parameters
| ----------
| path_effects : `.AbstractPathEffect`
| .. ACCEPTS: `.AbstractPathEffect`
|
| 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.
|
| Parameters
| ----------
| picker : None or bool or float or callable
| .. ACCEPTS: [None | bool | float | callable]
|
| set_rasterized(self, rasterized)
| Force rasterized (bitmap) drawing in vector backend output.
|
| Defaults to None, which implies the backend's default behavior.
|
| Parameters
| ----------
| rasterized : bool or None
| .. ACCEPTS: bool or None
|
| set_sketch_params(self, scale=None, length=None, randomness=None)
| Sets 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)
|
| .. ACCEPTS: (scale: float, length: float, randomness: float)
|
| 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.
|
| Parameters
| ----------
| snap : bool or None
| .. ACCEPTS: bool or None
|
| set_transform(self, t)
| Set the artist transform.
|
| Parameters
| ----------
| t : `.Transform`
| .. ACCEPTS: `.Transform`
|
| set_url(self, url)
| Sets the url for the artist.
|
| Parameters
| ----------
| url : str
| .. ACCEPTS: a url string
|
| set_visible(self, b)
| Set the artist's visibility.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_zorder(self, level)
| Set the zorder for the artist. Artists with lower zorder
| values are drawn first.
|
| Parameters
| ----------
| level : float
| .. ACCEPTS: float
|
| update(self, props)
| Update this artist's properties from the dictionary *prop*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from matplotlib.artist.Artist:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| axes
| The :class:`~matplotlib.axes.Axes` instance the artist
| resides in, or *None*.
|
| mouseover
|
| stale
| If the artist is 'stale' and needs to be re-drawn for the output to
| match the internal state of the artist.
|
| sticky_edges
| `x` and `y` sticky edge lists.
|
| 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 usecase is histograms,
| where one usually expects no margin on the bottom edge (0) of the
| histogram.
|
| 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)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from matplotlib.artist.Artist:
|
| aname = 'Artist'
help(plt.Circle)
Help on class Circle in module matplotlib.patches:
class Circle(Ellipse)
| Circle(xy, radius=5, **kwargs)
|
| A circle patch.
|
| Method resolution order:
| Circle
| Ellipse
| Patch
| matplotlib.artist.Artist
| builtins.object
|
| Methods defined here:
|
| __init__(self, xy, radius=5, **kwargs)
| Create true circle at center *xy* = (*x*, *y*) with given
| *radius*. Unlike :class:`~matplotlib.patches.CirclePolygon`
| which is a polygonal approximation, this uses Bézier splines
| and is much closer to a scale-free circle.
|
| Valid kwargs are:
| 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: float or None
| animated: bool
| antialiased or aa: bool or None
| capstyle: ['butt' | 'round' | 'projecting']
| clip_box: a `.Bbox` instance
| clip_on: bool
| clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
| color: matplotlib color spec
| contains: a callable function
| edgecolor or ec: mpl color spec, None, 'none', or 'auto'
| facecolor or fc: mpl color spec, or None for default, or 'none' for no color
| figure: a `.Figure` instance
| fill: bool
| gid: an id string
| hatch: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
| joinstyle: ['miter' | 'round' | 'bevel']
| label: object
| linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
| linewidth or lw: float or None for default
| path_effects: `.AbstractPathEffect`
| picker: [None | bool | float | callable]
| rasterized: bool or None
| sketch_params: (scale: float, length: float, randomness: float)
| snap: bool or None
| transform: `.Transform`
| url: a url string
| visible: bool
| zorder: float
|
| __str__(self)
| Return str(self).
|
| get_radius(self)
| return the radius of the circle
|
| set_radius(self, radius)
| Set the radius of the circle
|
| ACCEPTS: float
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| radius
| return the radius of the circle
|
| ----------------------------------------------------------------------
| Methods inherited from Ellipse:
|
| get_patch_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| takes patch coordinates to data coordinates.
|
| For example, one may define a patch of a circle which represents a
| radius of 5 by providing coordinates for a unit circle, and a
| transform which scales the coordinates (the patch coordinate) by 5.
|
| get_path(self)
| Return the vertices of the rectangle
|
| ----------------------------------------------------------------------
| Methods inherited from Patch:
|
| contains(self, mouseevent, radius=None)
| Test whether the mouse event occurred in the patch.
|
| Returns T/F, {}
|
| contains_point(self, point, radius=None)
| Returns ``True`` if the given *point* is inside the path
| (transformed with its transform attribute).
|
| *radius* allows the path to be made slightly larger or smaller.
|
| contains_points(self, points, radius=None)
| Returns a bool array which is ``True`` if the (closed) path
| contains the corresponding point.
| (transformed with its transform attribute).
|
| *points* must be Nx2 array.
| *radius* allows the path to be made slightly larger or smaller.
|
| draw(self, renderer)
| Draw the :class:`Patch` to the given *renderer*.
|
| get_aa = get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_capstyle(self)
| Return the current capstyle
|
| get_data_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| maps data coordinates to physical coordinates.
|
| get_ec = get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_extents(self)
| Return a :class:`~matplotlib.transforms.Bbox` object defining
| the axis-aligned extents of the :class:`Patch`.
|
| get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fc = get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fill(self)
| return whether fill is set
|
| get_hatch(self)
| Return the current hatching pattern
|
| get_joinstyle(self)
| Return the current joinstyle
|
| get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_linewidth(self)
| Return the line width in points.
|
| get_ls = get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_lw = get_linewidth(self)
| Return the line width in points.
|
| get_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` applied
| to the :class:`Patch`.
|
| get_verts(self)
| Return a copy of the vertices used in this patch
|
| If the patch contains Bezier curves, the curves will be
| interpolated by line segments. To access the curves as
| curves, use :meth:`get_path`.
|
| get_window_extent(self, renderer=None)
| Get the axes bounding box in display space.
| 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.
|
| set_aa(self, aa)
| alias for set_antialiased
|
| set_alpha(self, alpha)
| Set the alpha tranparency of the patch.
|
| ACCEPTS: float or None
|
| set_antialiased(self, aa)
| Set whether to use antialiased rendering.
|
| Parameters
| ----------
| b : bool or None
| .. ACCEPTS: bool or None
|
| set_capstyle(self, s)
| Set the patch capstyle
|
| ACCEPTS: ['butt' | 'round' | 'projecting']
|
| set_color(self, c)
| Set both the edgecolor and the facecolor.
|
| ACCEPTS: matplotlib color spec
|
| .. seealso::
|
| :meth:`set_facecolor`, :meth:`set_edgecolor`
| For setting the edge or face color individually.
|
| set_ec(self, color)
| alias for set_edgecolor
|
| set_edgecolor(self, color)
| Set the patch edge color
|
| ACCEPTS: mpl color spec, None, 'none', or 'auto'
|
| set_facecolor(self, color)
| Set the patch face color
|
| ACCEPTS: mpl color spec, or None for default, or 'none' for no color
|
| set_fc(self, color)
| alias for set_facecolor
|
| set_fill(self, b)
| Set whether to fill the patch.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_hatch(self, hatch)
| Set the hatching pattern
|
| *hatch* can be one of::
|
| / - diagonal hatching
| \ - back diagonal
| | - vertical
| - - horizontal
| + - crossed
| x - crossed diagonal
| o - small circle
| O - large circle
| . - dots
| * - stars
|
| Letters can be combined, in which case all the specified
| hatchings are done. If same letter repeats, it increases the
| density of hatching of that pattern.
|
| Hatching is supported in the PostScript, PDF, SVG and Agg
| backends only.
|
| ACCEPTS: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
|
| set_joinstyle(self, s)
| Set the patch joinstyle
|
| ACCEPTS: ['miter' | 'round' | 'bevel']
|
| set_linestyle(self, ls)
| Set the patch linestyle
|
| =========================== =================
| linestyle description
| =========================== =================
| ``'-'`` or ``'solid'`` solid line
| ``'--'`` or ``'dashed'`` dashed line
| ``'-.'`` or ``'dashdot'`` dash-dotted line
| ``':'`` or ``'dotted'`` dotted line
| =========================== =================
|
| Alternatively a dash tuple of the following form can be provided::
|
| (offset, onoffseq),
|
| where ``onoffseq`` is an even length tuple of on and off ink
| in points.
|
| ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |
| (offset, on-off-dash-seq) |
| ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |
| ``' '`` | ``''``]
|
| Parameters
| ----------
| ls : { '-', '--', '-.', ':'} and more see description
| The line style.
|
| set_linewidth(self, w)
| Set the patch linewidth in points
|
| ACCEPTS: float or None for default
|
| set_ls(self, ls)
| alias for set_linestyle
|
| set_lw(self, lw)
| alias for set_linewidth
|
| update_from(self, other)
| Updates this :class:`Patch` from the properties of *other*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Patch:
|
| fill
| return whether fill is set
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Patch:
|
| validCap = ('butt', 'round', 'projecting')
|
| validJoin = ('miter', 'round', 'bevel')
|
| zorder = 1
|
| ----------------------------------------------------------------------
| Methods inherited from matplotlib.artist.Artist:
|
| __getstate__(self)
|
| 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.
|
| format_cursor_data(self, data)
| Return *cursor data* string formatted.
|
| 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_children(self)
| Return a list of the child :class:`Artist`s this
| :class:`Artist` contains.
|
| 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_cursor_data(self, event)
| Get the cursor data for a given event.
|
| get_figure(self)
| Return the `.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 whether 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_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 artist's zorder.
|
| have_units(self)
| Return *True* if units are set on the *x* or *y* axes
|
| hitlist(self, event)
| .. deprecated:: 2.2
| The hitlist function was deprecated in version 2.2.
|
| List the children of the artist which contain the mouse event *event*.
|
| is_figure_set(self)
| .. deprecated:: 2.2
| artist.figure is not None
|
| Returns whether the artist is assigned to a `.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)
| Process pick event
|
| 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 property batch setter. Pass *kwargs* to set properties.
|
| set_agg_filter(self, filter_func)
| Set the agg filter.
|
| Parameters
| ----------
| filter_func : callable
| A filter function, which takes a (m, n, 3) float array and a dpi
| value, and returns a (m, n, 3) array.
|
| .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
| and a dpi value, and returns a (m, n, 3) array
|
| set_animated(self, b)
| Set the artist's animation state.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_box(self, clipbox)
| Set the artist's clip `.Bbox`.
|
| Parameters
| ----------
| clipbox : `.Bbox`
| .. ACCEPTS: a `.Bbox` instance
|
| set_clip_on(self, b)
| Set whether artist uses clipping.
|
| When False artists will be visible out side of the axes which
| can lead to unexpected results.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_path(self, path, transform=None)
| Set the artist's clip path, which may be:
|
| - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
| - a :class:`~matplotlib.path.Path` instance, in which case a
| :class:`~matplotlib.transforms.Transform` instance, which will be
| applied to the path before using it for clipping, must be provided;
| or
| - ``None``, to remove a previously set 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: [(`~matplotlib.path.Path`, `.Transform`) | `.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.
|
| Parameters
| ----------
| picker : callable
| .. ACCEPTS: a callable function
|
| set_figure(self, fig)
| Set the `.Figure` instance the artist belongs to.
|
| Parameters
| ----------
| fig : `.Figure`
| .. ACCEPTS: a `.Figure` instance
|
| set_gid(self, gid)
| Sets the (group) id for the artist.
|
| Parameters
| ----------
| gid : str
| .. ACCEPTS: an id string
|
| set_label(self, s)
| Set the label to *s* for auto legend.
|
| Parameters
| ----------
| s : object
| *s* will be converted to a string by calling `str` (`unicode` on
| Py2).
|
| .. ACCEPTS: object
|
| set_path_effects(self, path_effects)
| Set the path effects.
|
| Parameters
| ----------
| path_effects : `.AbstractPathEffect`
| .. ACCEPTS: `.AbstractPathEffect`
|
| 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.
|
| Parameters
| ----------
| picker : None or bool or float or callable
| .. ACCEPTS: [None | bool | float | callable]
|
| set_rasterized(self, rasterized)
| Force rasterized (bitmap) drawing in vector backend output.
|
| Defaults to None, which implies the backend's default behavior.
|
| Parameters
| ----------
| rasterized : bool or None
| .. ACCEPTS: bool or None
|
| set_sketch_params(self, scale=None, length=None, randomness=None)
| Sets 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)
|
| .. ACCEPTS: (scale: float, length: float, randomness: float)
|
| 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.
|
| Parameters
| ----------
| snap : bool or None
| .. ACCEPTS: bool or None
|
| set_transform(self, t)
| Set the artist transform.
|
| Parameters
| ----------
| t : `.Transform`
| .. ACCEPTS: `.Transform`
|
| set_url(self, url)
| Sets the url for the artist.
|
| Parameters
| ----------
| url : str
| .. ACCEPTS: a url string
|
| set_visible(self, b)
| Set the artist's visibility.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_zorder(self, level)
| Set the zorder for the artist. Artists with lower zorder
| values are drawn first.
|
| Parameters
| ----------
| level : float
| .. ACCEPTS: float
|
| update(self, props)
| Update this artist's properties from the dictionary *prop*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from matplotlib.artist.Artist:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| axes
| The :class:`~matplotlib.axes.Axes` instance the artist
| resides in, or *None*.
|
| mouseover
|
| stale
| If the artist is 'stale' and needs to be re-drawn for the output to
| match the internal state of the artist.
|
| sticky_edges
| `x` and `y` sticky edge lists.
|
| 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 usecase is histograms,
| where one usually expects no margin on the bottom edge (0) of the
| histogram.
|
| 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)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from matplotlib.artist.Artist:
|
| aname = 'Artist'
help(plt.Polygon)
Help on class Polygon in module matplotlib.patches:
class Polygon(Patch)
| Polygon(xy, closed=True, **kwargs)
|
| A general polygon patch.
|
| Method resolution order:
| Polygon
| Patch
| matplotlib.artist.Artist
| builtins.object
|
| Methods defined here:
|
| __init__(self, xy, closed=True, **kwargs)
| *xy* is a numpy array with shape Nx2.
|
| If *closed* is *True*, the polygon will be closed so the
| starting and ending points are the same.
|
| Valid kwargs are:
| 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: float or None
| animated: bool
| antialiased or aa: bool or None
| capstyle: ['butt' | 'round' | 'projecting']
| clip_box: a `.Bbox` instance
| clip_on: bool
| clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
| color: matplotlib color spec
| contains: a callable function
| edgecolor or ec: mpl color spec, None, 'none', or 'auto'
| facecolor or fc: mpl color spec, or None for default, or 'none' for no color
| figure: a `.Figure` instance
| fill: bool
| gid: an id string
| hatch: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
| joinstyle: ['miter' | 'round' | 'bevel']
| label: object
| linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
| linewidth or lw: float or None for default
| path_effects: `.AbstractPathEffect`
| picker: [None | bool | float | callable]
| rasterized: bool or None
| sketch_params: (scale: float, length: float, randomness: float)
| snap: bool or None
| transform: `.Transform`
| url: a url string
| visible: bool
| zorder: float
|
| .. seealso::
|
| :class:`Patch`
| For additional kwargs
|
| __str__(self)
| Return str(self).
|
| get_closed(self)
| Returns if the polygon is closed
|
| Returns
| -------
| closed : bool
| If the path is closed
|
| get_path(self)
| Get the path of the polygon
|
| Returns
| -------
| path : Path
| The :class:`~matplotlib.path.Path` object for
| the polygon
|
| get_xy(self)
| Get the vertices of the path
|
| Returns
| -------
| vertices : numpy array
| The coordinates of the vertices as a Nx2
| ndarray.
|
| set_closed(self, closed)
| Set if the polygon is closed
|
| Parameters
| ----------
| closed : bool
| True if the polygon is closed
|
| set_xy(self, xy)
| Set the vertices of the polygon
|
| Parameters
| ----------
| xy : numpy array or iterable of pairs
| The coordinates of the vertices as a Nx2
| ndarray or iterable of pairs.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| xy
| Set/get the vertices of the polygon. This property is
| provided for backward compatibility with matplotlib 0.91.x
| only. New code should use
| :meth:`~matplotlib.patches.Polygon.get_xy` and
| :meth:`~matplotlib.patches.Polygon.set_xy` instead.
|
| ----------------------------------------------------------------------
| Methods inherited from Patch:
|
| contains(self, mouseevent, radius=None)
| Test whether the mouse event occurred in the patch.
|
| Returns T/F, {}
|
| contains_point(self, point, radius=None)
| Returns ``True`` if the given *point* is inside the path
| (transformed with its transform attribute).
|
| *radius* allows the path to be made slightly larger or smaller.
|
| contains_points(self, points, radius=None)
| Returns a bool array which is ``True`` if the (closed) path
| contains the corresponding point.
| (transformed with its transform attribute).
|
| *points* must be Nx2 array.
| *radius* allows the path to be made slightly larger or smaller.
|
| draw(self, renderer)
| Draw the :class:`Patch` to the given *renderer*.
|
| get_aa = get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_antialiased(self)
| Returns True if the :class:`Patch` is to be drawn with antialiasing.
|
| get_capstyle(self)
| Return the current capstyle
|
| get_data_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| maps data coordinates to physical coordinates.
|
| get_ec = get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_edgecolor(self)
| Return the edge color of the :class:`Patch`.
|
| get_extents(self)
| Return a :class:`~matplotlib.transforms.Bbox` object defining
| the axis-aligned extents of the :class:`Patch`.
|
| get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fc = get_facecolor(self)
| Return the face color of the :class:`Patch`.
|
| get_fill(self)
| return whether fill is set
|
| get_hatch(self)
| Return the current hatching pattern
|
| get_joinstyle(self)
| Return the current joinstyle
|
| get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_linewidth(self)
| Return the line width in points.
|
| get_ls = get_linestyle(self)
| Return the linestyle. Will be one of ['solid' | 'dashed' |
| 'dashdot' | 'dotted']
|
| get_lw = get_linewidth(self)
| Return the line width in points.
|
| get_patch_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` instance which
| takes patch coordinates to data coordinates.
|
| For example, one may define a patch of a circle which represents a
| radius of 5 by providing coordinates for a unit circle, and a
| transform which scales the coordinates (the patch coordinate) by 5.
|
| get_transform(self)
| Return the :class:`~matplotlib.transforms.Transform` applied
| to the :class:`Patch`.
|
| get_verts(self)
| Return a copy of the vertices used in this patch
|
| If the patch contains Bezier curves, the curves will be
| interpolated by line segments. To access the curves as
| curves, use :meth:`get_path`.
|
| get_window_extent(self, renderer=None)
| Get the axes bounding box in display space.
| 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.
|
| set_aa(self, aa)
| alias for set_antialiased
|
| set_alpha(self, alpha)
| Set the alpha tranparency of the patch.
|
| ACCEPTS: float or None
|
| set_antialiased(self, aa)
| Set whether to use antialiased rendering.
|
| Parameters
| ----------
| b : bool or None
| .. ACCEPTS: bool or None
|
| set_capstyle(self, s)
| Set the patch capstyle
|
| ACCEPTS: ['butt' | 'round' | 'projecting']
|
| set_color(self, c)
| Set both the edgecolor and the facecolor.
|
| ACCEPTS: matplotlib color spec
|
| .. seealso::
|
| :meth:`set_facecolor`, :meth:`set_edgecolor`
| For setting the edge or face color individually.
|
| set_ec(self, color)
| alias for set_edgecolor
|
| set_edgecolor(self, color)
| Set the patch edge color
|
| ACCEPTS: mpl color spec, None, 'none', or 'auto'
|
| set_facecolor(self, color)
| Set the patch face color
|
| ACCEPTS: mpl color spec, or None for default, or 'none' for no color
|
| set_fc(self, color)
| alias for set_facecolor
|
| set_fill(self, b)
| Set whether to fill the patch.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_hatch(self, hatch)
| Set the hatching pattern
|
| *hatch* can be one of::
|
| / - diagonal hatching
| \ - back diagonal
| | - vertical
| - - horizontal
| + - crossed
| x - crossed diagonal
| o - small circle
| O - large circle
| . - dots
| * - stars
|
| Letters can be combined, in which case all the specified
| hatchings are done. If same letter repeats, it increases the
| density of hatching of that pattern.
|
| Hatching is supported in the PostScript, PDF, SVG and Agg
| backends only.
|
| ACCEPTS: ['/' | '\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']
|
| set_joinstyle(self, s)
| Set the patch joinstyle
|
| ACCEPTS: ['miter' | 'round' | 'bevel']
|
| set_linestyle(self, ls)
| Set the patch linestyle
|
| =========================== =================
| linestyle description
| =========================== =================
| ``'-'`` or ``'solid'`` solid line
| ``'--'`` or ``'dashed'`` dashed line
| ``'-.'`` or ``'dashdot'`` dash-dotted line
| ``':'`` or ``'dotted'`` dotted line
| =========================== =================
|
| Alternatively a dash tuple of the following form can be provided::
|
| (offset, onoffseq),
|
| where ``onoffseq`` is an even length tuple of on and off ink
| in points.
|
| ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' |
| (offset, on-off-dash-seq) |
| ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` |
| ``' '`` | ``''``]
|
| Parameters
| ----------
| ls : { '-', '--', '-.', ':'} and more see description
| The line style.
|
| set_linewidth(self, w)
| Set the patch linewidth in points
|
| ACCEPTS: float or None for default
|
| set_ls(self, ls)
| alias for set_linestyle
|
| set_lw(self, lw)
| alias for set_linewidth
|
| update_from(self, other)
| Updates this :class:`Patch` from the properties of *other*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Patch:
|
| fill
| return whether fill is set
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Patch:
|
| validCap = ('butt', 'round', 'projecting')
|
| validJoin = ('miter', 'round', 'bevel')
|
| zorder = 1
|
| ----------------------------------------------------------------------
| Methods inherited from matplotlib.artist.Artist:
|
| __getstate__(self)
|
| 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.
|
| format_cursor_data(self, data)
| Return *cursor data* string formatted.
|
| 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_children(self)
| Return a list of the child :class:`Artist`s this
| :class:`Artist` contains.
|
| 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_cursor_data(self, event)
| Get the cursor data for a given event.
|
| get_figure(self)
| Return the `.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 whether 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_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 artist's zorder.
|
| have_units(self)
| Return *True* if units are set on the *x* or *y* axes
|
| hitlist(self, event)
| .. deprecated:: 2.2
| The hitlist function was deprecated in version 2.2.
|
| List the children of the artist which contain the mouse event *event*.
|
| is_figure_set(self)
| .. deprecated:: 2.2
| artist.figure is not None
|
| Returns whether the artist is assigned to a `.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)
| Process pick event
|
| 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 property batch setter. Pass *kwargs* to set properties.
|
| set_agg_filter(self, filter_func)
| Set the agg filter.
|
| Parameters
| ----------
| filter_func : callable
| A filter function, which takes a (m, n, 3) float array and a dpi
| value, and returns a (m, n, 3) array.
|
| .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
| and a dpi value, and returns a (m, n, 3) array
|
| set_animated(self, b)
| Set the artist's animation state.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_box(self, clipbox)
| Set the artist's clip `.Bbox`.
|
| Parameters
| ----------
| clipbox : `.Bbox`
| .. ACCEPTS: a `.Bbox` instance
|
| set_clip_on(self, b)
| Set whether artist uses clipping.
|
| When False artists will be visible out side of the axes which
| can lead to unexpected results.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_clip_path(self, path, transform=None)
| Set the artist's clip path, which may be:
|
| - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
| - a :class:`~matplotlib.path.Path` instance, in which case a
| :class:`~matplotlib.transforms.Transform` instance, which will be
| applied to the path before using it for clipping, must be provided;
| or
| - ``None``, to remove a previously set 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: [(`~matplotlib.path.Path`, `.Transform`) | `.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.
|
| Parameters
| ----------
| picker : callable
| .. ACCEPTS: a callable function
|
| set_figure(self, fig)
| Set the `.Figure` instance the artist belongs to.
|
| Parameters
| ----------
| fig : `.Figure`
| .. ACCEPTS: a `.Figure` instance
|
| set_gid(self, gid)
| Sets the (group) id for the artist.
|
| Parameters
| ----------
| gid : str
| .. ACCEPTS: an id string
|
| set_label(self, s)
| Set the label to *s* for auto legend.
|
| Parameters
| ----------
| s : object
| *s* will be converted to a string by calling `str` (`unicode` on
| Py2).
|
| .. ACCEPTS: object
|
| set_path_effects(self, path_effects)
| Set the path effects.
|
| Parameters
| ----------
| path_effects : `.AbstractPathEffect`
| .. ACCEPTS: `.AbstractPathEffect`
|
| 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.
|
| Parameters
| ----------
| picker : None or bool or float or callable
| .. ACCEPTS: [None | bool | float | callable]
|
| set_rasterized(self, rasterized)
| Force rasterized (bitmap) drawing in vector backend output.
|
| Defaults to None, which implies the backend's default behavior.
|
| Parameters
| ----------
| rasterized : bool or None
| .. ACCEPTS: bool or None
|
| set_sketch_params(self, scale=None, length=None, randomness=None)
| Sets 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)
|
| .. ACCEPTS: (scale: float, length: float, randomness: float)
|
| 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.
|
| Parameters
| ----------
| snap : bool or None
| .. ACCEPTS: bool or None
|
| set_transform(self, t)
| Set the artist transform.
|
| Parameters
| ----------
| t : `.Transform`
| .. ACCEPTS: `.Transform`
|
| set_url(self, url)
| Sets the url for the artist.
|
| Parameters
| ----------
| url : str
| .. ACCEPTS: a url string
|
| set_visible(self, b)
| Set the artist's visibility.
|
| Parameters
| ----------
| b : bool
| .. ACCEPTS: bool
|
| set_zorder(self, level)
| Set the zorder for the artist. Artists with lower zorder
| values are drawn first.
|
| Parameters
| ----------
| level : float
| .. ACCEPTS: float
|
| update(self, props)
| Update this artist's properties from the dictionary *prop*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from matplotlib.artist.Artist:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| axes
| The :class:`~matplotlib.axes.Axes` instance the artist
| resides in, or *None*.
|
| mouseover
|
| stale
| If the artist is 'stale' and needs to be re-drawn for the output to
| match the internal state of the artist.
|
| sticky_edges
| `x` and `y` sticky edge lists.
|
| 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 usecase is histograms,
| where one usually expects no margin on the bottom edge (0) of the
| histogram.
|
| 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)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from matplotlib.artist.Artist:
|
| aname = 'Artist'
rect=plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.3)
circ=plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)
pgon=plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color='g',alpha=0.5)
ax.add_patch(rect)
<matplotlib.patches.Rectangle at 0x2ead88a90b8>
ax.add_patch(circ)
<matplotlib.patches.Circle at 0x2ead88a9208>
ax.add_patch(pgon)
<matplotlib.patches.Polygon at 0x2ead881acf8>
Saving plots to file
You can save the active figure to file using plt.savefig
.This method is equivalent to the figure objeects' savefig
instance method.The file type is inferred from the file extension.So if you used .pdf
instead,you would get a PDF.
There are a couple of import options:dpi
,which controls the dots-percent-inch resolution,and bbox_inches
,which can trim the whitespace around the actual figure.
savefig
does not have to write to disk;it can also write to any file-like object,such as a BytesIO
:
from io import BytesIO
buffer=BytesIO()
plt.savefig(buffer)
plot_data=buffer.getvalue()
plt.plot(np.random.randn(1000).cumsum(),'k.')
[<matplotlib.lines.Line2D at 0x2ead88e2b38>]
plt.savefig('test.png')
ax.set_ylim([1,10])
(1, 10)
fig=plt.figure()
<IPython.core.display.Javascript object>
ax=fig.add_subplot(111)
for i in range(10):
ax.annotate('',(0,i),(-i*10,i),arrowprops=dict(arrowstyle="->", connectionstyle="arc3"))
ax.set_xlim(-100,0)
(-100, 0)
ax.set_ylim([0,10])
(0, 10)
ax.plot([0,-90],[0,9],'k')
[<matplotlib.lines.Line2D at 0x2ead8bbe550>]
fig.savefig('tesst.pdf')
matplotlib configuration
Nearly all of the default behaviour can be customized via an extensive set of global parameters governingg figure size,subplot spacing,colors,font sizes,grid styles,and so on.One way to modify the configuration programmatically from Python is to use the rc
method;for example,to set the global default figure size to be 10×10,you could enter:
plt.rc('figure',figsize=(10,10))
.
The first argument to rc
is the component you wish to customize,such as figure
,axes
,xtick
,ytick
,grid
,legend
,or many others.After that can follow a sequence of keyword arguments indicating the new parameters.An easy way to write down the options in your program is as a dict:
font_options={'family':'monospace','weight':'bold','size':'small'}
plt.rc('font',**font_options)
Plotting with pandas and seaborn
Line plots
Series and DataFrame each have a plot
attribute for making some basic plot types.By default,plot() makes line plots.
fig1,ax1=plt.subplots(1,1)
<IPython.core.display.Javascript object>
s=pd.Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot.line(ax=ax1,xlim=[0,10])
<matplotlib.axes._subplots.AxesSubplot at 0x2ead8c49518>
help(s.plot)
Help on SeriesPlotMethods in module pandas.plotting._core object:
class SeriesPlotMethods(BasePlotMethods)
| SeriesPlotMethods(data)
|
| Series plotting accessor and method
|
| Examples
| --------
| >>> s.plot.line()
| >>> s.plot.bar()
| >>> s.plot.hist()
|
| Plotting methods can also be accessed by calling the accessor as a method
| with the ``kind`` argument:
| ``s.plot(kind='line')`` is equivalent to ``s.plot.line()``
|
| Method resolution order:
| SeriesPlotMethods
| BasePlotMethods
| pandas.core.base.PandasObject
| pandas.core.base.StringMixin
| pandas.core.accessor.DirNamesMixin
| builtins.object
|
| Methods defined here:
|
| __call__(self, kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)
| Make plots of Series using matplotlib / pylab.
|
| *New in version 0.17.0:* Each plot kind has a corresponding method on the
| ``Series.plot`` accessor:
| ``s.plot(kind='line')`` is equivalent to
| ``s.plot.line()``.
|
| Parameters
| ----------
| data : Series
|
| kind : str
| - 'line' : line plot (default)
| - 'bar' : vertical bar plot
| - 'barh' : horizontal bar plot
| - 'hist' : histogram
| - 'box' : boxplot
| - 'kde' : Kernel Density Estimation plot
| - 'density' : same as 'kde'
| - 'area' : area plot
| - 'pie' : pie plot
|
| ax : matplotlib axes object
| If not passed, uses gca()
| figsize : a tuple (width, height) in inches
| use_index : boolean, default True
| Use index as ticks for x axis
| title : string or list
| Title to use for the plot. If a string is passed, print the string at
| the top of the figure. If a list is passed and `subplots` is True,
| print each item in the list above the corresponding subplot.
| grid : boolean, default None (matlab style default)
| Axis grid lines
| legend : False/True/'reverse'
| Place legend on axis subplots
| style : list or dict
| matplotlib line style per column
| logx : boolean, default False
| Use log scaling on x axis
| logy : boolean, default False
| Use log scaling on y axis
| loglog : boolean, default False
| Use log scaling on both x and y axes
| xticks : sequence
| Values to use for the xticks
| yticks : sequence
| Values to use for the yticks
| xlim : 2-tuple/list
| ylim : 2-tuple/list
| rot : int, default None
| Rotation for ticks (xticks for vertical, yticks for horizontal plots)
| fontsize : int, default None
| Font size for xticks and yticks
| colormap : str or matplotlib colormap object, default None
| Colormap to select colors from. If string, load colormap with that name
| from matplotlib.
| colorbar : boolean, optional
| If True, plot colorbar (only relevant for 'scatter' and 'hexbin' plots)
| position : float
| Specify relative alignments for bar plot layout.
| From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
| table : boolean, Series or DataFrame, default False
| If True, draw a table using the data in the DataFrame and the data will
| be transposed to meet matplotlib's default layout.
| If a Series or DataFrame is passed, use passed data to draw a table.
| yerr : DataFrame, Series, array-like, dict and str
| See :ref:`Plotting with Error Bars <visualization.errorbars>` for
| detail.
| xerr : same types as yerr.
| label : label argument to provide to plot
| secondary_y : boolean or sequence of ints, default False
| If True then y-axis will be on the right
| mark_right : boolean, default True
| When using a secondary_y axis, automatically mark the column
| labels with "(right)" in the legend
| `**kwds` : keywords
| Options to pass to matplotlib plotting method
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| Notes
| -----
|
| - See matplotlib documentation online for more on this subject
| - If `kind` = 'bar' or 'barh', you can specify relative alignments
| for bar plot layout by `position` keyword.
| From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
|
| area(self, **kwds)
| Area plot
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| bar(self, **kwds)
| Vertical bar plot
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| barh(self, **kwds)
| Horizontal bar plot
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| box(self, **kwds)
| Boxplot
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| density = kde(self, bw_method=None, ind=None, **kwds)
|
| hist(self, bins=10, **kwds)
| Histogram
|
| Parameters
| ----------
| bins: integer, default 10
| Number of histogram bins to be used
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| kde(self, bw_method=None, ind=None, **kwds)
| Generate Kernel Density Estimate plot using Gaussian kernels.
|
| In statistics, `kernel density estimation`_ (KDE) is a non-parametric
| way to estimate the probability density function (PDF) of a random
| variable. This function uses Gaussian kernels and includes automatic
| bandwith determination.
|
| .. _kernel density estimation:
| https://en.wikipedia.org/wiki/Kernel_density_estimation
|
| Parameters
| ----------
| bw_method : str, scalar or callable, optional
| The method used to calculate the estimator bandwidth. This can be
| 'scott', 'silverman', a scalar constant or a callable.
| If None (default), 'scott' is used.
| See :class:`scipy.stats.gaussian_kde` for more information.
| ind : NumPy array or integer, optional
| Evaluation points for the estimated PDF. If None (default),
| 1000 equally spaced points are used. If `ind` is a NumPy array, the
| KDE is evaluated at the points passed. If `ind` is an integer,
| `ind` number of equally spaced points are used.
| **kwds : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : matplotlib.axes.Axes or numpy.ndarray of them
|
| See Also
| --------
| scipy.stats.gaussian_kde : Representation of a kernel-density
| estimate using Gaussian kernels. This is the function used
| internally to estimate the PDF.
| DataFrame.plot.kde : Generate a KDE plot for a
| DataFrame.
|
| Examples
| --------
| Given a Series of points randomly sampled from an unknown
| distribution, estimate its PDF using KDE with automatic
| bandwidth determination and plot the results, evaluating them at
| 1000 equally spaced points (default):
|
| .. plot::
| :context: close-figs
|
| >>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5])
| >>> ax = s.plot.kde()
|
| A scalar bandwidth can be specified. Using a small bandwidth value can
| lead to overfitting, while using a large bandwidth value may result
| in underfitting:
|
| .. plot::
| :context: close-figs
|
| >>> ax = s.plot.kde(bw_method=0.3)
|
| .. plot::
| :context: close-figs
|
| >>> ax = s.plot.kde(bw_method=3)
|
| Finally, the `ind` parameter determines the evaluation points for the
| plot of the estimated PDF:
|
| .. plot::
| :context: close-figs
|
| >>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5])
|
| line(self, **kwds)
| Line plot
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| Examples
| --------
|
| .. plot::
| :context: close-figs
|
| >>> s = pd.Series([1, 3, 2])
| >>> s.plot.line()
|
| pie(self, **kwds)
| Pie chart
|
| Parameters
| ----------
| `**kwds` : optional
| Additional keyword arguments are documented in
| :meth:`pandas.Series.plot`.
|
| Returns
| -------
| axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them
|
| ----------------------------------------------------------------------
| Methods inherited from BasePlotMethods:
|
| __init__(self, data)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from pandas.core.base.PandasObject:
|
| __sizeof__(self)
| Generates the total memory usage for an object that returns
| either a value or Series of values
|
| __unicode__(self)
| Return a string representation for a particular object.
|
| Invoked by unicode(obj) in py2 only. Yields a Unicode String in both
| py2/py3.
|
| ----------------------------------------------------------------------
| Methods inherited from pandas.core.base.StringMixin:
|
| __bytes__(self)
| Return a string representation for a particular object.
|
| Invoked by bytes(obj) in py3 only.
| Yields a bytestring in both py2/py3.
|
| __repr__(self)
| Return a string representation for a particular object.
|
| Yields Bytestring in Py2, Unicode String in py3.
|
| __str__(self)
| Return a string representation for a particular Object
|
| Invoked by str(df) in both py2/py3.
| Yields Bytestring in Py2, Unicode String in py3.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pandas.core.base.StringMixin:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from pandas.core.accessor.DirNamesMixin:
|
| __dir__(self)
| Provide method name lookup and completion
| Only provide 'public' methods
def f(x):
return x*10
f(np.arange(10))
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
s = pd.Series([1, 3, 2])
s.plot.line()
<matplotlib.axes._subplots.AxesSubplot at 0x2ead8c49518>
df=pd.DataFrame(np.random.randn(10,4).cumsum(0),columns=['A','B','C','D'],index=np.arange(0,100,10))
df.plot()
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.AxesSubplot at 0x2ead8c96b38>
The plot
attribute contains a 'family' of methods for different plot types.For example,df.plot()
is equivalent to df.plot().line()
.
Bar plots
The plot.bar()
and plot.barh()
make vertical and horizontal bar plots,respectively.
fig,axes=plt.subplots(2,1)
<IPython.core.display.Javascript object>
data=pd.Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[0],color='k',alpha=0.7)
<matplotlib.axes._subplots.AxesSubplot at 0x2ead8cf0400>
data.plot.barh(ax=axes[1],color='k',alpha=0.7)
<matplotlib.axes._subplots.AxesSubplot at 0x2ead8d21a20>
df=pd.DataFrame(np.random.randn(6,4),index=['one','two','three','four','five','six'],columns=pd.Index(['A','B','C','D'],name='Genus'))
df
Genus | A | B | C | D |
---|---|---|---|---|
one | -0.517227 | -1.461233 | 0.871440 | -1.673076 |
two | -0.015741 | 0.263614 | 0.912647 | -0.616754 |
three | -0.184967 | -0.058857 | 0.311703 | 0.258121 |
four | 3.188558 | 1.659664 | -0.712692 | -0.604190 |
five | -0.077124 | -0.981966 | 0.655416 | -0.680581 |
six | -1.511665 | 1.238646 | -0.758151 | -0.678801 |
df.plot.bar()
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.AxesSubplot at 0x2ead9e28cf8>
Note the name 'Genus' on the DataFrame's columns is used to title the legend.
df.plot.barh(stacked=True,alpha=0.5) # We create stacked bar plots from a DataFrame by passing stacked=True.
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.AxesSubplot at 0x2ead9e19518>
tips=pd.read_csv(r'./pydata-book-2nd-edition/examples/tips.csv')
tips.head()
total_bill | tip | smoker | day | time | size | |
---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | No | Sun | Dinner | 4 |
help(pd.crosstab)
Help on function crosstab in module pandas.core.reshape.pivot:
crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)
Compute a simple cross-tabulation of two (or more) factors. By default
computes a frequency table of the factors unless an array of values and an
aggregation function are passed
Parameters
----------
index : array-like, Series, or list of arrays/Series
Values to group by in the rows
columns : array-like, Series, or list of arrays/Series
Values to group by in the columns
values : array-like, optional
Array of values to aggregate according to the factors.
Requires `aggfunc` be specified.
aggfunc : function, optional
If specified, requires `values` be specified as well
rownames : sequence, default None
If passed, must match number of row arrays passed
colnames : sequence, default None
If passed, must match number of column arrays passed
margins : boolean, default False
Add row/column margins (subtotals)
margins_name : string, default 'All'
Name of the row / column that will contain the totals
when margins is True.
.. versionadded:: 0.21.0
dropna : boolean, default True
Do not include columns whose entries are all NaN
normalize : boolean, {'all', 'index', 'columns'}, or {0,1}, default False
Normalize by dividing all values by the sum of values.
- If passed 'all' or `True`, will normalize over all values.
- If passed 'index' will normalize over each row.
- If passed 'columns' will normalize over each column.
- If margins is `True`, will also normalize margin values.
.. versionadded:: 0.18.1
Notes
-----
Any Series passed will have their name attributes used unless row or column
names for the cross-tabulation are specified.
Any input passed containing Categorical data will have **all** of its
categories included in the cross-tabulation, even if the actual data does
not contain any instances of a particular category.
In the event that there aren't overlapping indexes an empty DataFrame will
be returned.
Examples
--------
>>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar",
... "bar", "bar", "foo", "foo", "foo"], dtype=object)
>>> b = np.array(["one", "one", "one", "two", "one", "one",
... "one", "two", "two", "two", "one"], dtype=object)
>>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny",
... "shiny", "dull", "shiny", "shiny", "shiny"],
... dtype=object)
>>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
... # doctest: +NORMALIZE_WHITESPACE
b one two
c dull shiny dull shiny
a
bar 1 2 1 0
foo 2 2 1 2
>>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
>>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
>>> crosstab(foo, bar) # 'c' and 'f' are not represented in the data,
... # but they still will be counted in the output
... # doctest: +SKIP
col_0 d e f
row_0
a 1 0 0
b 0 1 0
c 0 0 0
Returns
-------
crosstab : DataFrame
a = np.array(["foo", "foo", "foo", "foo", "bar", "bar","bar", "bar", "foo", "foo", "foo"], dtype=object)
b = np.array(["one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "three"], dtype=object)
c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny","shiny", "dull", "shiny", "shiny", "shiny"],dtype=object)
pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
b | one | three | two | ||
---|---|---|---|---|---|
c | dull | shiny | shiny | dull | shiny |
a | |||||
bar | 1 | 2 | 0 | 1 | 0 |
foo | 2 | 1 | 1 | 1 | 2 |
pd.crosstab(a, [b, c])
col_0 | one | three | two | ||
---|---|---|---|---|---|
col_1 | dull | shiny | shiny | dull | shiny |
row_0 | |||||
bar | 1 | 2 | 0 | 1 | 0 |
foo | 2 | 1 | 1 | 1 | 2 |
pd.DataFrame({'a':a,'b':b,'c':c})
a | b | c | |
---|---|---|---|
0 | foo | one | dull |
1 | foo | one | dull |
2 | foo | one | shiny |
3 | foo | two | dull |
4 | bar | one | dull |
5 | bar | one | shiny |
6 | bar | one | shiny |
7 | bar | two | dull |
8 | foo | two | shiny |
9 | foo | two | shiny |
10 | foo | three | shiny |
tips.head()
total_bill | tip | smoker | day | time | size | |
---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | No | Sun | Dinner | 4 |
party_counts=pd.crosstab(tips['day'],tips['size']);party_counts
size | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
day | ||||||
Fri | 1 | 16 | 1 | 1 | 0 | 0 |
Sat | 2 | 53 | 18 | 13 | 1 | 0 |
Sun | 0 | 39 | 15 | 18 | 3 | 1 |
Thur | 1 | 48 | 4 | 5 | 1 | 3 |
party_counts=party_counts.loc[:,2:5]
party_counts
size | 2 | 3 | 4 | 5 |
---|---|---|---|---|
day | ||||
Fri | 16 | 1 | 1 | 0 |
Sat | 53 | 18 | 13 | 1 |
Sun | 39 | 15 | 18 | 3 |
Thur | 48 | 4 | 5 | 1 |
party_pcts=party_counts.div(party_counts.sum(1),axis=0)
party_pcts.plot.bar()
<IPython.core.display.Javascript object>
<matplotlib.axes._subplots.AxesSubplot at 0x2ead9fb6400>
help(pd.DataFrame.sum)
Help on function sum in module pandas.core.frame:
sum(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
Return the sum of the values for the requested axis
Parameters
----------
axis : {index (0), columns (1)}
skipna : boolean, default True
Exclude NA/null values when computing the result.
level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a Series
numeric_only : boolean, default None
Include only float, int, boolean columns. If None, will attempt to use
everything, then use only numeric data. Not implemented for Series.
min_count : int, default 0
The required number of valid values to perform the operation. If fewer than
``min_count`` non-NA values are present the result will be NA.
.. versionadded :: 0.22.0
Added with the default being 0. This means the sum of an all-NA
or empty Series is 0, and the product of an all-NA or empty
Series is 1.
Returns
-------
sum : Series or DataFrame (if level specified)
Examples
--------
By default, the sum of an empty or all-NA Series is ``0``.
>>> pd.Series([]).sum() # min_count=0 is the default
0.0
This can be controlled with the ``min_count`` parameter. For example, if
you'd like the sum of an empty series to be NaN, pass ``min_count=1``.
>>> pd.Series([]).sum(min_count=1)
nan
Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
empty series identically.
>>> pd.Series([np.nan]).sum()
0.0
>>> pd.Series([np.nan]).sum(min_count=1)
nan
test=pd.DataFrame(np.arange(12).reshape((3,4)));test
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0 | 1 | 2 | 3 |
1 | 4 | 5 | 6 | 7 |
2 | 8 | 9 | 10 | 11 |
test.sum(0)
0 12
1 15
2 18
3 21
dtype: int64
test.sum(1)
0 6
1 22
2 38
dtype: int64
help(pd.DataFrame.div)
Help on function truediv in module pandas.core.ops:
truediv(self, other, axis='columns', level=None, fill_value=None)
Floating division of dataframe and other, element-wise (binary operator `truediv`).
Equivalent to ``dataframe / other``, but with support to substitute a fill_value for
missing data in one of the inputs.
Parameters
----------
other : Series, DataFrame, or constant
axis : {0, 1, 'index', 'columns'}
For Series input, axis to match Series index on
level : int or name
Broadcast across a level, matching Index values on the
passed MultiIndex level
fill_value : None or float value, default None
Fill existing missing (NaN) values, and any new element needed for
successful DataFrame alignment, with this value before computation.
If data in both corresponding DataFrame locations is missing
the result will be missing
Notes
-----
Mismatched indices will be unioned together
Returns
-------
result : DataFrame
Examples
--------
None
See also
--------
DataFrame.rtruediv
test.div(test.sum(1))
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0.000000 | 0.045455 | 0.052632 | NaN |
1 | 0.666667 | 0.227273 | 0.157895 | NaN |
2 | 1.333333 | 0.409091 | 0.263158 | NaN |
test.div(test.sum(0))
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0.000000 | 0.066667 | 0.111111 | 0.142857 |
1 | 0.333333 | 0.333333 | 0.333333 | 0.333333 |
2 | 0.666667 | 0.600000 | 0.555556 | 0.523810 |
test/test.sum(0)# 0/12,1/15,2/18,3/21...
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0.000000 | 0.066667 | 0.111111 | 0.142857 |
1 | 0.333333 | 0.333333 | 0.333333 | 0.333333 |
2 | 0.666667 | 0.600000 | 0.555556 | 0.523810 |
test/test.sum(1) # 0/6,1/22,2/38,3/?=Nan...
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0.000000 | 0.045455 | 0.052632 | NaN |
1 | 0.666667 | 0.227273 | 0.157895 | NaN |
2 | 1.333333 | 0.409091 | 0.263158 | NaN |
test
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 0 | 1 | 2 | 3 |
1 | 4 | 5 | 6 | 7 |
2 | 8 | 9 | 10 | 11 |
test.sum(1)
0 6
1 22
2 38
dtype: int64
test.sum(0)
0 12
1 15
2 18
3 21
dtype: int64
pd.DataFrame.div(ohter),by default,div other along columns,axis='columns'.
With data that requires aggregation or summarization before making a plot,using the seaborn
package can make things mush simpler.
import seaborn as sns
tips.head()
total_bill | tip | smoker | day | time | size | |
---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | No | Sun | Dinner | 4 |
tips['tip_pct']=tips['tip']/(tips['total_bill']-tips['tip'])
sns.barplot(x='tip_pct',y='day',data=tips,orient='h')
D:\Anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x2ead9fb6400>
Histograms and density plots
fig=plt.figure() # in jupyter notebook, create a figure before calling a draw function.
<IPython.core.display.Javascript object>
tips['tip_pct'].plot.hist(bins=50)
<matplotlib.axes._subplots.AxesSubplot at 0x2eadacee780>
To solve 'after pd.DataFrame.plot.hist() or so ,no images appear in jupyter notebook',just create a figure befor calling a draw function like the example above.
fig=plt.figure()
<IPython.core.display.Javascript object>
sns.barplot(x='tip_pct',y='day',data=tips,orient='h')
D:\Anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x2eadad18b00>
plt.figure()
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
tips['tip_pct'].plot.density()
<matplotlib.axes._subplots.AxesSubplot at 0x2eadadfbb00>
tips.head()
total_bill | tip | smoker | day | time | size | tip_pct | |
---|---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | No | Sun | Dinner | 2 | 0.063204 |
1 | 10.34 | 1.66 | No | Sun | Dinner | 3 | 0.191244 |
2 | 21.01 | 3.50 | No | Sun | Dinner | 3 | 0.199886 |
3 | 23.68 | 3.31 | No | Sun | Dinner | 2 | 0.162494 |
4 | 24.59 | 3.61 | No | Sun | Dinner | 4 | 0.172069 |
Density plot
is formed by computing an estimate of continuous probability distribution that might have generated the observed data.The usual procedure is to approximate this distribution as a mixture of 'kernels',that is simpler distributions like the normal distribution.
comp1=np.random.normal(0,1,size=200)
comp2=np.random.normal(10,2,size=200)
help(np.concatenate)
Help on built-in function concatenate in module numpy.core.multiarray:
concatenate(...)
concatenate((a1, a2, ...), axis=0, out=None)
Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : ndarray
The concatenated array.
See Also
--------
ma.concatenate : Concatenate function that preserves input masks.
array_split : Split an array into multiple sub-arrays of equal or
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise)
vsplit : Split array into multiple sub-arrays vertically (row wise)
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
stack : Stack a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise)
vstack : Stack arrays in sequence vertically (row wise)
dstack : Stack arrays in sequence depth wise (along third dimension)
Notes
-----
When one or more of the arrays to be concatenated is a MaskedArray,
this function will return a MaskedArray object instead of an ndarray,
but the input masks are *not* preserved. In cases where a MaskedArray
is expected as input, use the ma.concatenate function from the masked
array module instead.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs.
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data = [0 1 2 2 3 4],
mask = False,
fill_value = 999999)
>>> np.ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
values=pd.Series(np.concatenate([comp1,comp2]))
plt.figure()
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
sns.distplot(values,bins=100,color='k')
D:\Anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x2eadae46ba8>
Seaborn makes histograms and density plots even easier through its displot
method,which can plot both a histogram and a continuous density estimate simultaneously.
Scatter or point plots
Point plots or scatter plots can be a useful way of examining the relationship between two one-dimensional data series.
macro=pd.read_csv('./pydata-book-2nd-edition/examples/macrodata.csv')
macro.head()
year | quarter | realgdp | realcons | realinv | realgovt | realdpi | cpi | m1 | tbilrate | unemp | pop | infl | realint | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1959.0 | 1.0 | 2710.349 | 1707.4 | 286.898 | 470.045 | 1886.9 | 28.98 | 139.7 | 2.82 | 5.8 | 177.146 | 0.00 | 0.00 |
1 | 1959.0 | 2.0 | 2778.801 | 1733.7 | 310.859 | 481.301 | 1919.7 | 29.15 | 141.7 | 3.08 | 5.1 | 177.830 | 2.34 | 0.74 |
2 | 1959.0 | 3.0 | 2775.488 | 1751.8 | 289.226 | 491.260 | 1916.4 | 29.35 | 140.5 | 3.82 | 5.3 | 178.657 | 2.74 | 1.09 |
3 | 1959.0 | 4.0 | 2785.204 | 1753.7 | 299.356 | 484.052 | 1931.3 | 29.37 | 140.0 | 4.33 | 5.6 | 179.386 | 0.27 | 4.06 |
4 | 1960.0 | 1.0 | 2847.699 | 1770.5 | 331.722 | 462.199 | 1955.5 | 29.54 | 139.6 | 3.50 | 5.2 | 180.007 | 2.31 | 1.19 |
data=macro[['cpi','m1','tbilrate','unemp']]
trans_data=np.log(data).diff().dropna()
help(np.log(data).diff)
Help on method diff in module pandas.core.frame:
diff(periods=1, axis=0) method of pandas.core.frame.DataFrame instance
First discrete difference of element.
Calculates the difference of a DataFrame element compared with another
element in the DataFrame (default is the element in the same column
of the previous row).
Parameters
----------
periods : int, default 1
Periods to shift for calculating difference, accepts negative
values.
axis : {0 or 'index', 1 or 'columns'}, default 0
Take difference over rows (0) or columns (1).
.. versionadded:: 0.16.1.
Returns
-------
diffed : DataFrame
See Also
--------
Series.diff: First discrete difference for a Series.
DataFrame.pct_change: Percent change over given number of periods.
DataFrame.shift: Shift index by desired number of periods with an
optional time freq.
Examples
--------
Difference with previous row
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [1, 1, 2, 3, 5, 8],
... 'c': [1, 4, 9, 16, 25, 36]})
>>> df
a b c
0 1 1 1
1 2 1 4
2 3 2 9
3 4 3 16
4 5 5 25
5 6 8 36
>>> df.diff()
a b c
0 NaN NaN NaN
1 1.0 0.0 3.0
2 1.0 1.0 5.0
3 1.0 1.0 7.0
4 1.0 2.0 9.0
5 1.0 3.0 11.0
Difference with previous column
>>> df.diff(axis=1)
a b c
0 NaN 0.0 0.0
1 NaN -1.0 3.0
2 NaN -1.0 7.0
3 NaN -1.0 13.0
4 NaN 0.0 20.0
5 NaN 2.0 28.0
Difference with 3rd previous row
>>> df.diff(periods=3)
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 3.0 2.0 15.0
4 3.0 4.0 21.0
5 3.0 6.0 27.0
Difference with following row
>>> df.diff(periods=-1)
a b c
0 -1.0 0.0 -3.0
1 -1.0 -1.0 -5.0
2 -1.0 -1.0 -7.0
3 -1.0 -2.0 -9.0
4 -1.0 -3.0 -11.0
5 NaN NaN NaN
trans_data[-5:]
cpi | m1 | tbilrate | unemp | |
---|---|---|---|---|
198 | -0.007904 | 0.045361 | -0.396881 | 0.105361 |
199 | -0.021979 | 0.066753 | -2.277267 | 0.139762 |
200 | 0.002340 | 0.010286 | 0.606136 | 0.160343 |
201 | 0.008419 | 0.037461 | -0.200671 | 0.127339 |
202 | 0.008894 | 0.012202 | -0.405465 | 0.042560 |
We can use seaborn's regplot
method ,which makes a scatter plot and fits a linear regression line.
plt.figure()
D:\Anaconda\lib\site-packages\matplotlib\pyplot.py:522: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
max_open_warning, RuntimeWarning)
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
sns.regplot('m1','unemp',data=trans_data)
D:\Anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x2eadaf766d8>
plt.title('changes in log %s versus log %s'%('m1','unemp'))
Text(0.5,1,'changes in log m1 versus log unemp')
In exploratory data analysis it's helpful to be able to look at all the scatter plots among a group of variables;this is known as a pairs
plot or scatter plot matrix
.Making such a plot from scratch is a bit of work,so seaborn has a convenient pairplot
function,which supports placingg histograms or density estimates of each variable along the diagonal.
sns.pairplot(trans_data,diag_kind='kde',plot_kws={'alpha':0.2})
D:\Anaconda\lib\site-packages\matplotlib\pyplot.py:522: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
max_open_warning, RuntimeWarning)
<IPython.core.display.Javascript object>
D:\Anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<seaborn.axisgrid.PairGrid at 0x2eadafa2e48>