desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Get the ytick lines as a list of Line2D instances'
| def get_yticklines(self):
| return cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines())
|
'Return *True* if any artists have been added to axes.
This should not be used to determine whether the *dataLim*
need to be updated, and may not actually be useful for
anything.'
| def has_data(self):
| return ((((len(self.collections) + len(self.images)) + len(self.lines)) + len(self.patches)) > 0)
|
'Add any :class:`~matplotlib.artist.Artist` to the axes'
| def add_artist(self, a):
| a.set_axes(self)
self.artists.append(a)
self._set_artist_props(a)
a.set_clip_path(self.patch)
a._remove_method = (lambda h: self.artists.remove(h))
|
'add a :class:`~matplotlib.collections.Collection` instance
to the axes'
| def add_collection(self, collection, autolim=True):
| label = collection.get_label()
if (not label):
collection.set_label(('collection%d' % len(self.collections)))
self.collections.append(collection)
self._set_artist_props(collection)
collection.set_clip_path(self.patch)
if autolim:
if (collection._paths and len(collection._paths)):
self.update_datalim(collection.get_datalim(self.transData))
collection._remove_method = (lambda h: self.collections.remove(h))
|
'Add a :class:`~matplotlib.lines.Line2D` to the list of plot
lines'
| def add_line(self, line):
| self._set_artist_props(line)
line.set_clip_path(self.patch)
self._update_line_limits(line)
if (not line.get_label()):
line.set_label(('_line%d' % len(self.lines)))
self.lines.append(line)
line._remove_method = (lambda h: self.lines.remove(h))
|
'Add a :class:`~matplotlib.patches.Patch` *p* to the list of
axes patches; the clipbox will be set to the Axes clipping
box. If the transform is not set, it will be set to
:attr:`transData`.'
| def add_patch(self, p):
| self._set_artist_props(p)
p.set_clip_path(self.patch)
self._update_patch_limits(p)
self.patches.append(p)
p._remove_method = (lambda h: self.patches.remove(h))
|
'update the data limits for patch *p*'
| def _update_patch_limits(self, patch):
| if (isinstance(patch, mpatches.Rectangle) and ((patch.get_width() == 0) or (patch.get_height() == 0))):
return
vertices = patch.get_path().vertices
if (vertices.size > 0):
xys = patch.get_patch_transform().transform(vertices)
if (patch.get_data_transform() != self.transData):
transform = (patch.get_data_transform() + self.transData.inverted())
xys = transform.transform(xys)
self.update_datalim(xys, updatex=patch.x_isdata, updatey=patch.y_isdata)
|
'Add a :class:`~matplotlib.tables.Table` instance to the
list of axes tables'
| def add_table(self, tab):
| self._set_artist_props(tab)
self.tables.append(tab)
tab.set_clip_path(self.patch)
tab._remove_method = (lambda h: self.tables.remove(h))
|
'recompute the data limits based on current artists'
| def relim(self):
| self.dataLim.ignore(True)
self.ignore_existing_data_limits = True
for line in self.lines:
self._update_line_limits(line)
for p in self.patches:
self._update_patch_limits(p)
|
'Update the data lim bbox with seq of xy tups or equiv. 2-D array'
| def update_datalim(self, xys, updatex=True, updatey=True):
| if (iterable(xys) and (not len(xys))):
return
if (not ma.isMaskedArray(xys)):
xys = np.asarray(xys)
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, updatex=updatex, updatey=updatey)
self.ignore_existing_data_limits = False
|
'Update the data lim bbox with seq of xy tups'
| def update_datalim_numerix(self, x, y):
| if (iterable(x) and (not len(x))):
return
self.dataLim.update_from_data(x, y, self.ignore_existing_data_limits)
self.ignore_existing_data_limits = False
|
'Update the datalim to include the given
:class:`~matplotlib.transforms.Bbox` *bounds*'
| def update_datalim_bounds(self, bounds):
| self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds]))
|
'look for unit *kwargs* and update the axis instances as necessary'
| def _process_unit_info(self, xdata=None, ydata=None, kwargs=None):
| if ((self.xaxis is None) or (self.yaxis is None)):
return
if (xdata is not None):
if (not self.xaxis.have_units()):
self.xaxis.update_units(xdata)
if (ydata is not None):
if (not self.yaxis.have_units()):
self.yaxis.update_units(ydata)
if (kwargs is not None):
xunits = kwargs.pop('xunits', self.xaxis.units)
if (xunits != self.xaxis.units):
self.xaxis.set_units(xunits)
if (xdata is not None):
self.xaxis.update_units(xdata)
yunits = kwargs.pop('yunits', self.yaxis.units)
if (yunits != self.yaxis.units):
self.yaxis.set_units(yunits)
if (ydata is not None):
self.yaxis.update_units(ydata)
|
'return *True* if the given *mouseevent* (in display coords)
is in the Axes'
| def in_axes(self, mouseevent):
| return self.patch.contains(mouseevent)[0]
|
'Get whether autoscaling is applied on plot commands'
| def get_autoscale_on(self):
| return self._autoscaleon
|
'Set whether autoscaling is applied on plot commands
accepts: [ *True* | *False* ]'
| def set_autoscale_on(self, b):
| self._autoscaleon = b
|
'autoscale the view limits using the data limits. You can
selectively autoscale only a single axis, eg, the xaxis by
setting *scaley* to *False*. The autoscaling preserves any
axis direction reversal that has already been done.'
| def autoscale_view(self, tight=False, scalex=True, scaley=True):
| if (not self._autoscaleon):
return
if scalex:
xshared = self._shared_x_axes.get_siblings(self)
dl = [ax.dataLim for ax in xshared]
bb = mtransforms.BboxBase.union(dl)
(x0, x1) = bb.intervalx
if scaley:
yshared = self._shared_y_axes.get_siblings(self)
dl = [ax.dataLim for ax in yshared]
bb = mtransforms.BboxBase.union(dl)
(y0, y1) = bb.intervaly
if (tight or ((len(self.images) > 0) and (len(self.lines) == 0) and (len(self.patches) == 0))):
if scalex:
self.set_xbound(x0, x1)
if scaley:
self.set_ybound(y0, y1)
return
if scalex:
XL = self.xaxis.get_major_locator().view_limits(x0, x1)
self.set_xbound(XL)
if scaley:
YL = self.yaxis.get_major_locator().view_limits(y0, y1)
self.set_ybound(YL)
|
'Draw everything (plot lines, axes, labels)'
| def draw(self, renderer=None, inframe=False):
| if (renderer is None):
renderer = self._cachedRenderer
if (renderer is None):
raise RuntimeError('No renderer defined')
if (not self.get_visible()):
return
renderer.open_group('axes')
self.apply_aspect()
if (self.axison and self._frameon):
self.patch.draw(renderer)
artists = []
if ((len(self.images) <= 1) or renderer.option_image_nocomposite()):
for im in self.images:
im.draw(renderer)
else:
mag = renderer.get_image_magnification()
ims = [(im.make_image(mag), 0, 0) for im in self.images if im.get_visible()]
(l, b, r, t) = self.bbox.extents
width = (mag * ((round(r) + 0.5) - (round(l) - 0.5)))
height = (mag * ((round(t) + 0.5) - (round(b) - 0.5)))
im = mimage.from_images(height, width, ims)
im.is_grayscale = False
(l, b, w, h) = self.bbox.bounds
renderer.draw_image(round(l), round(b), im, self.bbox, self.patch.get_path(), self.patch.get_transform())
artists.extend(self.collections)
artists.extend(self.patches)
artists.extend(self.lines)
artists.extend(self.texts)
artists.extend(self.artists)
if (self.axison and (not inframe)):
if self._axisbelow:
self.xaxis.set_zorder(0.5)
self.yaxis.set_zorder(0.5)
else:
self.xaxis.set_zorder(2.5)
self.yaxis.set_zorder(2.5)
artists.extend([self.xaxis, self.yaxis])
if (not inframe):
artists.append(self.title)
artists.extend(self.tables)
if (self.legend_ is not None):
artists.append(self.legend_)
if (self.axison and self._frameon):
artists.append(self.frame)
dsu = [(a.zorder, i, a) for (i, a) in enumerate(artists) if (not a.get_animated())]
dsu.sort()
for (zorder, i, a) in dsu:
a.draw(renderer)
renderer.close_group('axes')
self._cachedRenderer = renderer
|
'This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)'
| def draw_artist(self, a):
| assert (self._cachedRenderer is not None)
a.draw(self._cachedRenderer)
|
'This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)'
| def redraw_in_frame(self):
| assert (self._cachedRenderer is not None)
self.draw(self._cachedRenderer, inframe=True)
|
'Get whether the axes rectangle patch is drawn'
| def get_frame_on(self):
| return self._frameon
|
'Set whether the axes rectangle patch is drawn
ACCEPTS: [ *True* | *False* ]'
| def set_frame_on(self, b):
| self._frameon = b
|
'Get whether axis below is true or not'
| def get_axisbelow(self):
| return self._axisbelow
|
'Set whether the axis ticks and gridlines are above or below most artists
ACCEPTS: [ *True* | *False* ]'
| def set_axisbelow(self, b):
| self._axisbelow = b
|
'call signature::
grid(self, b=None, **kwargs)
Set the axes grids on or off; *b* is a boolean
If *b* is *None* and ``len(kwargs)==0``, toggle the grid state. If
*kwargs* are supplied, it is assumed that you want a grid and *b*
is thus set to *True*
*kawrgs* are used to set the grid line properties, eg::
ax.grid(color=\'r\', linestyle=\'-\', linewidth=2)
Valid :class:`~matplotlib.lines.Line2D` kwargs are
%(Line2D)s'
| def grid(self, b=None, **kwargs):
| if len(kwargs):
b = True
self.xaxis.grid(b, **kwargs)
self.yaxis.grid(b, **kwargs)
|
'Convenience method for manipulating the ScalarFormatter
used by default for linear axes.
Optional keyword arguments:
Keyword Description
*style* [ \'sci\' (or \'scientific\') | \'plain\' ]
plain turns off scientific notation
*scilimits* (m, n), pair of integers; if *style*
is \'sci\', scientific notation will
be used for numbers outside the range
10`-m`:sup: to 10`n`:sup:.
Use (0,0) to include all numbers.
*axis* [ \'x\' | \'y\' | \'both\' ]
Only the major ticks are affected.
If the method is called when the
:class:`~matplotlib.ticker.ScalarFormatter` is not the
:class:`~matplotlib.ticker.Formatter` being used, an
:exc:`AttributeError` will be raised.'
| def ticklabel_format(self, **kwargs):
| style = kwargs.pop('style', '').lower()
scilimits = kwargs.pop('scilimits', None)
if (scilimits is not None):
try:
(m, n) = scilimits
((m + n) + 1)
except (ValueError, TypeError):
raise ValueError('scilimits must be a sequence of 2 integers')
axis = kwargs.pop('axis', 'both').lower()
if (style[:3] == 'sci'):
sb = True
elif (style in ['plain', 'comma']):
sb = False
if (style == 'plain'):
cb = False
else:
cb = True
raise NotImplementedError, 'comma style remains to be added'
elif (style == ''):
sb = None
else:
raise ValueError, '%s is not a valid style value'
try:
if (sb is not None):
if ((axis == 'both') or (axis == 'x')):
self.xaxis.major.formatter.set_scientific(sb)
if ((axis == 'both') or (axis == 'y')):
self.yaxis.major.formatter.set_scientific(sb)
if (scilimits is not None):
if ((axis == 'both') or (axis == 'x')):
self.xaxis.major.formatter.set_powerlimits(scilimits)
if ((axis == 'both') or (axis == 'y')):
self.yaxis.major.formatter.set_powerlimits(scilimits)
except AttributeError:
raise AttributeError('This method only works with the ScalarFormatter.')
|
'turn off the axis'
| def set_axis_off(self):
| self.axison = False
|
'turn on the axis'
| def set_axis_on(self):
| self.axison = True
|
'Return the axis background color'
| def get_axis_bgcolor(self):
| return self._axisbg
|
'set the axes background color
ACCEPTS: any matplotlib color - see
:func:`~matplotlib.pyplot.colors`'
| def set_axis_bgcolor(self, color):
| self._axisbg = color
self.patch.set_facecolor(color)
|
'Invert the x-axis.'
| def invert_xaxis(self):
| (left, right) = self.get_xlim()
self.set_xlim(right, left)
|
'Returns True if the x-axis is inverted.'
| def xaxis_inverted(self):
| (left, right) = self.get_xlim()
return (right < left)
|
'Returns the x-axis numerical bounds where::
lowerBound < upperBound'
| def get_xbound(self):
| (left, right) = self.get_xlim()
if (left < right):
return (left, right)
else:
return (right, left)
|
'Set the lower and upper numerical bounds of the x-axis.
This method will honor axes inversion regardless of parameter order.'
| def set_xbound(self, lower=None, upper=None):
| if ((upper is None) and iterable(lower)):
(lower, upper) = lower
(old_lower, old_upper) = self.get_xbound()
if (lower is None):
lower = old_lower
if (upper is None):
upper = old_upper
if self.xaxis_inverted():
if (lower < upper):
self.set_xlim(upper, lower)
else:
self.set_xlim(lower, upper)
elif (lower < upper):
self.set_xlim(lower, upper)
else:
self.set_xlim(upper, lower)
|
'Get the x-axis range [*xmin*, *xmax*]'
| def get_xlim(self):
| return tuple(self.viewLim.intervalx)
|
'call signature::
set_xlim(self, *args, **kwargs)
Set the limits for the xaxis
Returns the current xlimits as a length 2 tuple: [*xmin*, *xmax*]
Examples::
set_xlim((valmin, valmax))
set_xlim(valmin, valmax)
set_xlim(xmin=1) # xmax unchanged
set_xlim(xmax=1) # xmin unchanged
Keyword arguments:
*ymin*: scalar
the min of the ylim
*ymax*: scalar
the max of the ylim
*emit*: [ True | False ]
notify observers of lim change
ACCEPTS: len(2) sequence of floats'
| def set_xlim(self, xmin=None, xmax=None, emit=True, **kwargs):
| if ((xmax is None) and iterable(xmin)):
(xmin, xmax) = xmin
self._process_unit_info(xdata=(xmin, xmax))
if (xmin is not None):
xmin = self.convert_xunits(xmin)
if (xmax is not None):
xmax = self.convert_xunits(xmax)
(old_xmin, old_xmax) = self.get_xlim()
if (xmin is None):
xmin = old_xmin
if (xmax is None):
xmax = old_xmax
(xmin, xmax) = mtransforms.nonsingular(xmin, xmax, increasing=False)
(xmin, xmax) = self.xaxis.limit_range_for_scale(xmin, xmax)
self.viewLim.intervalx = (xmin, xmax)
if emit:
self.callbacks.process('xlim_changed', self)
for other in self._shared_x_axes.get_siblings(self):
if (other is not self):
other.set_xlim(self.viewLim.intervalx, emit=False)
if ((other.figure != self.figure) and (other.figure.canvas is not None)):
other.figure.canvas.draw_idle()
return (xmin, xmax)
|
'call signature::
set_xscale(value)
Set the scaling of the x-axis: %(scale)s
ACCEPTS: [%(scale)s]
Different kwargs are accepted, depending on the scale:
%(scale_docs)s'
| def set_xscale(self, value, **kwargs):
| self.xaxis.set_scale(value, **kwargs)
self.autoscale_view()
self._update_transScale()
|
'Return the x ticks as a list of locations'
| def get_xticks(self, minor=False):
| return self.xaxis.get_ticklocs(minor=minor)
|
'Set the x ticks with list of *ticks*
ACCEPTS: sequence of floats'
| def set_xticks(self, ticks, minor=False):
| return self.xaxis.set_ticks(ticks, minor=minor)
|
'Get the xtick labels as a list of Text instances'
| def get_xmajorticklabels(self):
| return cbook.silent_list('Text xticklabel', self.xaxis.get_majorticklabels())
|
'Get the xtick labels as a list of Text instances'
| def get_xminorticklabels(self):
| return cbook.silent_list('Text xticklabel', self.xaxis.get_minorticklabels())
|
'Get the xtick labels as a list of Text instances'
| def get_xticklabels(self, minor=False):
| return cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels(minor=minor))
|
'call signature::
set_xticklabels(labels, fontdict=None, minor=False, **kwargs)
Set the xtick labels with list of strings *labels*. Return a
list of axis text instances.
*kwargs* set the :class:`~matplotlib.text.Text` properties.
Valid properties are
%(Text)s
ACCEPTS: sequence of strings'
| def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs):
| return self.xaxis.set_ticklabels(labels, fontdict, minor=minor, **kwargs)
|
'Invert the y-axis.'
| def invert_yaxis(self):
| (left, right) = self.get_ylim()
self.set_ylim(right, left)
|
'Returns True if the y-axis is inverted.'
| def yaxis_inverted(self):
| (left, right) = self.get_ylim()
return (right < left)
|
'Return y-axis numerical bounds in the form of lowerBound < upperBound'
| def get_ybound(self):
| (left, right) = self.get_ylim()
if (left < right):
return (left, right)
else:
return (right, left)
|
'Set the lower and upper numerical bounds of the y-axis.
This method will honor axes inversion regardless of parameter order.'
| def set_ybound(self, lower=None, upper=None):
| if ((upper is None) and iterable(lower)):
(lower, upper) = lower
(old_lower, old_upper) = self.get_ybound()
if (lower is None):
lower = old_lower
if (upper is None):
upper = old_upper
if self.yaxis_inverted():
if (lower < upper):
self.set_ylim(upper, lower)
else:
self.set_ylim(lower, upper)
elif (lower < upper):
self.set_ylim(lower, upper)
else:
self.set_ylim(upper, lower)
|
'Get the y-axis range [*ymin*, *ymax*]'
| def get_ylim(self):
| return tuple(self.viewLim.intervaly)
|
'call signature::
set_ylim(self, *args, **kwargs):
Set the limits for the yaxis; v = [ymin, ymax]::
set_ylim((valmin, valmax))
set_ylim(valmin, valmax)
set_ylim(ymin=1) # ymax unchanged
set_ylim(ymax=1) # ymin unchanged
Keyword arguments:
*ymin*: scalar
the min of the ylim
*ymax*: scalar
the max of the ylim
*emit*: [ True | False ]
notify observers of lim change
Returns the current ylimits as a length 2 tuple
ACCEPTS: len(2) sequence of floats'
| def set_ylim(self, ymin=None, ymax=None, emit=True, **kwargs):
| if ((ymax is None) and iterable(ymin)):
(ymin, ymax) = ymin
if (ymin is not None):
ymin = self.convert_yunits(ymin)
if (ymax is not None):
ymax = self.convert_yunits(ymax)
(old_ymin, old_ymax) = self.get_ylim()
if (ymin is None):
ymin = old_ymin
if (ymax is None):
ymax = old_ymax
(ymin, ymax) = mtransforms.nonsingular(ymin, ymax, increasing=False)
(ymin, ymax) = self.yaxis.limit_range_for_scale(ymin, ymax)
self.viewLim.intervaly = (ymin, ymax)
if emit:
self.callbacks.process('ylim_changed', self)
for other in self._shared_y_axes.get_siblings(self):
if (other is not self):
other.set_ylim(self.viewLim.intervaly, emit=False)
if ((other.figure != self.figure) and (other.figure.canvas is not None)):
other.figure.canvas.draw_idle()
return (ymin, ymax)
|
'call signature::
set_yscale(value)
Set the scaling of the y-axis: %(scale)s
ACCEPTS: [%(scale)s]
Different kwargs are accepted, depending on the scale:
%(scale_docs)s'
| def set_yscale(self, value, **kwargs):
| self.yaxis.set_scale(value, **kwargs)
self.autoscale_view()
self._update_transScale()
|
'Return the y ticks as a list of locations'
| def get_yticks(self, minor=False):
| return self.yaxis.get_ticklocs(minor=minor)
|
'Set the y ticks with list of *ticks*
ACCEPTS: sequence of floats
Keyword arguments:
*minor*: [ False | True ]
Sets the minor ticks if True'
| def set_yticks(self, ticks, minor=False):
| return self.yaxis.set_ticks(ticks, minor=minor)
|
'Get the xtick labels as a list of Text instances'
| def get_ymajorticklabels(self):
| return cbook.silent_list('Text yticklabel', self.yaxis.get_majorticklabels())
|
'Get the xtick labels as a list of Text instances'
| def get_yminorticklabels(self):
| return cbook.silent_list('Text yticklabel', self.yaxis.get_minorticklabels())
|
'Get the xtick labels as a list of Text instances'
| def get_yticklabels(self, minor=False):
| return cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels(minor=minor))
|
'call signature::
set_yticklabels(labels, fontdict=None, minor=False, **kwargs)
Set the ytick labels with list of strings *labels*. Return a list of
:class:`~matplotlib.text.Text` instances.
*kwargs* set :class:`~matplotlib.text.Text` properties for the labels.
Valid properties are
%(Text)s
ACCEPTS: sequence of strings'
| def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs):
| return self.yaxis.set_ticklabels(labels, fontdict, minor=minor, **kwargs)
|
'Sets up x-axis ticks and labels that treat the x data as dates.
*tz* is the time zone to use in labeling dates. Defaults to rc value.'
| def xaxis_date(self, tz=None):
| (xmin, xmax) = self.dataLim.intervalx
if (xmin == 0.0):
dmax = today = datetime.date.today()
dmin = (today - datetime.timedelta(days=10))
self._process_unit_info(xdata=(dmin, dmax))
(dmin, dmax) = self.convert_xunits([dmin, dmax])
self.viewLim.intervalx = (dmin, dmax)
self.dataLim.intervalx = (dmin, dmax)
locator = self.xaxis.get_major_locator()
if (not isinstance(locator, mdates.DateLocator)):
locator = mdates.AutoDateLocator(tz)
self.xaxis.set_major_locator(locator)
if (self.viewLim.intervalx[0] == 0.0):
self.viewLim.intervalx = tuple(self.dataLim.intervalx)
locator.refresh()
formatter = self.xaxis.get_major_formatter()
if (not isinstance(formatter, mdates.DateFormatter)):
formatter = mdates.AutoDateFormatter(locator, tz)
self.xaxis.set_major_formatter(formatter)
|
'Sets up y-axis ticks and labels that treat the y data as dates.
*tz* is the time zone to use in labeling dates. Defaults to rc value.'
| def yaxis_date(self, tz=None):
| (ymin, ymax) = self.dataLim.intervaly
if (ymin == 0.0):
dmax = today = datetime.date.today()
dmin = (today - datetime.timedelta(days=10))
self._process_unit_info(ydata=(dmin, dmax))
(dmin, dmax) = self.convert_yunits([dmin, dmax])
self.viewLim.intervaly = (dmin, dmax)
self.dataLim.intervaly = (dmin, dmax)
locator = self.yaxis.get_major_locator()
if (not isinstance(locator, mdates.DateLocator)):
locator = mdates.AutoDateLocator(tz)
self.yaxis.set_major_locator(locator)
if (self.viewLim.intervaly[0] == 0.0):
self.viewLim.intervaly = tuple(self.dataLim.intervaly)
locator.refresh()
formatter = self.xaxis.get_major_formatter()
if (not isinstance(formatter, mdates.DateFormatter)):
formatter = mdates.AutoDateFormatter(locator, tz)
self.yaxis.set_major_formatter(formatter)
|
'Return *x* string formatted. This function will use the attribute
self.fmt_xdata if it is callable, else will fall back on the xaxis
major formatter'
| def format_xdata(self, x):
| try:
return self.fmt_xdata(x)
except TypeError:
func = self.xaxis.get_major_formatter().format_data_short
val = func(x)
return val
|
'Return y string formatted. This function will use the
:attr:`fmt_ydata` attribute if it is callable, else will fall
back on the yaxis major formatter'
| def format_ydata(self, y):
| try:
return self.fmt_ydata(y)
except TypeError:
func = self.yaxis.get_major_formatter().format_data_short
val = func(y)
return val
|
'return a format string formatting the *x*, *y* coord'
| def format_coord(self, x, y):
| if (x is None):
x = '???'
if (y is None):
y = '???'
xs = self.format_xdata(x)
ys = self.format_ydata(y)
return ('x=%s, y=%s' % (xs, ys))
|
'Return *True* if this axes support the zoom box'
| def can_zoom(self):
| return True
|
'Get whether the axes responds to navigation commands'
| def get_navigate(self):
| return self._navigate
|
'Set whether the axes responds to navigation toolbar commands
ACCEPTS: [ True | False ]'
| def set_navigate(self, b):
| self._navigate = b
|
'Get the navigation toolbar button status: \'PAN\', \'ZOOM\', or None'
| def get_navigate_mode(self):
| return self._navigate_mode
|
'Set the navigation toolbar button status;
.. warning::
this is not a user-API function.'
| def set_navigate_mode(self, b):
| self._navigate_mode = b
|
'Called when a pan operation has started.
*x*, *y* are the mouse coordinates in display coords.
button is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
.. note::
Intended to be overridden by new projection types.'
| def start_pan(self, x, y, button):
| self._pan_start = cbook.Bunch(lim=self.viewLim.frozen(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), bbox=self.bbox.frozen(), x=x, y=y)
|
'Called when a pan operation completes (when the mouse button
is up.)
.. note::
Intended to be overridden by new projection types.'
| def end_pan(self):
| del self._pan_start
|
'Called when the mouse moves during a pan operation.
*button* is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
*key* is a "shift" key
*x*, *y* are the mouse coordinates in display coords.
.. note::
Intended to be overridden by new projection types.'
| def drag_pan(self, button, key, x, y):
| def format_deltas(key, dx, dy):
if (key == 'control'):
if (abs(dx) > abs(dy)):
dy = dx
else:
dx = dy
elif (key == 'x'):
dy = 0
elif (key == 'y'):
dx = 0
elif (key == 'shift'):
if ((2 * abs(dx)) < abs(dy)):
dx = 0
elif ((2 * abs(dy)) < abs(dx)):
dy = 0
elif (abs(dx) > abs(dy)):
dy = ((dy / abs(dy)) * abs(dx))
else:
dx = ((dx / abs(dx)) * abs(dy))
return (dx, dy)
p = self._pan_start
dx = (x - p.x)
dy = (y - p.y)
if ((dx == 0) and (dy == 0)):
return
if (button == 1):
(dx, dy) = format_deltas(key, dx, dy)
result = p.bbox.translated((- dx), (- dy)).transformed(p.trans_inverse)
elif (button == 3):
try:
dx = ((- dx) / float(self.bbox.width))
dy = ((- dy) / float(self.bbox.height))
(dx, dy) = format_deltas(key, dx, dy)
if (self.get_aspect() != 'auto'):
dx = (0.5 * (dx + dy))
dy = dx
alpha = np.power(10.0, (dx, dy))
start = p.trans_inverse.transform_point((p.x, p.y))
lim_points = p.lim.get_points()
result = (start + (alpha * (lim_points - start)))
result = mtransforms.Bbox(result)
except OverflowError:
warnings.warn('Overflow while panning')
return
self.set_xlim(*result.intervalx)
self.set_ylim(*result.intervaly)
|
'return the cursor propertiess as a (*linewidth*, *color*)
tuple, where *linewidth* is a float and *color* is an RGBA
tuple'
| def get_cursor_props(self):
| return self._cursorProps
|
'Set the cursor property as::
ax.set_cursor_props(linewidth, color)
or::
ax.set_cursor_props((linewidth, color))
ACCEPTS: a (*float*, *color*) tuple'
| def set_cursor_props(self, *args):
| if (len(args) == 1):
(lw, c) = args[0]
elif (len(args) == 2):
(lw, c) = args
else:
raise ValueError('args must be a (linewidth, color) tuple')
c = mcolors.colorConverter.to_rgba(c)
self._cursorProps = (lw, c)
|
'Register observers to be notified when certain events occur. Register
with callback functions with the following signatures. The function
has the following signature::
func(ax) # where ax is the instance making the callback.
The following events can be connected to:
\'xlim_changed\',\'ylim_changed\'
The connection id is is returned - you can use this with
disconnect to disconnect from the axes event'
| def connect(self, s, func):
| raise DeprecationWarning('use the callbacks CallbackRegistry instance instead')
|
'disconnect from the Axes event.'
| def disconnect(self, cid):
| raise DeprecationWarning('use the callbacks CallbackRegistry instance instead')
|
'return a list of child artists'
| def get_children(self):
| children = []
children.append(self.xaxis)
children.append(self.yaxis)
children.extend(self.lines)
children.extend(self.patches)
children.extend(self.texts)
children.extend(self.tables)
children.extend(self.artists)
children.extend(self.images)
if (self.legend_ is not None):
children.append(self.legend_)
children.extend(self.collections)
children.append(self.title)
children.append(self.patch)
children.append(self.frame)
return children
|
'Test whether the mouse event occured in the axes.
Returns T/F, {}'
| def contains(self, mouseevent):
| if callable(self._contains):
return self._contains(self, mouseevent)
return self.patch.contains(mouseevent)
|
'call signature::
pick(mouseevent)
each child artist will fire a pick event if mouseevent is over
the artist and the artist has picker set'
| def pick(self, *args):
| if (len(args) > 1):
raise DeprecationWarning('New pick API implemented -- see API_CHANGES in the src distribution')
martist.Artist.pick(self, args[0])
|
'Return the artist under point that is closest to the *x*, *y*.
If *trans* is *None*, *x*, and *y* are in window coords,
(0,0 = lower left). Otherwise, *trans* is a
:class:`~matplotlib.transforms.Transform` that specifies the
coordinate system of *x*, *y*.
The selection of artists from amongst which the pick function
finds an artist can be narrowed using the optional keyword
argument *among*. If provided, this should be either a sequence
of permitted artists or a function taking an artist as its
argument and returning a true value if and only if that artist
can be selected.
Note this algorithm calculates distance to the vertices of the
polygon, so if you want to pick a patch, click on the edge!'
| def __pick(self, x, y, trans=None, among=None):
| if (trans is not None):
xywin = trans.transform_point((x, y))
else:
xywin = (x, y)
def dist_points(p1, p2):
'return the distance between two points'
(x1, y1) = p1
(x2, y2) = p2
return math.sqrt((((x1 - x2) ** 2) + ((y1 - y2) ** 2)))
def dist_x_y(p1, x, y):
'*x* and *y* are arrays; return the distance to the closest point'
(x1, y1) = p1
return min(np.sqrt((((x - x1) ** 2) + ((y - y1) ** 2))))
def dist(a):
if isinstance(a, Text):
bbox = a.get_window_extent()
(l, b, w, h) = bbox.bounds
verts = ((l, b), (l, (b + h)), ((l + w), (b + h)), ((l + w), b))
(xt, yt) = zip(*verts)
elif isinstance(a, Patch):
path = a.get_path()
tverts = a.get_transform().transform_path(path)
(xt, yt) = zip(*tverts)
elif isinstance(a, mlines.Line2D):
xdata = a.get_xdata(orig=False)
ydata = a.get_ydata(orig=False)
(xt, yt) = a.get_transform().numerix_x_y(xdata, ydata)
return dist_x_y(xywin, np.asarray(xt), np.asarray(yt))
artists = ((self.lines + self.patches) + self.texts)
if callable(among):
artists = filter(test, artists)
elif iterable(among):
amongd = dict([(k, 1) for k in among])
artists = [a for a in artists if (a in amongd)]
elif (among is None):
pass
else:
raise ValueError('among must be callable or iterable')
if (not len(artists)):
return None
ds = [(dist(a), a) for a in artists]
ds.sort()
return ds[0][1]
|
'Get the title text string.'
| def get_title(self):
| return self.title.get_text()
|
'call signature::
set_title(label, fontdict=None, **kwargs):
Set the title for the axes.
kwargs are Text properties:
%(Text)s
ACCEPTS: str
.. seealso::
:meth:`text`:
for information on how override and the optional args work'
| def set_title(self, label, fontdict=None, **kwargs):
| default = {'fontsize': rcParams['axes.titlesize'], 'verticalalignment': 'bottom', 'horizontalalignment': 'center'}
self.title.set_text(label)
self.title.update(default)
if (fontdict is not None):
self.title.update(fontdict)
self.title.update(kwargs)
return self.title
|
'Get the xlabel text string.'
| def get_xlabel(self):
| label = self.xaxis.get_label()
return label.get_text()
|
'call signature::
set_xlabel(xlabel, fontdict=None, **kwargs)
Set the label for the xaxis.
Valid kwargs are Text properties:
%(Text)s
ACCEPTS: str
.. seealso::
:meth:`text`:
for information on how override and the optional args work'
| def set_xlabel(self, xlabel, fontdict=None, **kwargs):
| label = self.xaxis.get_label()
label.set_text(xlabel)
if (fontdict is not None):
label.update(fontdict)
label.update(kwargs)
return label
|
'Get the ylabel text string.'
| def get_ylabel(self):
| label = self.yaxis.get_label()
return label.get_text()
|
'call signature::
set_ylabel(ylabel, fontdict=None, **kwargs)
Set the label for the yaxis
Valid kwargs are Text properties:
%(Text)s
ACCEPTS: str
.. seealso::
:meth:`text`:
for information on how override and the optional args work'
| def set_ylabel(self, ylabel, fontdict=None, **kwargs):
| label = self.yaxis.get_label()
label.set_text(ylabel)
if (fontdict is not None):
label.update(fontdict)
label.update(kwargs)
return label
|
'call signature::
text(x, y, s, fontdict=None, **kwargs)
Add text in string *s* to axis at location *x*, *y*, data
coordinates.
Keyword arguments:
*fontdict*:
A dictionary to override the default text properties.
If *fontdict* is *None*, the defaults are determined by your rc
parameters.
*withdash*: [ False | True ]
Creates a :class:`~matplotlib.text.TextWithDash` instance
instead of a :class:`~matplotlib.text.Text` instance.
Individual keyword arguments can be used to override any given
parameter::
text(x, y, s, fontsize=12)
The default transform specifies that text is in data coords,
alternatively, you can specify text in axis coords (0,0 is
lower-left and 1,1 is upper-right). The example below places
text in the center of the axes::
text(0.5, 0.5,\'matplotlib\',
horizontalalignment=\'center\',
verticalalignment=\'center\',
transform = ax.transAxes)
You can put a rectangular box around the text instance (eg. to
set a background color) by using the keyword *bbox*. *bbox* is
a dictionary of :class:`matplotlib.patches.Rectangle`
properties. For example::
text(x, y, s, bbox=dict(facecolor=\'red\', alpha=0.5))
Valid kwargs are :class:`matplotlib.text.Text` properties:
%(Text)s'
| def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
| default = {'verticalalignment': 'bottom', 'horizontalalignment': 'left', 'transform': self.transData}
if withdash:
t = mtext.TextWithDash(x=x, y=y, text=s)
else:
t = mtext.Text(x=x, y=y, text=s)
self._set_artist_props(t)
t.update(default)
if (fontdict is not None):
t.update(fontdict)
t.update(kwargs)
self.texts.append(t)
t._remove_method = (lambda h: self.texts.remove(h))
if ('clip_on' in kwargs):
t.set_clip_box(self.bbox)
return t
|
'call signature::
annotate(s, xy, xytext=None, xycoords=\'data\',
textcoords=\'data\', arrowprops=None, **kwargs)
Keyword arguments:
%(Annotation)s
.. plot:: mpl_examples/pylab_examples/annotation_demo2.py'
| def annotate(self, *args, **kwargs):
| a = mtext.Annotation(*args, **kwargs)
a.set_transform(mtransforms.IdentityTransform())
self._set_artist_props(a)
if kwargs.has_key('clip_on'):
a.set_clip_path(self.patch)
self.texts.append(a)
return a
|
'call signature::
axhline(y=0, xmin=0, xmax=1, **kwargs)
Axis Horizontal Line
Draw a horizontal line at *y* from *xmin* to *xmax*. With the
default values of *xmin* = 0 and *xmax* = 1, this line will
always span the horizontal extent of the axes, regardless of
the xlim settings, even if you change them, eg. with the
:meth:`set_xlim` command. That is, the horizontal extent is
in axes coords: 0=left, 0.5=middle, 1.0=right but the *y*
location is in data coordinates.
Return value is the :class:`~matplotlib.lines.Line2D`
instance. kwargs are the same as kwargs to plot, and can be
used to control the line properties. Eg.,
* draw a thick red hline at *y* = 0 that spans the xrange
>>> axhline(linewidth=4, color=\'r\')
* draw a default hline at *y* = 1 that spans the xrange
>>> axhline(y=1)
* draw a default hline at *y* = .5 that spans the the middle half of
the xrange
>>> axhline(y=.5, xmin=0.25, xmax=0.75)
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`axhspan`:
for example plot and source code'
| def axhline(self, y=0, xmin=0, xmax=1, **kwargs):
| (ymin, ymax) = self.get_ybound()
yy = self.convert_yunits(y)
scaley = ((yy < ymin) or (yy > ymax))
trans = mtransforms.blended_transform_factory(self.transAxes, self.transData)
l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs)
l.x_isdata = False
self.add_line(l)
self.autoscale_view(scalex=False, scaley=scaley)
return l
|
'call signature::
axvline(x=0, ymin=0, ymax=1, **kwargs)
Axis Vertical Line
Draw a vertical line at *x* from *ymin* to *ymax*. With the
default values of *ymin* = 0 and *ymax* = 1, this line will
always span the vertical extent of the axes, regardless of the
xlim settings, even if you change them, eg. with the
:meth:`set_xlim` command. That is, the vertical extent is in
axes coords: 0=bottom, 0.5=middle, 1.0=top but the *x* location
is in data coordinates.
Return value is the :class:`~matplotlib.lines.Line2D`
instance. kwargs are the same as kwargs to plot, and can be
used to control the line properties. Eg.,
* draw a thick red vline at *x* = 0 that spans the yrange
>>> axvline(linewidth=4, color=\'r\')
* draw a default vline at *x* = 1 that spans the yrange
>>> axvline(x=1)
* draw a default vline at *x* = .5 that spans the the middle half of
the yrange
>>> axvline(x=.5, ymin=0.25, ymax=0.75)
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`axhspan`:
for example plot and source code'
| def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
| (xmin, xmax) = self.get_xbound()
xx = self.convert_xunits(x)
scalex = ((xx < xmin) or (xx > xmax))
trans = mtransforms.blended_transform_factory(self.transData, self.transAxes)
l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)
l.y_isdata = False
self.add_line(l)
self.autoscale_view(scalex=scalex, scaley=False)
return l
|
'call signature::
axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)
Axis Horizontal Span.
*y* coords are in data units and *x* coords are in axes (relative
0-1) units.
Draw a horizontal span (rectangle) from *ymin* to *ymax*.
With the default values of *xmin* = 0 and *xmax* = 1, this
always spans the xrange, regardless of the xlim settings, even
if you change them, eg. with the :meth:`set_xlim` command.
That is, the horizontal extent is in axes coords: 0=left,
0.5=middle, 1.0=right but the *y* location is in data
coordinates.
Return value is a :class:`matplotlib.patches.Polygon`
instance.
Examples:
* draw a gray rectangle from *y* = 0.25-0.75 that spans the
horizontal extent of the axes
>>> axhspan(0.25, 0.75, facecolor=\'0.5\', alpha=0.5)
Valid kwargs are :class:`~matplotlib.patches.Polygon` properties:
%(Polygon)s
**Example:**
.. plot:: mpl_examples/pylab_examples/axhspan_demo.py'
| def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
| trans = mtransforms.blended_transform_factory(self.transAxes, self.transData)
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
(xmin, xmax) = self.convert_xunits([xmin, xmax])
(ymin, ymax) = self.convert_yunits([ymin, ymax])
verts = ((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin))
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
p.x_isdata = False
self.add_patch(p)
return p
|
'call signature::
axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
Axis Vertical Span.
*x* coords are in data units and *y* coords are in axes (relative
0-1) units.
Draw a vertical span (rectangle) from *xmin* to *xmax*. With
the default values of *ymin* = 0 and *ymax* = 1, this always
spans the yrange, regardless of the ylim settings, even if you
change them, eg. with the :meth:`set_ylim` command. That is,
the vertical extent is in axes coords: 0=bottom, 0.5=middle,
1.0=top but the *y* location is in data coordinates.
Return value is the :class:`matplotlib.patches.Polygon`
instance.
Examples:
* draw a vertical green translucent rectangle from x=1.25 to 1.55 that
spans the yrange of the axes
>>> axvspan(1.25, 1.55, facecolor=\'g\', alpha=0.5)
Valid kwargs are :class:`~matplotlib.patches.Polygon`
properties:
%(Polygon)s
.. seealso::
:meth:`axhspan`:
for example plot and source code'
| def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
| trans = mtransforms.blended_transform_factory(self.transData, self.transAxes)
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
(xmin, xmax) = self.convert_xunits([xmin, xmax])
(ymin, ymax) = self.convert_yunits([ymin, ymax])
verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
p.y_isdata = False
self.add_patch(p)
return p
|
'call signature::
hlines(y, xmin, xmax, colors=\'k\', linestyles=\'solid\', **kwargs)
Plot horizontal lines at each *y* from *xmin* to *xmax*.
Returns the :class:`~matplotlib.collections.LineCollection`
that was added.
Required arguments:
*y*:
a 1-D numpy array or iterable.
*xmin* and *xmax*:
can be scalars or ``len(x)`` numpy arrays. If they are
scalars, then the respective values are constant, else the
widths of the lines are determined by *xmin* and *xmax*.
Optional keyword arguments:
*colors*:
a line collections color argument, either a single color
or a ``len(y)`` list of colors
*linestyles*:
[ \'solid\' | \'dashed\' | \'dashdot\' | \'dotted\' ]
**Example:**
.. plot:: mpl_examples/pylab_examples/hline_demo.py'
| def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', label='', **kwargs):
| if (kwargs.get('fmt') is not None):
raise DeprecationWarning('hlines now uses a collections.LineCollection and not a list of Line2D to draw; see API_CHANGES')
y = self.convert_yunits(y)
xmin = self.convert_xunits(xmin)
xmax = self.convert_xunits(xmax)
if (not iterable(y)):
y = [y]
if (not iterable(xmin)):
xmin = [xmin]
if (not iterable(xmax)):
xmax = [xmax]
y = np.asarray(y)
xmin = np.asarray(xmin)
xmax = np.asarray(xmax)
if (len(xmin) == 1):
xmin = np.resize(xmin, y.shape)
if (len(xmax) == 1):
xmax = np.resize(xmax, y.shape)
if (len(xmin) != len(y)):
raise ValueError, 'xmin and y are unequal sized sequences'
if (len(xmax) != len(y)):
raise ValueError, 'xmax and y are unequal sized sequences'
verts = [((thisxmin, thisy), (thisxmax, thisy)) for (thisxmin, thisxmax, thisy) in zip(xmin, xmax, y)]
coll = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label)
self.add_collection(coll)
coll.update(kwargs)
minx = min(xmin.min(), xmax.min())
maxx = max(xmin.max(), xmax.max())
miny = y.min()
maxy = y.max()
corners = ((minx, miny), (maxx, maxy))
self.update_datalim(corners)
self.autoscale_view()
return coll
|
'call signature::
vlines(x, ymin, ymax, color=\'k\', linestyles=\'solid\')
Plot vertical lines at each *x* from *ymin* to *ymax*. *ymin*
or *ymax* can be scalars or len(*x*) numpy arrays. If they are
scalars, then the respective values are constant, else the
heights of the lines are determined by *ymin* and *ymax*.
*colors*
a line collections color args, either a single color
or a len(*x*) list of colors
*linestyles*
one of [ \'solid\' | \'dashed\' | \'dashdot\' | \'dotted\' ]
Returns the :class:`matplotlib.collections.LineCollection`
that was added.
kwargs are :class:`~matplotlib.collections.LineCollection` properties:
%(LineCollection)s'
| def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', **kwargs):
| if (kwargs.get('fmt') is not None):
raise DeprecationWarning('vlines now uses a collections.LineCollection and not a list of Line2D to draw; see API_CHANGES')
self._process_unit_info(xdata=x, ydata=ymin, kwargs=kwargs)
x = self.convert_xunits(x)
ymin = self.convert_yunits(ymin)
ymax = self.convert_yunits(ymax)
if (not iterable(x)):
x = [x]
if (not iterable(ymin)):
ymin = [ymin]
if (not iterable(ymax)):
ymax = [ymax]
x = np.asarray(x)
ymin = np.asarray(ymin)
ymax = np.asarray(ymax)
if (len(ymin) == 1):
ymin = np.resize(ymin, x.shape)
if (len(ymax) == 1):
ymax = np.resize(ymax, x.shape)
if (len(ymin) != len(x)):
raise ValueError, 'ymin and x are unequal sized sequences'
if (len(ymax) != len(x)):
raise ValueError, 'ymax and x are unequal sized sequences'
Y = np.array([ymin, ymax]).T
verts = [((thisx, thisymin), (thisx, thisymax)) for (thisx, (thisymin, thisymax)) in zip(x, Y)]
coll = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label)
self.add_collection(coll)
coll.update(kwargs)
minx = min(x)
maxx = max(x)
miny = min(min(ymin), min(ymax))
maxy = max(max(ymin), max(ymax))
corners = ((minx, miny), (maxx, maxy))
self.update_datalim(corners)
self.autoscale_view()
return coll
|
'Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following is
legal::
plot(x, y) # plot x and y using default line style and color
plot(x, y, \'bo\') # plot x and y using blue circle markers
plot(y) # plot y using x as index array 0..N-1
plot(y, \'r+\') # ditto, but with red plusses
If *x* and/or *y* is 2-dimensional, then the corresponding columns
will be plotted.
An arbitrary number of *x*, *y*, *fmt* groups can be
specified, as in::
a.plot(x1, y1, \'g^\', x2, y2, \'g-\')
Return value is a list of lines that were added.
The following format string characters are accepted to control
the line style or marker:
character description
\'-\' solid line style
\'--\' dashed line style
\'-.\' dash-dot line style
\':\' dotted line style
\'.\' point marker
\',\' pixel marker
\'o\' circle marker
\'v\' triangle_down marker
\'^\' triangle_up marker
\'<\' triangle_left marker
\'>\' triangle_right marker
\'1\' tri_down marker
\'2\' tri_up marker
\'3\' tri_left marker
\'4\' tri_right marker
\'s\' square marker
\'p\' pentagon marker
\'*\' star marker
\'h\' hexagon1 marker
\'H\' hexagon2 marker
\'+\' plus marker
\'x\' x marker
\'D\' diamond marker
\'d\' thin_diamond marker
\'|\' vline marker
\'_\' hline marker
The following color abbreviations are supported:
character color
\'b\' blue
\'g\' green
\'r\' red
\'c\' cyan
\'m\' magenta
\'y\' yellow
\'k\' black
\'w\' white
In addition, you can specify colors in many weird and
wonderful ways, including full names (``\'green\'``), hex
strings (``\'#008000\'``), RGB or RGBA tuples (``(0,1,0,1)``) or
grayscale intensities as a string (``\'0.8\'``). Of these, the
string specifications can be used in place of a ``fmt`` group,
but the tuple forms can be used only as ``kwargs``.
Line styles and colors are combined in a single format string, as in
``\'bo\'`` for blue circles.
The *kwargs* can be used to set line properties (any property that has
a ``set_*`` method). You can use this to set a line label (for auto
legends), linewidth, anitialising, marker face color, etc. Here is an
example::
plot([1,2,3], [1,2,3], \'go-\', label=\'line 1\', linewidth=2)
plot([1,2,3], [1,4,9], \'rs\', label=\'line 2\')
axis([0, 4, 0, 10])
legend()
If you make multiple lines with one plot command, the kwargs
apply to all those lines, e.g.::
plot(x1, y1, x2, y2, antialised=False)
Neither line will be antialiased.
You do not need to use format strings, which are just
abbreviations. All of the line properties can be controlled
by keyword arguments. For example, you can set the color,
marker, linestyle, and markercolor with::
plot(x, y, color=\'green\', linestyle=\'dashed\', marker=\'o\',
markerfacecolor=\'blue\', markersize=12). See
:class:`~matplotlib.lines.Line2D` for details.
The kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
kwargs *scalex* and *scaley*, if defined, are passed on to
:meth:`~matplotlib.axes.Axes.autoscale_view` to determine
whether the *x* and *y* axes are autoscaled; the default is
*True*.'
| def plot(self, *args, **kwargs):
| scalex = kwargs.pop('scalex', True)
scaley = kwargs.pop('scaley', True)
if (not self._hold):
self.cla()
lines = []
for line in self._get_lines(*args, **kwargs):
self.add_line(line)
lines.append(line)
self.autoscale_view(scalex=scalex, scaley=scaley)
return lines
|
'call signature::
plot_date(x, y, fmt=\'bo\', tz=None, xdate=True, ydate=False, **kwargs)
Similar to the :func:`~matplotlib.pyplot.plot` command, except
the *x* or *y* (or both) data is considered to be dates, and the
axis is labeled accordingly.
*x* and/or *y* can be a sequence of dates represented as float
days since 0001-01-01 UTC.
Keyword arguments:
*fmt*: string
The plot format string.
*tz*: [ None | timezone string ]
The time zone to use in labeling dates. If *None*, defaults to rc
value.
*xdate*: [ True | False ]
If *True*, the *x*-axis will be labeled with dates.
*ydate*: [ False | True ]
If *True*, the *y*-axis will be labeled with dates.
Note if you are using custom date tickers and formatters, it
may be necessary to set the formatters/locators after the call
to :meth:`plot_date` since :meth:`plot_date` will set the
default tick locator to
:class:`matplotlib.ticker.AutoDateLocator` (if the tick
locator is not already set to a
:class:`matplotlib.ticker.DateLocator` instance) and the
default tick formatter to
:class:`matplotlib.ticker.AutoDateFormatter` (if the tick
formatter is not already set to a
:class:`matplotlib.ticker.DateFormatter` instance).
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:mod:`~matplotlib.dates`:
for helper functions
:func:`~matplotlib.dates.date2num`,
:func:`~matplotlib.dates.num2date` and
:func:`~matplotlib.dates.drange`:
for help on creating the required floating point
dates.'
| def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False, **kwargs):
| if (not self._hold):
self.cla()
ret = self.plot(x, y, fmt, **kwargs)
if xdate:
self.xaxis_date(tz)
if ydate:
self.yaxis_date(tz)
self.autoscale_view()
return ret
|
'call signature::
loglog(*args, **kwargs)
Make a plot with log scaling on the *x* and *y* axis.
:func:`~matplotlib.pyplot.loglog` supports all the keyword
arguments of :func:`~matplotlib.pyplot.plot` and
:meth:`matplotlib.axes.Axes.set_xscale` /
:meth:`matplotlib.axes.Axes.set_yscale`.
Notable keyword arguments:
*basex*/*basey*: scalar > 1
base of the *x*/*y* logarithm
*subsx*/*subsy*: [ None | sequence ]
the location of the minor *x*/*y* ticks; *None* defaults
to autosubs, which depend on the number of decades in the
plot; see :meth:`matplotlib.axes.Axes.set_xscale` /
:meth:`matplotlib.axes.Axes.set_yscale` for details
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/log_demo.py'
| def loglog(self, *args, **kwargs):
| if (not self._hold):
self.cla()
dx = {'basex': kwargs.pop('basex', 10), 'subsx': kwargs.pop('subsx', None)}
dy = {'basey': kwargs.pop('basey', 10), 'subsy': kwargs.pop('subsy', None)}
self.set_xscale('log', **dx)
self.set_yscale('log', **dy)
b = self._hold
self._hold = True
l = self.plot(*args, **kwargs)
self._hold = b
return l
|
'call signature::
semilogx(*args, **kwargs)
Make a plot with log scaling on the *x* axis.
:func:`semilogx` supports all the keyword arguments of
:func:`~matplotlib.pyplot.plot` and
:meth:`matplotlib.axes.Axes.set_xscale`.
Notable keyword arguments:
*basex*: scalar > 1
base of the *x* logarithm
*subsx*: [ None | sequence ]
The location of the minor xticks; *None* defaults to
autosubs, which depend on the number of decades in the
plot; see :meth:`~matplotlib.axes.Axes.set_xscale` for
details.
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`loglog`:
For example code and figure'
| def semilogx(self, *args, **kwargs):
| if (not self._hold):
self.cla()
d = {'basex': kwargs.pop('basex', 10), 'subsx': kwargs.pop('subsx', None)}
self.set_xscale('log', **d)
b = self._hold
self._hold = True
l = self.plot(*args, **kwargs)
self._hold = b
return l
|
'call signature::
semilogy(*args, **kwargs)
Make a plot with log scaling on the *y* axis.
:func:`semilogy` supports all the keyword arguments of
:func:`~matplotlib.pylab.plot` and
:meth:`matplotlib.axes.Axes.set_yscale`.
Notable keyword arguments:
*basey*: scalar > 1
Base of the *y* logarithm
*subsy*: [ None | sequence ]
The location of the minor yticks; *None* defaults to
autosubs, which depend on the number of decades in the
plot; see :meth:`~matplotlib.axes.Axes.set_yscale` for
details.
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`loglog`:
For example code and figure'
| def semilogy(self, *args, **kwargs):
| if (not self._hold):
self.cla()
d = {'basey': kwargs.pop('basey', 10), 'subsy': kwargs.pop('subsy', None)}
self.set_yscale('log', **d)
b = self._hold
self._hold = True
l = self.plot(*args, **kwargs)
self._hold = b
return l
|
'call signature::
acorr(x, normed=False, detrend=mlab.detrend_none, usevlines=False,
maxlags=None, **kwargs)
Plot the autocorrelation of *x*. If *normed* = *True*,
normalize the data by the autocorrelation at 0-th lag. *x* is
detrended by the *detrend* callable (default no normalization).
Data are plotted as ``plot(lags, c, **kwargs)``
Return value is a tuple (*lags*, *c*, *line*) where:
- *lags* are a length 2*maxlags+1 lag vector
- *c* is the 2*maxlags+1 auto correlation vector
- *line* is a :class:`~matplotlib.lines.Line2D` instance
returned by :meth:`plot`
The default *linestyle* is None and the default *marker* is
``\'o\'``, though these can be overridden with keyword args.
The cross correlation is performed with
:func:`numpy.correlate` with *mode* = 2.
If *usevlines* is *True*, :meth:`~matplotlib.axes.Axes.vlines`
rather than :meth:`~matplotlib.axes.Axes.plot` is used to draw
vertical lines from the origin to the acorr. Otherwise, the
plot style is determined by the kwargs, which are
:class:`~matplotlib.lines.Line2D` properties.
*maxlags* is a positive integer detailing the number of lags
to show. The default value of *None* will return all
:math:`2 \mathrm{len}(x) - 1` lags.
The return value is a tuple (*lags*, *c*, *linecol*, *b*)
where
- *linecol* is the
:class:`~matplotlib.collections.LineCollection`
- *b* is the *x*-axis.
.. seealso::
:meth:`~matplotlib.axes.Axes.plot` or
:meth:`~matplotlib.axes.Axes.vlines`: For documentation on
valid kwargs.
**Example:**
:func:`~matplotlib.pyplot.xcorr` above, and
:func:`~matplotlib.pyplot.acorr` below.
**Example:**
.. plot:: mpl_examples/pylab_examples/xcorr_demo.py'
| def acorr(self, x, **kwargs):
| return self.xcorr(x, x, **kwargs)
|
'call signature::
xcorr(x, y, normed=False, detrend=mlab.detrend_none,
usevlines=False, **kwargs):
Plot the cross correlation between *x* and *y*. If *normed* =
*True*, normalize the data by the cross correlation at 0-th
lag. *x* and y are detrended by the *detrend* callable
(default no normalization). *x* and *y* must be equal length.
Data are plotted as ``plot(lags, c, **kwargs)``
Return value is a tuple (*lags*, *c*, *line*) where:
- *lags* are a length ``2*maxlags+1`` lag vector
- *c* is the ``2*maxlags+1`` auto correlation vector
- *line* is a :class:`~matplotlib.lines.Line2D` instance
returned by :func:`~matplotlib.pyplot.plot`.
The default *linestyle* is *None* and the default *marker* is
\'o\', though these can be overridden with keyword args. The
cross correlation is performed with :func:`numpy.correlate`
with *mode* = 2.
If *usevlines* is *True*:
:func:`~matplotlib.pyplot.vlines`
rather than :func:`~matplotlib.pyplot.plot` is used to draw
vertical lines from the origin to the xcorr. Otherwise the
plotstyle is determined by the kwargs, which are
:class:`~matplotlib.lines.Line2D` properties.
The return value is a tuple (*lags*, *c*, *linecol*, *b*)
where *linecol* is the
:class:`matplotlib.collections.LineCollection` instance and
*b* is the *x*-axis.
*maxlags* is a positive integer detailing the number of lags to show.
The default value of *None* will return all ``(2*len(x)-1)`` lags.
**Example:**
:func:`~matplotlib.pyplot.xcorr` above, and
:func:`~matplotlib.pyplot.acorr` below.
**Example:**
.. plot:: mpl_examples/pylab_examples/xcorr_demo.py'
| def xcorr(self, x, y, normed=False, detrend=mlab.detrend_none, usevlines=False, maxlags=None, **kwargs):
| Nx = len(x)
if (Nx != len(y)):
raise ValueError('x and y must be equal length')
x = detrend(np.asarray(x))
y = detrend(np.asarray(y))
c = np.correlate(x, y, mode=2)
if normed:
c /= np.sqrt((np.dot(x, x) * np.dot(y, y)))
if (maxlags is None):
maxlags = (Nx - 1)
if ((maxlags >= Nx) or (maxlags < 1)):
raise ValueError(('maglags must be None or strictly positive < %d' % Nx))
lags = np.arange((- maxlags), (maxlags + 1))
c = c[((Nx - 1) - maxlags):(Nx + maxlags)]
if usevlines:
a = self.vlines(lags, [0], c, **kwargs)
b = self.axhline(**kwargs)
else:
kwargs.setdefault('marker', 'o')
kwargs.setdefault('linestyle', 'None')
(a,) = self.plot(lags, c, **kwargs)
b = None
return (lags, c, a, b)
|
'call signature::
legend(*args, **kwargs)
Place a legend on the current axes at location *loc*. Labels are a
sequence of strings and *loc* can be a string or an integer specifying
the legend location.
To make a legend with existing lines::
legend()
:meth:`legend` by itself will try and build a legend using the label
property of the lines/patches/collections. You can set the label of
a line by doing::
plot(x, y, label=\'my data\')
or::
line.set_label(\'my data\').
If label is set to \'_nolegend_\', the item will not be shown in
legend.
To automatically generate the legend from labels::
legend( (\'label1\', \'label2\', \'label3\') )
To make a legend for a list of lines and labels::
legend( (line1, line2, line3), (\'label1\', \'label2\', \'label3\') )
To make a legend at a given location, using a location argument::
legend( (\'label1\', \'label2\', \'label3\'), loc=\'upper left\')
or::
legend( (line1, line2, line3), (\'label1\', \'label2\', \'label3\'), loc=2)
The location 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
If none of these are locations are suitable, loc can be a 2-tuple
giving x,y in axes coords, ie::
loc = 0, 1 # left top
loc = 0.5, 0.5 # center
Keyword arguments:
*isaxes*: [ True | False ]
Indicates that this is an axes legend
*numpoints*: integer
The number of points in the legend line, default is 4
*prop*: [ None | FontProperties ]
A :class:`matplotlib.font_manager.FontProperties`
instance, or *None* to use rc settings.
*pad*: [ None | scalar ]
The fractional whitespace inside the legend border, between 0 and 1.
If *None*, use rc settings.
*markerscale*: [ None | scalar ]
The relative size of legend markers vs. original. If *None*, use rc
settings.
*shadow*: [ None | False | True ]
If *True*, draw a shadow behind legend. If *None*, use rc settings.
*labelsep*: [ None | scalar ]
The vertical space between the legend entries. If *None*, use rc
settings.
*handlelen*: [ None | scalar ]
The length of the legend lines. If *None*, use rc settings.
*handletextsep*: [ None | scalar ]
The space between the legend line and legend text. If *None*, use rc
settings.
*axespad*: [ None | scalar ]
The border between the axes and legend edge. If *None*, use rc
settings.
**Example:**
.. plot:: mpl_examples/api/legend_demo.py'
| def legend(self, *args, **kwargs):
| def get_handles():
handles = self.lines[:]
handles.extend(self.patches)
handles.extend([c for c in self.collections if isinstance(c, mcoll.LineCollection)])
handles.extend([c for c in self.collections if isinstance(c, mcoll.RegularPolyCollection)])
return handles
if (len(args) == 0):
handles = []
labels = []
for handle in get_handles():
label = handle.get_label()
if ((label is not None) and (label != '') and (not label.startswith('_'))):
handles.append(handle)
labels.append(label)
if (len(handles) == 0):
warnings.warn("No labeled objects found. Use label='...' kwarg on individual plots.")
return None
elif (len(args) == 1):
labels = args[0]
handles = [h for (h, label) in zip(get_handles(), labels)]
elif (len(args) == 2):
if (is_string_like(args[1]) or isinstance(args[1], int)):
(labels, loc) = args
handles = [h for (h, label) in zip(get_handles(), labels)]
kwargs['loc'] = loc
else:
(handles, labels) = args
elif (len(args) == 3):
(handles, labels, loc) = args
kwargs['loc'] = loc
else:
raise TypeError('Invalid arguments to legend')
handles = cbook.flatten(handles)
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
return self.legend_
|
'call signature::
step(x, y, *args, **kwargs)
Make a step plot. Additional keyword args to :func:`step` are the same
as those for :func:`~matplotlib.pyplot.plot`.
*x* and *y* must be 1-D sequences, and it is assumed, but not checked,
that *x* is uniformly increasing.
Keyword arguments:
*where*: [ \'pre\' | \'post\' | \'mid\' ]
If \'pre\', the interval from x[i] to x[i+1] has level y[i]
If \'post\', that interval has level y[i+1]
If \'mid\', the jumps in *y* occur half-way between the
*x*-values.'
| def step(self, x, y, *args, **kwargs):
| where = kwargs.pop('where', 'pre')
if (where not in ('pre', 'post', 'mid')):
raise ValueError("'where' argument to step must be 'pre', 'post' or 'mid'")
kwargs['linestyle'] = ('steps-' + where)
return self.plot(x, y, *args, **kwargs)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.