In [1]:
import numpy as np
import pandas as pd
from numpy.random import randn
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import stats
from sklearn import datasets
import statsmodels
import seaborn as sns
%matplotlib inline
# plot in notebook
%pylab inline
# change plot size
Populating the interactive namespace from numpy and matplotlib
In [2]:
# Note seaborn is importes.
# (So you get its basic theme)
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
In [3]:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
Out[3]:
[<matplotlib.lines.Line2D at 0x10b8c1650>]
In [4]:
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
In [5]:
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
In [6]:
help(matplotlib)
Help on package matplotlib:
NAME
matplotlib - This is an object-oriented plotting library.
FILE
/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py
DESCRIPTION
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
at the ipython shell prompt.
For the most part, direct use of the object-oriented library is
encouraged when programming; pyplot is primarily for working
interactively. The
exceptions are the pyplot commands :func:`~matplotlib.pyplot.figure`,
:func:`~matplotlib.pyplot.subplot`,
:func:`~matplotlib.pyplot.subplots`, and
:func:`~pyplot.savefig`, which can greatly simplify scripting.
Modules include:
:mod:`matplotlib.axes`
defines the :class:`~matplotlib.axes.Axes` class. Most pylab
commands are wrappers for :class:`~matplotlib.axes.Axes`
methods. The axes module is the highest level of OO access to
the library.
:mod:`matplotlib.figure`
defines the :class:`~matplotlib.figure.Figure` class.
:mod:`matplotlib.artist`
defines the :class:`~matplotlib.artist.Artist` base class for
all classes that draw things.
:mod:`matplotlib.lines`
defines the :class:`~matplotlib.lines.Line2D` class for
drawing lines and markers
:mod:`matplotlib.patches`
defines classes for drawing polygons
:mod:`matplotlib.text`
defines the :class:`~matplotlib.text.Text`,
:class:`~matplotlib.text.TextWithDash`, and
:class:`~matplotlib.text.Annotate` classes
:mod:`matplotlib.image`
defines the :class:`~matplotlib.image.AxesImage` and
:class:`~matplotlib.image.FigureImage` classes
:mod:`matplotlib.collections`
classes for efficient drawing of groups of lines or polygons
:mod:`matplotlib.colors`
classes for interpreting color specifications and for making
colormaps
:mod:`matplotlib.cm`
colormaps and the :class:`~matplotlib.image.ScalarMappable`
mixin class for providing color mapping functionality to other
classes
:mod:`matplotlib.ticker`
classes for calculating tick mark locations and for formatting
tick labels
:mod:`matplotlib.backends`
a subpackage with modules for various gui libraries and output
formats
The base matplotlib namespace includes:
:data:`~matplotlib.rcParams`
a global dictionary of default configuration settings. It is
initialized by code which may be overridded by a matplotlibrc
file.
:func:`~matplotlib.rc`
a function for setting groups of rcParams values
:func:`~matplotlib.use`
a function for setting the matplotlib backend. If used, this
function must be called immediately after importing matplotlib
for the first time. In particular, it must be called
**before** importing pylab (if pylab is imported).
matplotlib was initially written by John D. Hunter (1968-2012) and is now
developed and maintained by a host of others.
Occasionally the internal documentation (python docstrings) will refer
to MATLAB®, a registered trademark of The MathWorks, Inc.
PACKAGE CONTENTS
_cm
_cm_listed
_cntr
_color_data
_contour
_delaunay
_image
_mathtext_data
_path
_png
_pylab_helpers
_qhull
_tri
_version
afm
animation
artist
axes (package)
axis
backend_bases
backend_managers
backend_tools
backends (package)
bezier
blocking_input
cbook
cm
collections
colorbar
colors
compat (package)
container
contour
dates
delaunay (package)
docstring
dviread
figure
finance
font_manager
fontconfig_pattern
ft2font
gridspec
hatch
image
legend
legend_handler
lines
markers
mathtext
mlab
offsetbox
patches
path
patheffects
projections (package)
pylab
pyplot
quiver
rcsetup
sankey
scale
sphinxext (package)
spines
stackplot
streamplot
style (package)
table
testing (package)
tests (package)
texmanager
text
textpath
ticker
tight_bbox
tight_layout
transforms
tri (package)
ttconv
type1font
units
widgets
SUBMODULES
subprocess
CLASSES
__builtin__.dict(__builtin__.object)
RcParams
__builtin__.object
Verbose
rc_context
class RcParams(__builtin__.dict)
| A dictionary object including validation
|
| validating functions are defined and associated with rc parameters in
| :mod:`matplotlib.rcsetup`
|
| Method resolution order:
| RcParams
| __builtin__.dict
| __builtin__.object
|
| Methods defined here:
|
| __getitem__(self, key)
|
| __init__(self, *args, **kwargs)
| # validate values on the way in
|
| __repr__(self)
|
| __setitem__(self, key, val)
|
| __str__(self)
|
| find_all(self, pattern)
| Return the subset of this RcParams dictionary whose keys match,
| using :func:`re.search`, the given ``pattern``.
|
| .. note::
|
| Changes to the returned dictionary are *not* propagated to
| the parent RcParams dictionary.
|
| keys(self)
| Return sorted list of keys.
|
| update(self, *args, **kwargs)
| # http://stackoverflow.com/questions/2390827
| # (how-to-properly-subclass-dict-and-override-get-set)
| # the default dict `update` does not use __setitem__
| # so rcParams.update(...) (such as in seaborn) side-steps
| # all of the validation over-ride update to force
| # through __setitem__
|
| values(self)
| Return values in order of sorted keys.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| msg_depr = u'%s is deprecated and replaced with %s; please use the lat...
|
| msg_depr_ignore = u'%s is deprecated and ignored. Use %s'
|
| msg_depr_set = u'%s is deprecated. Please remove it from your matplotl...
|
| msg_obsolete = u'%s is obsolete. Please remove it from your matplotlib...
|
| validate = {u'_internal.classic_mode': <function validate_bool>, u'agg...
|
| ----------------------------------------------------------------------
| Methods inherited from __builtin__.dict:
|
| __cmp__(...)
| x.__cmp__(y) <==> cmp(x,y)
|
| __contains__(...)
| D.__contains__(k) -> True if D has a key k, else False
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __gt__(...)
| x.__gt__(y) <==> x>y
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __le__(...)
| x.__le__(y) <==> x<=y
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __lt__(...)
| x.__lt__(y) <==> x<y
|
| __ne__(...)
| x.__ne__(y) <==> x!=y
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| fromkeys(...)
| dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
| v defaults to None.
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| has_key(...)
| D.has_key(k) -> True if D has a key k, else False
|
| items(...)
| D.items() -> list of D's (key, value) pairs, as 2-tuples
|
| iteritems(...)
| D.iteritems() -> an iterator over the (key, value) items of D
|
| iterkeys(...)
| D.iterkeys() -> an iterator over the keys of D
|
| itervalues(...)
| D.itervalues() -> an iterator over the values of D
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| viewitems(...)
| D.viewitems() -> a set-like object providing a view on D's items
|
| viewkeys(...)
| D.viewkeys() -> a set-like object providing a view on D's keys
|
| viewvalues(...)
| D.viewvalues() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from __builtin__.dict:
|
| __hash__ = None
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
class Verbose(__builtin__.object)
| A class to handle reporting. Set the fileo attribute to any file
| instance to handle the output. Default is sys.stdout
|
| Methods defined here:
|
| __init__(self)
|
| ge(self, level)
| return true if self.level is >= level
|
| report(self, s, level=u'helpful')
| print message s to self.fileo if self.level>=level. Return
| value indicates whether a message was issued
|
| set_fileo(self, fname)
|
| set_level(self, level)
| set the verbosity to one of the Verbose.levels strings
|
| wrap(self, fmt, func, level=u'helpful', always=True)
| return a callable function that wraps func and reports it
| output through the verbose handler if current verbosity level
| is higher than level
|
| if always is True, the report will occur on every function
| call; otherwise only on the first time the function is called
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| arg = '/Users/jayavelarumugam/Library/Jupyter/runtime/kernel-3c3a8b95-...
|
| i = 3
|
| level = u'debug-annoying'
|
| levels = (u'silent', u'helpful', u'debug', u'debug-annoying')
|
| vald = {u'debug': 2, u'debug-annoying': 3, u'helpful': 1, u'silent': 0...
class rc_context(__builtin__.object)
| Return a context manager for managing rc settings.
|
| This allows one to do::
|
| with mpl.rc_context(fname='screen.rc'):
| plt.plot(x, a)
| with mpl.rc_context(fname='print.rc'):
| plt.plot(x, b)
| plt.plot(x, c)
|
| The 'a' vs 'x' and 'c' vs 'x' plots would have settings from
| 'screen.rc', while the 'b' vs 'x' plot would have settings from
| 'print.rc'.
|
| A dictionary can also be passed to the context manager::
|
| with mpl.rc_context(rc={'text.usetex': True}, fname='screen.rc'):
| plt.plot(x, a)
|
| The 'rc' dictionary takes precedence over the settings loaded from
| 'fname'. Passing a dictionary only is also valid.
|
| Methods defined here:
|
| __enter__(self)
|
| __exit__(self, type, value, tb)
|
| __init__(self, rc=None, fname=None)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
FUNCTIONS
checkdep_dvipng()
checkdep_ghostscript()
checkdep_inkscape()
checkdep_pdftops()
checkdep_ps_distiller(s)
checkdep_tex()
checkdep_usetex(s)
checkdep_xmllint()
compare_versions(a, b)
return True if a is greater than or equal to b
get_backend()
Return the name of the current backend.
get_cachedir = wrapper(*args, **kwargs)
Return the location of the cache directory.
The procedure used to find the directory is the same as for
_get_config_dir, except using `$XDG_CACHE_HOME`/`~/.cache` instead.
get_configdir = wrapper(*args, **kwargs)
Return the string representing the configuration directory.
The directory is chosen as follows:
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
2a. On Linux, if `$HOME/.matplotlib` exists, choose that, but warn that
that is the old location. Barring that, follow the XDG specification
and look first in `$XDG_CONFIG_HOME`, if defined, or `$HOME/.config`.
2b. On other platforms, choose `$HOME/.matplotlib`.
3. If the chosen directory exists and is writable, use that as the
configuration directory.
4. If possible, create a temporary directory, and use it as the
configuration directory.
5. A writable directory could not be found or created; return None.
get_data_path = wrapper(*args, **kwargs)
get_example_data(fname)
get_example_data is deprecated -- use matplotlib.cbook.get_sample_data
instead
get_home = wrapper(*args, **kwargs)
Find user's home directory if possible.
Otherwise, returns None.
:see:
http://mail.python.org/pipermail/python-list/2005-February/325395.html
get_py2exe_datafiles()
interactive(b)
Set interactive mode to boolean b.
If b is True, then draw after every plotting command, e.g., after xlabel
is_interactive()
Return true if plot mode is interactive
is_url(filename)
Return True if string is an http, ftp, or file URL path.
matplotlib_fname()
Get the location of the config file.
The file location is determined in the following order
- `$PWD/matplotlibrc`
- `$MATPLOTLIBRC/matplotlibrc`
- `$MPLCONFIGDIR/matplotlibrc`
- On Linux,
- `$HOME/.matplotlib/matplotlibrc`, if it exists
- or `$XDG_CONFIG_HOME/matplotlib/matplotlibrc` (if
$XDG_CONFIG_HOME is defined)
- or `$HOME/.config/matplotlib/matplotlibrc` (if
$XDG_CONFIG_HOME is not defined)
- On other platforms,
- `$HOME/.matplotlib/matplotlibrc` if `$HOME` is defined.
- Lastly, it looks in `$MATPLOTLIBDATA/matplotlibrc` for a
system-defined copy.
rc(group, **kwargs)
Set the current rc params. Group is the grouping for the rc, e.g.,
for ``lines.linewidth`` the group is ``lines``, for
``axes.facecolor``, the group is ``axes``, and so on. Group may
also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
*kwargs* is a dictionary attribute name/value pairs, e.g.,::
rc('lines', linewidth=2, color='r')
sets the current rc params and is equivalent to::
rcParams['lines.linewidth'] = 2
rcParams['lines.color'] = 'r'
The following aliases are available to save typing for interactive
users:
===== =================
Alias Property
===== =================
'lw' 'linewidth'
'ls' 'linestyle'
'c' 'color'
'fc' 'facecolor'
'ec' 'edgecolor'
'mew' 'markeredgewidth'
'aa' 'antialiased'
===== =================
Thus you could abbreviate the above rc command as::
rc('lines', lw=2, c='r')
Note you can use python's kwargs dictionary facility to store
dictionaries of default parameters. e.g., you can customize the
font rc as follows::
font = {'family' : 'monospace',
'weight' : 'bold',
'size' : 'larger'}
rc('font', **font) # pass in the font dict as kwargs
This enables you to easily switch between several configurations.
Use :func:`~matplotlib.pyplot.rcdefaults` to restore the default
rc params after changes.
rc_file(fname)
Update rc params from file.
rc_file_defaults()
Restore the default rc params from the original matplotlib rc that
was loaded
rc_params(fail_on_error=False)
Return a :class:`matplotlib.RcParams` instance from the
default matplotlib rc file.
rc_params_from_file(fname, fail_on_error=False, use_default_template=True)
Return :class:`matplotlib.RcParams` from the contents of the given file.
Parameters
----------
fname : str
Name of file parsed for matplotlib settings.
fail_on_error : bool
If True, raise an error when the parser fails to convert a parameter.
use_default_template : bool
If True, initialize with default parameters before updating with those
in the given file. If False, the configuration class only contains the
parameters specified in the file. (Useful for updating dicts.)
rcdefaults()
Restore the default rc params. These are not the params loaded by
the rc file, but mpl's internal params. See rc_file_defaults for
reloading the default params from the rc file
reload(...)
reload(module) -> module
Reload the module. The module must have been successfully imported before.
test(verbosity=1)
run the matplotlib test suite
tk_window_focus()
Return true if focus maintenance under TkAgg on win32 is on.
This currently works only for python.exe and IPython.exe.
Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on.
unpack_labeled_data(replace_names=None, replace_all_args=False, label_namer=None, positional_parameter_names=None)
A decorator to add a 'data' kwarg to any a function. The signature
of the input function must include the ax argument at the first position ::
def foo(ax, *args, **kwargs)
so this is suitable for use with Axes methods.
Parameters
----------
replace_names : list of strings, optional, default: None
The list of parameter names which arguments should be replaced by
`data[name]`. If None, all arguments are replaced if they are
included in `data`.
replace_all_args : bool, default: False
If True, all arguments in *args get replaced, even if they are not
in replace_names.
label_namer : string, optional, default: None
The name of the parameter which argument should be used as label, if
label is not set. If None, the label keyword argument is not set.
positional_parameter_names : list of strings or callable, optional
The full list of positional parameter names (excluding an explicit
`ax`/'self' argument at the first place and including all possible
positional parameter in `*args`), in the right order. Can also include
all other keyword parameter. Only needed if the wrapped function does
contain `*args` and (replace_names is not None or replace_all_args is
False). If it is a callable, it will be called with the actual
tuple of *args and the data and should return a list like
above.
NOTE: callables should only be used when the names and order of *args
can only be determined at runtime. Please use list of names
when the order and names of *args is clear before runtime!
use(arg, warn=True, force=False)
Set the matplotlib backend to one of the known backends.
The argument is case-insensitive. *warn* specifies whether a
warning should be issued if a backend has already been set up.
*force* is an **experimental** flag that tells matplotlib to
attempt to initialize a new backend by reloading the backend
module.
.. note::
This function must be called *before* importing pyplot for
the first time; or, if you are not using pyplot, it must be called
before importing matplotlib.backends. If warn is True, a warning
is issued if you try and call this after pylab or pyplot have been
loaded. In certain black magic use cases, e.g.
:func:`pyplot.switch_backend`, we are doing the reloading necessary to
make the backend switch work (in some cases, e.g., pure image
backends) so one can set warn=False to suppress the warnings.
To find out which backend is currently set, see
:func:`matplotlib.get_backend`.
DATA
URL_REGEX = <_sre.SRE_Pattern object>
__bibtex__ = u'@Article{Hunter:2007,\n Author = {Hunter, ...er = {...
__version__ = '2.0.0'
__version__numpy__ = '1.7.1'
absolute_import = _Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0...
bad_pyparsing = False
default = 1.0
defaultParams = {u'_internal.classic_mode': [False, <function validate...
default_test_modules = [u'matplotlib.tests.test_agg', u'matplotlib.tes...
division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192...
f = Forward: ...
key = u'grid.alpha'
major = 2
minor1 = 7
minor2 = 12
print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)...
rcParams = RcParams({u'_internal.classic_mode': False,
...or.width...
rcParamsDefault = RcParams({u'_internal.classic_mode': False,
...o...
rcParamsOrig = {u'_internal.classic_mode': False, u'agg.path.chunksize...
s = '/Users/jayavelarumugam/Library/Jupyter/runtime/kernel-3c3a8b95-54...
tmp = 0
unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', ...
verbose = <matplotlib.Verbose object>
VERSION
2.0.0
In [7]:
help(matplotlib.lines)
Help on module matplotlib.lines in matplotlib:
NAME
matplotlib.lines
FILE
/usr/local/lib/python2.7/site-packages/matplotlib/lines.py
DESCRIPTION
This module contains all the 2D line class which can draw with a
variety of line styles, markers and colors.
CLASSES
__builtin__.object
VertexSelector
matplotlib.artist.Artist(__builtin__.object)
Line2D
class Line2D(matplotlib.artist.Artist)
| A line - the line can have both a solid linestyle connecting all
| the vertices, and a marker at each vertex. Additionally, the
| drawing of the solid line is influenced by the drawstyle, e.g., one
| can create "stepped" lines in various styles.
|
| Method resolution order:
| Line2D
| matplotlib.artist.Artist
| __builtin__.object
|
| Methods defined here:
|
| __getstate__(self)
|
| __init__(self, xdata, ydata, linewidth=None, linestyle=None, color=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt=u'none', fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs)
| Create a :class:`~matplotlib.lines.Line2D` instance with *x*
| and *y* data in sequences *xdata*, *ydata*.
|
| The kwargs are :class:`~matplotlib.lines.Line2D` properties:
|
| agg_filter: unknown
| alpha: float (0.0 transparent through 1.0 opaque)
| animated: [True | False]
| antialiased or aa: [True | False]
| axes: an :class:`~matplotlib.axes.Axes` instance
| clip_box: a :class:`matplotlib.transforms.Bbox` instance
| clip_on: [True | False]
| clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
| color or c: any matplotlib color
| contains: a callable function
| dash_capstyle: ['butt' | 'round' | 'projecting']
| dash_joinstyle: ['miter' | 'round' | 'bevel']
| dashes: sequence of on/off ink in points
| drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post']
| figure: a :class:`matplotlib.figure.Figure` instance
| fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
| gid: an id string
| label: string or anything printable with '%s' conversion.
| linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
| linewidth or lw: float value in points
| marker: :mod:`A valid marker style <matplotlib.markers>`
| markeredgecolor or mec: any matplotlib color
| markeredgewidth or mew: float value in points
| markerfacecolor or mfc: any matplotlib color
| markerfacecoloralt or mfcalt: any matplotlib color
| markersize or ms: float
| markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
| path_effects: unknown
| picker: float distance in points or callable pick function ``fn(artist, event)``
| pickradius: float distance in points
| rasterized: [True | False | None]
| sketch_params: unknown
| snap: unknown
| solid_capstyle: ['butt' | 'round' | 'projecting']
| solid_joinstyle: ['miter' | 'round' | 'bevel']
| transform: a :class:`matplotlib.transforms.Transform` instance
| url: a url string
| visible: [True | False]
| xdata: 1D array
| ydata: 1D array
| zorder: any number
|
| See :meth:`set_linestyle` for a decription of the line styles,
| :meth:`set_marker` for a description of the markers, and
| :meth:`set_drawstyle` for a description of the draw styles.
|
| __str__(self)
|
| contains(self, mouseevent)
| Test whether the mouse event occurred on the line. The pick
| radius determines the precision of the location test (usually
| within five points of the value). Use
| :meth:`~matplotlib.lines.Line2D.get_pickradius` or
| :meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
| modify it.
|
| Returns *True* if any values are within the radius along with
| ``{'ind': pointlist}``, where *pointlist* is the set of points
| within the radius.
|
| TODO: sort returned indices by distance
|
| draw(artist, renderer, *args, **kwargs)
| draw the Line with `renderer` unless visibility is False
|
| get_aa(self)
| alias for get_antialiased
|
| get_antialiased(self)
|
| get_c(self)
| alias for get_color
|
| get_color(self)
|
| get_dash_capstyle(self)
| Get the cap style for dashed linestyles
|
| get_dash_joinstyle(self)
| Get the join style for dashed linestyles
|
| get_data(self, orig=True)
| Return the xdata, ydata.
|
| If *orig* is *True*, return the original data.
|
| get_drawstyle(self)
|
| get_fillstyle(self)
| return the marker fillstyle
|
| get_linestyle(self)
|
| get_linewidth(self)
|
| get_ls(self)
| alias for get_linestyle
|
| get_lw(self)
| alias for get_linewidth
|
| get_marker(self)
|
| get_markeredgecolor(self)
|
| get_markeredgewidth(self)
|
| get_markerfacecolor(self)
|
| get_markerfacecoloralt(self)
|
| get_markersize(self)
|
| get_markevery(self)
| return the markevery setting
|
| get_mec(self)
| alias for get_markeredgecolor
|
| get_mew(self)
| alias for get_markeredgewidth
|
| get_mfc(self)
| alias for get_markerfacecolor
|
| get_mfcalt(self, alt=False)
| alias for get_markerfacecoloralt
|
| get_ms(self)
| alias for get_markersize
|
| get_path(self)
| Return the :class:`~matplotlib.path.Path` object associated
| with this line.
|
| get_pickradius(self)
| return the pick radius used for containment tests
|
| get_solid_capstyle(self)
| Get the cap style for solid linestyles
|
| get_solid_joinstyle(self)
| Get the join style for solid linestyles
|
| get_window_extent(self, renderer)
|
| get_xdata(self, orig=True)
| Return the xdata.
|
| If *orig* is *True*, return the original data, else the
| processed data.
|
| get_xydata(self)
| Return the *xy* data as a Nx2 numpy array.
|
| get_ydata(self, orig=True)
| Return the ydata.
|
| If *orig* is *True*, return the original data, else the
| processed data.
|
| is_dashed(self)
| return True if line is dashstyle
|
| recache(self, always=False)
|
| recache_always(self)
|
| set_aa(self, val)
| alias for set_antialiased
|
| set_antialiased(self, b)
| True if line should be drawin with antialiased rendering
|
| ACCEPTS: [True | False]
|
| set_c(self, val)
| alias for set_color
|
| set_color(self, color)
| Set the color of the line
|
| ACCEPTS: any matplotlib color
|
| set_dash_capstyle(self, s)
| Set the cap style for dashed linestyles
|
| ACCEPTS: ['butt' | 'round' | 'projecting']
|
| set_dash_joinstyle(self, s)
| Set the join style for dashed linestyles
| ACCEPTS: ['miter' | 'round' | 'bevel']
|
| set_dashes(self, seq)
| Set the dash sequence, sequence of dashes with on off ink in
| points. If seq is empty or if seq = (None, None), the
| linestyle will be set to solid.
|
| ACCEPTS: sequence of on/off ink in points
|
| set_data(self, *args)
| Set the x and y data
|
| ACCEPTS: 2D array (rows are x, y) or two 1D arrays
|
| set_drawstyle(self, drawstyle)
| Set the drawstyle of the plot
|
| 'default' connects the points with lines. The steps variants
| produce step-plots. 'steps' is equivalent to 'steps-pre' and
| is maintained for backward-compatibility.
|
| ACCEPTS: ['default' | 'steps' | 'steps-pre' | 'steps-mid' |
| 'steps-post']
|
| set_fillstyle(self, fs)
| Set the marker fill style; 'full' means fill the whole marker.
| 'none' means no filling; other options are for half-filled markers.
|
| ACCEPTS: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
|
| set_linestyle(self, ls)
| Set the linestyle of the line (also accepts drawstyles,
| e.g., ``'steps--'``)
|
|
| =========================== =================
| linestyle description
| =========================== =================
| ``'-'`` or ``'solid'`` solid line
| ``'--'`` or ``'dashed'`` dashed line
| ``'-.'`` or ``'dashdot'`` dash-dotted line
| ``':'`` or ``'dotted'`` dotted line
| ``'None'`` draw nothing
| ``' '`` draw nothing
| ``''`` draw nothing
| =========================== =================
|
| 'steps' is equivalent to 'steps-pre' and is maintained for
| backward-compatibility.
|
| 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'`` |
| ``' '`` | ``''``]
|
| .. seealso::
|
| :meth:`set_drawstyle`
| To set the drawing style (stepping) of the plot.
|
| Parameters
| ----------
| ls : { ``'-'``, ``'--'``, ``'-.'``, ``':'``} and more see description
| The line style.
|
| set_linewidth(self, w)
| Set the line width in points
|
| ACCEPTS: float value in points
|
| set_ls(self, val)
| alias for set_linestyle
|
| set_lw(self, val)
| alias for set_linewidth
|
| set_marker(self, marker)
| Set the line marker
|
| ACCEPTS: :mod:`A valid marker style <matplotlib.markers>`
|
| Parameters
| ----------
|
| marker: marker style
| See `~matplotlib.markers` for full description of possible
| argument
|
| set_markeredgecolor(self, ec)
| Set the marker edge color
|
| ACCEPTS: any matplotlib color
|
| set_markeredgewidth(self, ew)
| Set the marker edge width in points
|
| ACCEPTS: float value in points
|
| set_markerfacecolor(self, fc)
| Set the marker face color.
|
| ACCEPTS: any matplotlib color
|
| set_markerfacecoloralt(self, fc)
| Set the alternate marker face color.
|
| ACCEPTS: any matplotlib color
|
| set_markersize(self, sz)
| Set the marker size in points
|
| ACCEPTS: float
|
| set_markevery(self, every)
| Set the markevery property to subsample the plot when using markers.
|
| e.g., if `every=5`, every 5-th marker will be plotted.
|
| ACCEPTS: [None | int | length-2 tuple of int | slice |
| list/array of int | float | length-2 tuple of float]
|
| Parameters
| ----------
| every: None | int | length-2 tuple of int | slice | list/array of int |
| float | length-2 tuple of float
| Which markers to plot.
|
| - every=None, every point will be plotted.
| - every=N, every N-th marker will be plotted starting with
| marker 0.
| - every=(start, N), every N-th marker, starting at point
| start, will be plotted.
| - every=slice(start, end, N), every N-th marker, starting at
| point start, upto but not including point end, will be plotted.
| - every=[i, j, m, n], only markers at points i, j, m, and n
| will be plotted.
| - every=0.1, (i.e. a float) then markers will be spaced at
| approximately equal distances along the line; the distance
| along the line between markers is determined by multiplying the
| display-coordinate distance of the axes bounding-box diagonal
| by the value of every.
| - every=(0.5, 0.1) (i.e. a length-2 tuple of float), the
| same functionality as every=0.1 is exhibited but the first
| marker will be 0.5 multiplied by the
| display-cordinate-diagonal-distance along the line.
|
| Notes
| -----
| Setting the markevery property will only show markers at actual data
| points. When using float arguments to set the markevery property
| on irregularly spaced data, the markers will likely not appear evenly
| spaced because the actual data points do not coincide with the
| theoretical spacing between markers.
|
| When using a start offset to specify the first marker, the offset will
| be from the first data point which may be different from the first
| the visible data point if the plot is zoomed in.
|
| If zooming in on a plot when using float arguments then the actual
| data points that have markers will change because the distance between
| markers is always determined from the display-coordinates
| axes-bounding-box-diagonal regardless of the actual axes data limits.
|
| set_mec(self, val)
| alias for set_markeredgecolor
|
| set_mew(self, val)
| alias for set_markeredgewidth
|
| set_mfc(self, val)
| alias for set_markerfacecolor
|
| set_mfcalt(self, val)
| alias for set_markerfacecoloralt
|
| set_ms(self, val)
| alias for set_markersize
|
| set_picker(self, p)
| Sets the event picker details for the line.
|
| ACCEPTS: float distance in points or callable pick function
| ``fn(artist, event)``
|
| set_pickradius(self, d)
| Sets the pick radius used for containment tests
|
| ACCEPTS: float distance in points
|
| set_solid_capstyle(self, s)
| Set the cap style for solid linestyles
|
| ACCEPTS: ['butt' | 'round' | 'projecting']
|
| set_solid_joinstyle(self, s)
| Set the join style for solid linestyles
| ACCEPTS: ['miter' | 'round' | 'bevel']
|
| set_transform(self, t)
| set the Transformation instance used by this artist
|
| ACCEPTS: a :class:`matplotlib.transforms.Transform` instance
|
| set_xdata(self, x)
| Set the data np.array for x
|
| ACCEPTS: 1D array
|
| set_ydata(self, y)
| Set the data np.array for y
|
| ACCEPTS: 1D array
|
| update_from(self, other)
| copy properties from other to self
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| axes
| The :class:`~matplotlib.axes.Axes` instance the artist
| resides in, or *None*.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| drawStyleKeys = [u'default', u'steps-mid', u'steps-pre', u'steps-post'...
|
| drawStyles = {u'default': u'_draw_lines', u'steps': u'_draw_steps_pre'...
|
| fillStyles = (u'full', u'left', u'right', u'bottom', u'top', u'none')
|
| filled_markers = (u'o', u'v', u'^', u'<', u'>', u'8', u's', u'p', u'*'...
|
| lineStyles = {u'': u'_draw_nothing', u' ': u'_draw_nothing', u'-': u'_...
|
| markers = {None: u'nothing', 0: u'tickleft', 1: u'tickright', 2: u'tic...
|
| validCap = (u'butt', u'round', u'projecting')
|
| validJoin = (u'miter', u'round', u'bevel')
|
| zorder = 2
|
| ----------------------------------------------------------------------
| Methods inherited from matplotlib.artist.Artist:
|
| add_callback(self, func)
| Adds a callback function that will be called whenever one of
| the :class:`Artist`'s properties changes.
|
| Returns an *id* that is useful for removing the callback with
| :meth:`remove_callback` later.
|
| convert_xunits(self, x)
| For artists in an axes, if the xaxis has units support,
| convert *x* using xaxis unit type
|
| convert_yunits(self, y)
| For artists in an axes, if the yaxis has units support,
| convert *y* using yaxis unit type
|
| findobj(self, match=None, include_self=True)
| Find artist objects.
|
| Recursively find all :class:`~matplotlib.artist.Artist` instances
| contained in self.
|
| *match* can be
|
| - None: return all objects contained in artist.
|
| - function with signature ``boolean = match(artist)``
| used to filter matches
|
| - class instance: e.g., Line2D. Only return artists of class type.
|
| If *include_self* is True (default), include self in the list to be
| checked for a match.
|
| 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_axes(self)
| Return the :class:`~matplotlib.axes.Axes` instance the artist
| resides in, or *None*.
|
| This has been deprecated in mpl 1.5, please use the
| axes property. Will be removed in 1.7 or 2.0.
|
| 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 :class:`~matplotlib.figure.Figure` instance the
| artist belongs to.
|
| get_gid(self)
| Returns the group id
|
| get_label(self)
| Get the label used for this artist in the legend.
|
| get_path_effects(self)
|
| get_picker(self)
| Return the picker object used by this artist
|
| get_rasterized(self)
| return True if the artist is to be rasterized
|
| get_sketch_params(self)
| Returns the sketch parameters for the artist.
|
| Returns
| -------
| sketch_params : tuple or `None`
|
| A 3-tuple with the following elements:
|
| * `scale`: The amplitude of the wiggle perpendicular to the
| source line.
|
| * `length`: The length of the wiggle along the line.
|
| * `randomness`: The scale factor by which the length is
| shrunken or expanded.
|
| May return `None` if no sketch parameters were set.
|
| get_snap(self)
| Returns the snap setting which may be:
|
| * True: snap vertices to the nearest pixel center
|
| * False: leave vertices as-is
|
| * None: (auto) If the path contains only rectilinear line
| segments, round to the nearest pixel center
|
| Only supported by the Agg and MacOSX backends.
|
| get_transform(self)
| Return the :class:`~matplotlib.transforms.Transform`
| instance used by this artist.
|
| get_transformed_clip_path_and_affine(self)
| Return the clip path with the non-affine part of its
| transformation applied, and the remaining affine part of its
| transformation.
|
| get_url(self)
| Returns the url
|
| get_visible(self)
| Return the artist's visiblity
|
| get_zorder(self)
| Return the :class:`Artist`'s zorder.
|
| have_units(self)
| Return *True* if units are set on the *x* or *y* axes
|
| hitlist(self, event)
| List the children of the artist which contain the mouse event *event*.
|
| is_figure_set(self)
| Returns True if the artist is assigned to a
| :class:`~matplotlib.figure.Figure`.
|
| is_transform_set(self)
| Returns *True* if :class:`Artist` has a transform explicitly
| set.
|
| pchanged(self)
| Fire an event when property changed, calling all of the
| registered callbacks.
|
| pick(self, mouseevent)
| 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 agg_filter fuction.
|
| set_alpha(self, alpha)
| Set the alpha value used for blending - not supported on
| all backends.
|
| ACCEPTS: float (0.0 transparent through 1.0 opaque)
|
| set_animated(self, b)
| Set the artist's animation state.
|
| ACCEPTS: [True | False]
|
| set_axes(self, axes)
| Set the :class:`~matplotlib.axes.Axes` instance in which the
| artist resides, if any.
|
| This has been deprecated in mpl 1.5, please use the
| axes property. Will be removed in 1.7 or 2.0.
|
| ACCEPTS: an :class:`~matplotlib.axes.Axes` instance
|
| set_clip_box(self, clipbox)
| Set the artist's clip :class:`~matplotlib.transforms.Bbox`.
|
| ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance
|
| set_clip_on(self, b)
| Set whether artist uses clipping.
|
| When False artists will be visible out side of the axes which
| can lead to unexpected results.
|
| ACCEPTS: [True | False]
|
| set_clip_path(self, path, transform=None)
| Set the artist's clip path, which may be:
|
| * a :class:`~matplotlib.patches.Patch` (or subclass) instance
|
| * a :class:`~matplotlib.path.Path` instance, in which case
| an optional :class:`~matplotlib.transforms.Transform`
| instance may be provided, which will be applied to the
| path before using it for clipping.
|
| * *None*, to remove the clipping path
|
| For efficiency, if the path happens to be an axis-aligned
| rectangle, this method will set the clipping box to the
| corresponding rectangle and set the clipping path to *None*.
|
| ACCEPTS: [ (:class:`~matplotlib.path.Path`,
| :class:`~matplotlib.transforms.Transform`) |
| :class:`~matplotlib.patches.Patch` | None ]
|
| set_contains(self, picker)
| Replace the contains test used by this artist. The new picker
| should be a callable function which determines whether the
| artist is hit by the mouse event::
|
| hit, props = picker(artist, mouseevent)
|
| If the mouse event is over the artist, return *hit* = *True*
| and *props* is a dictionary of properties you want returned
| with the contains test.
|
| ACCEPTS: a callable function
|
| set_figure(self, fig)
| Set the :class:`~matplotlib.figure.Figure` instance the artist
| belongs to.
|
| ACCEPTS: a :class:`matplotlib.figure.Figure` instance
|
| set_gid(self, gid)
| Sets the (group) id for the artist
|
| ACCEPTS: an id string
|
| set_label(self, s)
| Set the label to *s* for auto legend.
|
| ACCEPTS: string or anything printable with '%s' conversion.
|
| set_path_effects(self, path_effects)
| set path_effects, which should be a list of instances of
| matplotlib.patheffect._Base class or its derivatives.
|
| set_rasterized(self, rasterized)
| Force rasterized (bitmap) drawing in vector backend output.
|
| Defaults to None, which implies the backend's default behavior
|
| ACCEPTS: [True | False | None]
|
| set_sketch_params(self, scale=None, length=None, randomness=None)
| Sets the sketch parameters.
|
| Parameters
| ----------
|
| scale : float, optional
| The amplitude of the wiggle perpendicular to the source
| line, in pixels. If scale is `None`, or not provided, no
| sketch filter will be provided.
|
| length : float, optional
| The length of the wiggle along the line, in pixels
| (default 128.0)
|
| randomness : float, optional
| The scale factor by which the length is shrunken or
| expanded (default 16.0)
|
| set_snap(self, snap)
| Sets the snap setting which may be:
|
| * True: snap vertices to the nearest pixel center
|
| * False: leave vertices as-is
|
| * None: (auto) If the path contains only rectilinear line
| segments, round to the nearest pixel center
|
| Only supported by the Agg and MacOSX backends.
|
| set_url(self, url)
| Sets the url for the artist
|
| ACCEPTS: a url string
|
| set_visible(self, b)
| Set the artist's visiblity.
|
| ACCEPTS: [True | False]
|
| set_zorder(self, level)
| Set the zorder for the artist. Artists with lower zorder
| values are drawn first.
|
| ACCEPTS: any number
|
| update(self, props)
| Update the properties of this :class:`Artist` from the
| dictionary *prop*.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from matplotlib.artist.Artist:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| 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 = u'Artist'
class VertexSelector(__builtin__.object)
| Manage the callbacks to maintain a list of selected vertices for
| :class:`matplotlib.lines.Line2D`. Derived classes should override
| :meth:`~matplotlib.lines.VertexSelector.process_selected` to do
| something with the picks.
|
| Here is an example which highlights the selected verts with red
| circles::
|
| import numpy as np
| import matplotlib.pyplot as plt
| import matplotlib.lines as lines
|
| class HighlightSelected(lines.VertexSelector):
| def __init__(self, line, fmt='ro', **kwargs):
| lines.VertexSelector.__init__(self, line)
| self.markers, = self.axes.plot([], [], fmt, **kwargs)
|
| def process_selected(self, ind, xs, ys):
| self.markers.set_data(xs, ys)
| self.canvas.draw()
|
| fig = plt.figure()
| ax = fig.add_subplot(111)
| x, y = np.random.rand(2, 30)
| line, = ax.plot(x, y, 'bs-', picker=5)
|
| selector = HighlightSelected(line)
| plt.show()
|
| Methods defined here:
|
| __init__(self, line)
| Initialize the class with a :class:`matplotlib.lines.Line2D`
| instance. The line should already be added to some
| :class:`matplotlib.axes.Axes` instance and should have the
| picker property set.
|
| onpick(self, event)
| When the line is picked, update the set of selected indicies.
|
| process_selected(self, ind, xs, ys)
| Default "do nothing" implementation of the
| :meth:`process_selected` method.
|
| *ind* are the indices of the selected vertices. *xs* and *ys*
| are the coordinates of the selected vertices.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
FUNCTIONS
segment_hits(cx, cy, x, y, radius)
Determine if any line segments are within radius of a
point. Returns the list of line segments that are within that
radius.
DATA
CARETDOWN = 7
CARETDOWNBASE = 11
CARETLEFT = 4
CARETLEFTBASE = 8
CARETRIGHT = 5
CARETRIGHTBASE = 9
CARETUP = 6
CARETUPBASE = 10
TICKDOWN = 3
TICKLEFT = 0
TICKRIGHT = 1
TICKUP = 2
absolute_import = _Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0...
division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192...
drawStyles = {u'default': u'_draw_lines', u'steps': u'_draw_steps_pre'...
fillStyles = (u'full', u'left', u'right', u'bottom', u'top', u'none')
lineMarkers = {None: u'nothing', 0: u'tickleft', 1: u'tickright', 2: u...
lineStyles = {u'': u'_draw_nothing', u' ': u'_draw_nothing', u'-': u'_...
ls_mapper = {u'-': u'solid', u'--': u'dashed', u'-.': u'dashdot', u':'...
ls_mapper_r = {u'dashdot': u'-.', u'dashed': u'--', u'dotted': u':', u...
print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)...
rcParams = RcParams({u'_internal.classic_mode': False,
...or.width...
unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', ...
In [7]:
plt.plot(t, t, linewidth=2.0)
Out[7]:
[<matplotlib.lines.Line2D at 0x10bc63f50>]
In [8]:
line, = plt.plot(t, t, '-')
line.set_antialiased(False) # turn off antialising
In [9]:
lines = plt.plot(t, t, t, t**2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
Out[9]:
[None, None, None, None]
In [10]:
lines = plt.plot(t, t, t, t**2, t, t**3)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
Out[10]:
[None, None, None, None, None, None]
In [11]:
# to get properties
plt.setp(lines)
agg_filter: unknown
alpha: float (0.0 transparent through 1.0 opaque)
animated: [True | False]
antialiased or aa: [True | False]
axes: an :class:`~matplotlib.axes.Axes` instance
clip_box: a :class:`matplotlib.transforms.Bbox` instance
clip_on: [True | False]
clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
color or c: any matplotlib color
contains: a callable function
dash_capstyle: ['butt' | 'round' | 'projecting']
dash_joinstyle: ['miter' | 'round' | 'bevel']
dashes: sequence of on/off ink in points
drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post']
figure: a :class:`matplotlib.figure.Figure` instance
fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
gid: an id string
label: string or anything printable with '%s' conversion.
linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
linewidth or lw: float value in points
marker: :mod:`A valid marker style <matplotlib.markers>`
markeredgecolor or mec: any matplotlib color
markeredgewidth or mew: float value in points
markerfacecolor or mfc: any matplotlib color
markerfacecoloralt or mfcalt: any matplotlib color
markersize or ms: float
markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effects: unknown
picker: float distance in points or callable pick function ``fn(artist, event)``
pickradius: float distance in points
rasterized: [True | False | None]
sketch_params: unknown
snap: unknown
solid_capstyle: ['butt' | 'round' | 'projecting']
solid_joinstyle: ['miter' | 'round' | 'bevel']
transform: a :class:`matplotlib.transforms.Transform` instance
url: a url string
visible: [True | False]
xdata: 1D array
ydata: 1D array
zorder: any number
In [12]:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
In [13]:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(2,1,1)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(2,1,2)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
The subplot() command specifies numrows, numcols, fignum where fignum ranges from 1 to numrows*numcols.
In [14]:
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])
plt.figure(2) # a second figure
plt.plot([4, 5, 6]) # creates a subplot(111) by default
plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
Out[14]:
<matplotlib.text.Text at 0x10c05c450>
In [15]:
# Fixing random state for reproducibility
np.random.seed(19680801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
In [27]:
help(plt.hist)
Help on function hist in module matplotlib.pyplot:
hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u'bar', align=u'mid', orientation=u'vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
Plot a histogram.
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
Multiple data can be provided via *x* as a list of datasets
of potentially different length ([*x0*, *x1*, ...]), or as
a 2-D ndarray in which each column is a dataset. Note that
the ndarray form is transposed relative to the list form.
Masked arrays are not supported at present.
Parameters
----------
x : (n,) array or sequence of (n,) arrays
Input values, this takes either a single array or a sequency of
arrays which are not required to be of the same length
bins : integer or array_like or 'auto', optional
If an integer is given, `bins + 1` bin edges are returned,
consistently with :func:`numpy.histogram` for numpy version >=
1.3.
Unequally spaced bins are supported if `bins` is a sequence.
If Numpy 1.11 is installed, may also be ``'auto'``.
Default is taken from the rcParam ``hist.bins``.
range : tuple or None, optional
The lower and upper range of the bins. Lower and upper outliers
are ignored. If not provided, `range` is (x.min(), x.max()). Range
has no effect if `bins` is a sequence.
If `bins` is a sequence or `range` is specified, autoscaling
is based on the specified bin range instead of the
range of x.
Default is ``None``
normed : boolean, optional
If `True`, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)`dbin)``, i.e., the integral of the histogram will sum
to 1. If *stacked* is also *True*, the sum of the histograms is
normalized to 1.
Default is ``False``
weights : (n, ) array_like or None, optional
An array of weights, of the same shape as `x`. Each value in `x`
only contributes its associated weight towards the bin count
(instead of 1). If `normed` is True, the weights are normalized,
so that the integral of the density over the range remains 1.
Default is ``None``
cumulative : boolean, optional
If `True`, then a histogram is computed where each bin gives the
counts in that bin plus all bins for smaller values. The last bin
gives the total number of datapoints. If `normed` is also `True`
then the histogram is normalized such that the last bin equals 1.
If `cumulative` evaluates to less than 0 (e.g., -1), the direction
of accumulation is reversed. In this case, if `normed` is also
`True`, then the histogram is normalized such that the first bin
equals 1.
Default is ``False``
bottom : array_like, scalar, or None
Location of the bottom baseline of each bin. If a scalar,
the base line for each bin is shifted by the same amount.
If an array, each bin is shifted independently and the length
of bottom must match the number of bins. If None, defaults to 0.
Default is ``None``
histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, optional
The type of histogram to draw.
- 'bar' is a traditional bar-type histogram. If multiple data
are given the bars are aranged side by side.
- 'barstacked' is a bar-type histogram where multiple
data are stacked on top of each other.
- 'step' generates a lineplot that is by default
unfilled.
- 'stepfilled' generates a lineplot that is by default
filled.
Default is 'bar'
align : {'left', 'mid', 'right'}, optional
Controls how the histogram is plotted.
- 'left': bars are centered on the left bin edges.
- 'mid': bars are centered between the bin edges.
- 'right': bars are centered on the right bin edges.
Default is 'mid'
orientation : {'horizontal', 'vertical'}, optional
If 'horizontal', `~matplotlib.pyplot.barh` will be used for
bar-type histograms and the *bottom* kwarg will be the left edges.
rwidth : scalar or None, optional
The relative width of the bars as a fraction of the bin width. If
`None`, automatically compute the width.
Ignored if `histtype` is 'step' or 'stepfilled'.
Default is ``None``
log : boolean, optional
If `True`, the histogram axis will be set to a log scale. If `log`
is `True` and `x` is a 1D array, empty bins will be filtered out
and only the non-empty (`n`, `bins`, `patches`) will be returned.
Default is ``False``
color : color or array_like of colors or None, optional
Color spec or sequence of color specs, one per dataset. Default
(`None`) uses the standard line color sequence.
Default is ``None``
label : string or None, optional
String, or sequence of strings to match multiple datasets. Bar
charts yield multiple patches per dataset, but only the first gets
the label, so that the legend command will work as expected.
default is ``None``
stacked : boolean, optional
If `True`, multiple data are stacked on top of each other If
`False` multiple data are aranged side by side if histtype is
'bar' or on top of each other if histtype is 'step'
Default is ``False``
Returns
-------
n : array or list of arrays
The values of the histogram bins. See **normed** and **weights**
for a description of the possible semantics. If input **x** is an
array, then this is an array of length **nbins**. If input is a
sequence arrays ``[data1, data2,..]``, then this is a list of
arrays with the values of the histograms for each of the arrays
in the same order.
bins : array
The edges of the bins. Length nbins + 1 (nbins left edges and right
edge of last bin). Always a single array even when multiple data
sets are passed in.
patches : list or list of lists
Silent list of individual patches used to create the histogram
or list of such list if multiple input datasets.
Other Parameters
----------------
kwargs : `~matplotlib.patches.Patch` properties
See also
--------
hist2d : 2D histograms
Notes
-----
Until numpy release 1.5, the underlying numpy histogram function was
incorrect with `normed`=`True` if bin sizes were unequal. MPL
inherited that error. It is now corrected within MPL when using
earlier numpy versions.
Examples
--------
.. plot:: mpl_examples/statistics/histogram_demo_features.py
.. note::
In addition to the above described arguments, this function can take a
**data** keyword argument. If such a **data** argument is given, the
following arguments are replaced by **data[<arg>]**:
* All arguments with the following names: 'weights', 'x'.
In [16]:
import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()
In [17]:
from matplotlib.ticker import NullFormatter # useful for `logit` scale
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
In [18]:
plt.style.use('ggplot')
In [19]:
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()
In [20]:
"""
=====
Decay
=====
This example showcases a sinusoidal decay animation.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(t=0):
cnt = 0
while cnt < 1000:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
del ydata[:]
line.set_data(xdata, ydata)
return line,
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []
def run(data):
# update the data
t, y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)
return line,
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
repeat=False, init_func=init)
plt.show()
In [43]:
ax = plt.subplot2grid((2,2),(0, 0))
In [44]:
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))
In [48]:
#import matplotlib.pyplot as plt
#import matplotlib.gridspec as gridspec
#import numpy as np
try:
from itertools import product
except ImportError:
# product is new in v 2.6
def product(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):
return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)
fig = plt.figure(figsize=(8, 8))
# gridspec inside gridspec
outer_grid = gridspec.GridSpec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a, b = int(i/4)+1,i%4+1
for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):
ax = plt.Subplot(fig, inner_grid[j])
ax.plot(*squiggle_xy(a, b, c, d))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
all_axes = fig.get_axes()
#show only the outside spines
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
plt.show()
Content source: jArumugam/python-notes
Similar notebooks: