desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'call signature::
bar(left, height, width=0.8, bottom=0,
color=None, edgecolor=None, linewidth=None,
yerr=None, xerr=None, ecolor=None, capsize=3,
align=\'edge\', orientation=\'vertical\', log=False)
Make a bar plot with rectangles bounded by:
*left*, *left* + *width*, *bottom*, *bottom* + *height*
(left, right, bottom and top edges)
*left*, *height*, *width*, and *bottom* can be either scalars
or sequences
Return value is a list of
:class:`matplotlib.patches.Rectangle` instances.
Required arguments:
Argument Description
*left* the x coordinates of the left sides of the bars
*height* the heights of the bars
Optional keyword arguments:
Keyword Description
*width* the widths of the bars
*bottom* the y coordinates of the bottom edges of
the bars
*color* the colors of the bars
*edgecolor* the colors of the bar edges
*linewidth* width of bar edges; None means use default
linewidth; 0 means don\'t draw edges.
*xerr* if not None, will be used to generate
errorbars on the bar chart
*yerr* if not None, will be used to generate
errorbars on the bar chart
*ecolor* specifies the color of any errorbar
*capsize* (default 3) determines the length in
points of the error bar caps
*align* \'edge\' (default) | \'center\'
*orientation* \'vertical\' | \'horizontal\'
*log* [False|True] False (default) leaves the
orientation axis as-is; True sets it to
log scale
For vertical bars, *align* = \'edge\' aligns bars by their left
edges in left, while *align* = \'center\' interprets these
values as the *x* coordinates of the bar centers. For
horizontal bars, *align* = \'edge\' aligns bars by their bottom
edges in bottom, while *align* = \'center\' interprets these
values as the *y* coordinates of the bar centers.
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars. This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Other optional kwargs:
%(Rectangle)s
**Example:** A stacked bar chart.
.. plot:: mpl_examples/pylab_examples/bar_stacked.py'
| def bar(self, left, height, width=0.8, bottom=None, color=None, edgecolor=None, linewidth=None, yerr=None, xerr=None, ecolor=None, capsize=3, align='edge', orientation='vertical', log=False, **kwargs):
| if (not self._hold):
self.cla()
label = kwargs.pop('label', '')
def make_iterable(x):
if (not iterable(x)):
return [x]
else:
return x
_left = left
left = make_iterable(left)
height = make_iterable(height)
width = make_iterable(width)
_bottom = bottom
bottom = make_iterable(bottom)
linewidth = make_iterable(linewidth)
adjust_ylim = False
adjust_xlim = False
if (orientation == 'vertical'):
self._process_unit_info(xdata=left, ydata=height, kwargs=kwargs)
if log:
self.set_yscale('log')
if (_bottom is None):
if (self.get_yscale() == 'log'):
bottom = [1e-100]
adjust_ylim = True
else:
bottom = [0]
nbars = len(left)
if (len(width) == 1):
width *= nbars
if (len(bottom) == 1):
bottom *= nbars
elif (orientation == 'horizontal'):
self._process_unit_info(xdata=width, ydata=bottom, kwargs=kwargs)
if log:
self.set_xscale('log')
if (_left is None):
if (self.get_xscale() == 'log'):
left = [1e-100]
adjust_xlim = True
else:
left = [0]
nbars = len(bottom)
if (len(left) == 1):
left *= nbars
if (len(height) == 1):
height *= nbars
else:
raise ValueError, ('invalid orientation: %s' % orientation)
if (len(linewidth) < nbars):
linewidth *= nbars
if (color is None):
color = ([None] * nbars)
else:
color = list(mcolors.colorConverter.to_rgba_array(color))
if (len(color) < nbars):
color *= nbars
if (edgecolor is None):
edgecolor = ([None] * nbars)
else:
edgecolor = list(mcolors.colorConverter.to_rgba_array(edgecolor))
if (len(edgecolor) < nbars):
edgecolor *= nbars
if (yerr is not None):
if (not iterable(yerr)):
yerr = ([yerr] * nbars)
if (xerr is not None):
if (not iterable(xerr)):
xerr = ([xerr] * nbars)
assert (len(left) == nbars), ("argument 'left' must be %d or scalar" % nbars)
assert (len(height) == nbars), ("argument 'height' must be %d or scalar" % nbars)
assert (len(width) == nbars), ("argument 'width' must be %d or scalar" % nbars)
assert (len(bottom) == nbars), ("argument 'bottom' must be %d or scalar" % nbars)
if ((yerr is not None) and (len(yerr) != nbars)):
raise ValueError(("bar() argument 'yerr' must be len(%s) or scalar" % nbars))
if ((xerr is not None) and (len(xerr) != nbars)):
raise ValueError(("bar() argument 'xerr' must be len(%s) or scalar" % nbars))
patches = []
if (self.xaxis is not None):
xconv = self.xaxis.converter
if (xconv is not None):
units = self.xaxis.get_units()
left = xconv.convert(left, units)
width = xconv.convert(width, units)
if (self.yaxis is not None):
yconv = self.yaxis.converter
if (yconv is not None):
units = self.yaxis.get_units()
bottom = yconv.convert(bottom, units)
height = yconv.convert(height, units)
if (align == 'edge'):
pass
elif (align == 'center'):
if (orientation == 'vertical'):
left = [(left[i] - (width[i] / 2.0)) for i in xrange(len(left))]
elif (orientation == 'horizontal'):
bottom = [(bottom[i] - (height[i] / 2.0)) for i in xrange(len(bottom))]
else:
raise ValueError, ('invalid alignment: %s' % align)
args = zip(left, bottom, width, height, color, edgecolor, linewidth)
for (l, b, w, h, c, e, lw) in args:
if (h < 0):
b += h
h = abs(h)
if (w < 0):
l += w
w = abs(w)
r = mpatches.Rectangle(xy=(l, b), width=w, height=h, facecolor=c, edgecolor=e, linewidth=lw, label=label)
label = '_nolegend_'
r.update(kwargs)
self.add_patch(r)
patches.append(r)
holdstate = self._hold
self.hold(True)
if ((xerr is not None) or (yerr is not None)):
if (orientation == 'vertical'):
x = [(l + (0.5 * w)) for (l, w) in zip(left, width)]
y = [(b + h) for (b, h) in zip(bottom, height)]
elif (orientation == 'horizontal'):
x = [(l + w) for (l, w) in zip(left, width)]
y = [(b + (0.5 * h)) for (b, h) in zip(bottom, height)]
self.errorbar(x, y, yerr=yerr, xerr=xerr, fmt=None, ecolor=ecolor, capsize=capsize)
self.hold(holdstate)
if adjust_xlim:
(xmin, xmax) = self.dataLim.intervalx
xmin = np.amin(width[(width != 0)])
if (xerr is not None):
xmin = (xmin - np.amax(xerr))
xmin = max((xmin * 0.9), 1e-100)
self.dataLim.intervalx = (xmin, xmax)
if adjust_ylim:
(ymin, ymax) = self.dataLim.intervaly
ymin = np.amin(height[(height != 0)])
if (yerr is not None):
ymin = (ymin - np.amax(yerr))
ymin = max((ymin * 0.9), 1e-100)
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
return patches
|
'call signature::
barh(bottom, width, height=0.8, left=0, **kwargs)
Make a horizontal bar plot with rectangles bounded by:
*left*, *left* + *width*, *bottom*, *bottom* + *height*
(left, right, bottom and top edges)
*bottom*, *width*, *height*, and *left* can be either scalars
or sequences
Return value is a list of
:class:`matplotlib.patches.Rectangle` instances.
Required arguments:
Argument Description
*bottom* the vertical positions of the bottom edges of the bars
*width* the lengths of the bars
Optional keyword arguments:
Keyword Description
*height* the heights (thicknesses) of the bars
*left* the x coordinates of the left edges of the
bars
*color* the colors of the bars
*edgecolor* the colors of the bar edges
*linewidth* width of bar edges; None means use default
linewidth; 0 means don\'t draw edges.
*xerr* if not None, will be used to generate
errorbars on the bar chart
*yerr* if not None, will be used to generate
errorbars on the bar chart
*ecolor* specifies the color of any errorbar
*capsize* (default 3) determines the length in
points of the error bar caps
*align* \'edge\' (default) | \'center\'
*log* [False|True] False (default) leaves the
horizontal axis as-is; True sets it to log
scale
Setting *align* = \'edge\' aligns bars by their bottom edges in
bottom, while *align* = \'center\' interprets these values as
the *y* coordinates of the bar centers.
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars. This enables you to use
barh as the basis for stacked bar charts, or candlestick
plots.
other optional kwargs:
%(Rectangle)s'
| def barh(self, bottom, width, height=0.8, left=None, **kwargs):
| patches = self.bar(left=left, height=height, width=width, bottom=bottom, orientation='horizontal', **kwargs)
return patches
|
'call signature::
broken_barh(self, xranges, yrange, **kwargs)
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
Required arguments:
Argument Description
*xranges* sequence of (*xmin*, *xwidth*)
*yrange* sequence of (*ymin*, *ywidth*)
kwargs are
:class:`matplotlib.collections.BrokenBarHCollection`
properties:
%(BrokenBarHCollection)s
these can either be a single argument, ie::
facecolors = \'black\'
or a sequence of arguments for the various bars, ie::
facecolors = (\'black\', \'red\', \'green\')
**Example:**
.. plot:: mpl_examples/pylab_examples/broken_barh.py'
| def broken_barh(self, xranges, yrange, **kwargs):
| col = mcoll.BrokenBarHCollection(xranges, yrange, **kwargs)
self.add_collection(col, autolim=True)
self.autoscale_view()
return col
|
'call signature::
stem(x, y, linefmt=\'b-\', markerfmt=\'bo\', basefmt=\'r-\')
A stem plot plots vertical lines (using *linefmt*) at each *x*
location from the baseline to *y*, and places a marker there
using *markerfmt*. A horizontal line at 0 is is plotted using
*basefmt*.
Return value is a tuple (*markerline*, *stemlines*,
*baseline*).
.. seealso::
`this document`__ for details
:file:`examples/pylab_examples/stem_plot.py`:
for a demo
__ http://www.mathworks.com/access/helpdesk/help/techdoc/ref/stem.html'
| def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-'):
| remember_hold = self._hold
if (not self._hold):
self.cla()
self.hold(True)
(markerline,) = self.plot(x, y, markerfmt)
stemlines = []
for (thisx, thisy) in zip(x, y):
(l,) = self.plot([thisx, thisx], [0, thisy], linefmt)
stemlines.append(l)
(baseline,) = self.plot([np.amin(x), np.amax(x)], [0, 0], basefmt)
self.hold(remember_hold)
return (markerline, stemlines, baseline)
|
'call signature::
pie(x, explode=None, labels=None,
colors=(\'b\', \'g\', \'r\', \'c\', \'m\', \'y\', \'k\', \'w\'),
autopct=None, pctdistance=0.6, labeldistance=1.1, shadow=False)
Make a pie chart of array *x*. The fractional area of each
wedge is given by x/sum(x). If sum(x) <= 1, then the values
of x give the fractional area directly and the array will not
be normalized.
Keyword arguments:
*explode*: [ None | len(x) sequence ]
If not *None*, is a len(*x*) array which specifies the
fraction of the radius with which to offset each wedge.
*colors*: [ None | color sequence ]
A sequence of matplotlib color args through which the pie chart
will cycle.
*labels*: [ None | len(x) sequence of strings ]
A sequence of strings providing the labels for each wedge
*autopct*: [ None | format string | format function ]
If not *None*, is a string or function used to label the
wedges with their numeric value. The label will be placed inside
the wedge. If it is a format string, the label will be ``fmt%pct``.
If it is a function, it will be called.
*pctdistance*: scalar
The ratio between the center of each pie slice and the
start of the text generated by *autopct*. Ignored if
*autopct* is *None*; default is 0.6.
*labeldistance*: scalar
The radial distance at which the pie labels are drawn
*shadow*: [ False | True ]
Draw a shadow beneath the pie.
The pie chart will probably look best if the figure and axes are
square. Eg.::
figure(figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8])
Return value:
If *autopct* is None, return the tuple (*patches*, *texts*):
- *patches* is a sequence of
:class:`matplotlib.patches.Wedge` instances
- *texts* is a list of the label
:class:`matplotlib.text.Text` instances.
If *autopct* is not *None*, return the tuple (*patches*,
*texts*, *autotexts*), where *patches* and *texts* are as
above, and *autotexts* is a list of
:class:`~matplotlib.text.Text` instances for the numeric
labels.'
| def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1):
| self.set_frame_on(False)
x = np.asarray(x).astype(np.float32)
sx = float(x.sum())
if (sx > 1):
x = np.divide(x, sx)
if (labels is None):
labels = ([''] * len(x))
if (explode is None):
explode = ([0] * len(x))
assert (len(x) == len(labels))
assert (len(x) == len(explode))
if (colors is None):
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w')
center = (0, 0)
radius = 1
theta1 = 0
i = 0
texts = []
slices = []
autotexts = []
for (frac, label, expl) in cbook.safezip(x, labels, explode):
(x, y) = center
theta2 = (theta1 + frac)
thetam = (((2 * math.pi) * 0.5) * (theta1 + theta2))
x += (expl * math.cos(thetam))
y += (expl * math.sin(thetam))
w = mpatches.Wedge((x, y), radius, (360.0 * theta1), (360.0 * theta2), facecolor=colors[(i % len(colors))])
slices.append(w)
self.add_patch(w)
w.set_label(label)
if shadow:
shad = mpatches.Shadow(w, (-0.02), (-0.02))
shad.set_zorder((0.9 * w.get_zorder()))
self.add_patch(shad)
xt = (x + ((labeldistance * radius) * math.cos(thetam)))
yt = (y + ((labeldistance * radius) * math.sin(thetam)))
label_alignment = (((xt > 0) and 'left') or 'right')
t = self.text(xt, yt, label, size=rcParams['xtick.labelsize'], horizontalalignment=label_alignment, verticalalignment='center')
texts.append(t)
if (autopct is not None):
xt = (x + ((pctdistance * radius) * math.cos(thetam)))
yt = (y + ((pctdistance * radius) * math.sin(thetam)))
if is_string_like(autopct):
s = (autopct % (100.0 * frac))
elif callable(autopct):
s = autopct((100.0 * frac))
else:
raise TypeError('autopct must be callable or a format string')
t = self.text(xt, yt, s, horizontalalignment='center', verticalalignment='center')
autotexts.append(t)
theta1 = theta2
i += 1
self.set_xlim(((-1.25), 1.25))
self.set_ylim(((-1.25), 1.25))
self.set_xticks([])
self.set_yticks([])
if (autopct is None):
return (slices, texts)
else:
return (slices, texts, autotexts)
|
'call signature::
errorbar(x, y, yerr=None, xerr=None,
fmt=\'-\', ecolor=None, elinewidth=None, capsize=3,
barsabove=False, lolims=False, uplims=False,
xlolims=False, xuplims=False)
Plot *x* versus *y* with error deltas in *yerr* and *xerr*.
Vertical errorbars are plotted if *yerr* is not *None*.
Horizontal errorbars are plotted if *xerr* is not *None*.
*x*, *y*, *xerr*, and *yerr* can all be scalars, which plots a
single error bar at *x*, *y*.
Optional keyword arguments:
*xerr*/*yerr*: [ scalar | N, Nx1, Nx2 array-like ]
If a scalar number, len(N) array-like object, or an Nx1 array-like
object, errorbars are drawn +/- value.
If a rank-1, Nx2 Numpy array, errorbars are drawn at -column1 and
+column2
*fmt*: \'-\'
The plot format symbol for *y*. If *fmt* is *None*, just plot the
errorbars with no line symbols. This can be useful for creating a
bar plot with errorbars.
*ecolor*: [ None | mpl color ]
a matplotlib color arg which gives the color the errorbar lines; if
*None*, use the marker color.
*elinewidth*: scalar
the linewidth of the errorbar lines. If *None*, use the linewidth.
*capsize*: scalar
the size of the error bar caps in points
*barsabove*: [ True | False ]
if *True*, will plot the errorbars above the plot
symbols. Default is below.
*lolims*/*uplims*/*xlolims*/*xuplims*: [ False | True ]
These arguments can be used to indicate that a value gives
only upper/lower limits. In that case a caret symbol is
used to indicate this. lims-arguments may be of the same
type as *xerr* and *yerr*.
All other keyword arguments are passed on to the plot command for the
markers, so you can add additional key=value pairs to control the
errorbar markers. For example, this code makes big red squares with
thick green edges::
x,y,yerr = rand(3,10)
errorbar(x, y, yerr, marker=\'s\',
mfc=\'red\', mec=\'green\', ms=20, mew=4)
where *mfc*, *mec*, *ms* and *mew* are aliases for the longer
property names, *markerfacecolor*, *markeredgecolor*, *markersize*
and *markeredgewith*.
valid kwargs for the marker properties are
%(Line2D)s
Return value is a length 3 tuple. The first element is the
:class:`~matplotlib.lines.Line2D` instance for the *y* symbol
lines. The second element is a list of error bar cap lines,
the third element is a list of
:class:`~matplotlib.collections.LineCollection` instances for
the horizontal and vertical error ranges.
**Example:**
.. plot:: mpl_examples/pylab_examples/errorbar_demo.py'
| def errorbar(self, x, y, yerr=None, xerr=None, fmt='-', ecolor=None, elinewidth=None, capsize=3, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, **kwargs):
| self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
if (not self._hold):
self.cla()
if (not iterable(x)):
x = [x]
if (not iterable(y)):
y = [y]
if (xerr is not None):
if (not iterable(xerr)):
xerr = ([xerr] * len(x))
if (yerr is not None):
if (not iterable(yerr)):
yerr = ([yerr] * len(y))
l0 = None
if (barsabove and (fmt is not None)):
(l0,) = self.plot(x, y, fmt, **kwargs)
barcols = []
caplines = []
lines_kw = {'label': '_nolegend_'}
if elinewidth:
lines_kw['linewidth'] = elinewidth
else:
if ('linewidth' in kwargs):
lines_kw['linewidth'] = kwargs['linewidth']
if ('lw' in kwargs):
lines_kw['lw'] = kwargs['lw']
if ('transform' in kwargs):
lines_kw['transform'] = kwargs['transform']
if (not iterable(lolims)):
lolims = np.asarray(([lolims] * len(x)), bool)
else:
lolims = np.asarray(lolims, bool)
if (not iterable(uplims)):
uplims = np.array(([uplims] * len(x)), bool)
else:
uplims = np.asarray(uplims, bool)
if (not iterable(xlolims)):
xlolims = np.array(([xlolims] * len(x)), bool)
else:
xlolims = np.asarray(xlolims, bool)
if (not iterable(xuplims)):
xuplims = np.array(([xuplims] * len(x)), bool)
else:
xuplims = np.asarray(xuplims, bool)
def xywhere(xs, ys, mask):
'\n return xs[mask], ys[mask] where mask is True but xs and\n ys are not arrays\n '
assert (len(xs) == len(ys))
assert (len(xs) == len(mask))
xs = [thisx for (thisx, b) in zip(xs, mask) if b]
ys = [thisy for (thisy, b) in zip(ys, mask) if b]
return (xs, ys)
if (capsize > 0):
plot_kw = {'ms': (2 * capsize), 'label': '_nolegend_'}
if ('markeredgewidth' in kwargs):
plot_kw['markeredgewidth'] = kwargs['markeredgewidth']
if ('mew' in kwargs):
plot_kw['mew'] = kwargs['mew']
if ('transform' in kwargs):
plot_kw['transform'] = kwargs['transform']
if (xerr is not None):
if (iterable(xerr) and (len(xerr) == 2) and iterable(xerr[0]) and iterable(xerr[1])):
left = [(thisx - thiserr) for (thisx, thiserr) in cbook.safezip(x, xerr[0])]
right = [(thisx + thiserr) for (thisx, thiserr) in cbook.safezip(x, xerr[1])]
else:
left = [(thisx - thiserr) for (thisx, thiserr) in cbook.safezip(x, xerr)]
right = [(thisx + thiserr) for (thisx, thiserr) in cbook.safezip(x, xerr)]
barcols.append(self.hlines(y, left, right, **lines_kw))
if (capsize > 0):
if xlolims.any():
(leftlo, ylo) = xywhere(left, y, xlolims)
caplines.extend(self.plot(leftlo, ylo, ls='None', marker=mlines.CARETLEFT, **plot_kw))
xlolims = (~ xlolims)
(leftlo, ylo) = xywhere(left, y, xlolims)
caplines.extend(self.plot(leftlo, ylo, 'k|', **plot_kw))
else:
caplines.extend(self.plot(left, y, 'k|', **plot_kw))
if xuplims.any():
(rightup, yup) = xywhere(right, y, xuplims)
caplines.extend(self.plot(rightup, yup, ls='None', marker=mlines.CARETRIGHT, **plot_kw))
xuplims = (~ xuplims)
(rightup, yup) = xywhere(right, y, xuplims)
caplines.extend(self.plot(rightup, yup, 'k|', **plot_kw))
else:
caplines.extend(self.plot(right, y, 'k|', **plot_kw))
if (yerr is not None):
if (iterable(yerr) and (len(yerr) == 2) and iterable(yerr[0]) and iterable(yerr[1])):
lower = [(thisy - thiserr) for (thisy, thiserr) in cbook.safezip(y, yerr[0])]
upper = [(thisy + thiserr) for (thisy, thiserr) in cbook.safezip(y, yerr[1])]
else:
lower = [(thisy - thiserr) for (thisy, thiserr) in cbook.safezip(y, yerr)]
upper = [(thisy + thiserr) for (thisy, thiserr) in cbook.safezip(y, yerr)]
barcols.append(self.vlines(x, lower, upper, **lines_kw))
if (capsize > 0):
if lolims.any():
(xlo, lowerlo) = xywhere(x, lower, lolims)
caplines.extend(self.plot(xlo, lowerlo, ls='None', marker=mlines.CARETDOWN, **plot_kw))
lolims = (~ lolims)
(xlo, lowerlo) = xywhere(x, lower, lolims)
caplines.extend(self.plot(xlo, lowerlo, 'k_', **plot_kw))
else:
caplines.extend(self.plot(x, lower, 'k_', **plot_kw))
if uplims.any():
(xup, upperup) = xywhere(x, upper, uplims)
caplines.extend(self.plot(xup, upperup, ls='None', marker=mlines.CARETUP, **plot_kw))
uplims = (~ uplims)
(xup, upperup) = xywhere(x, upper, uplims)
caplines.extend(self.plot(xup, upperup, 'k_', **plot_kw))
else:
caplines.extend(self.plot(x, upper, 'k_', **plot_kw))
if ((not barsabove) and (fmt is not None)):
(l0,) = self.plot(x, y, fmt, **kwargs)
if (ecolor is None):
if (l0 is None):
ecolor = self._get_lines._get_next_cycle_color()
else:
ecolor = l0.get_color()
for l in barcols:
l.set_color(ecolor)
for l in caplines:
l.set_color(ecolor)
self.autoscale_view()
return (l0, caplines, barcols)
|
'call signature::
boxplot(x, notch=0, sym=\'+\', vert=1, whis=1.5,
positions=None, widths=None)
Make a box and whisker plot for each column of *x* or each
vector in sequence *x*. The box extends from the lower to
upper quartile values of the data, with a line at the median.
The whiskers extend from the box to show the range of the
data. Flier points are those past the end of the whiskers.
- *notch* = 0 (default) produces a rectangular box plot.
- *notch* = 1 will produce a notched box plot
*sym* (default \'b+\') is the default symbol for flier points.
Enter an empty string (\'\') if you don\'t want to show fliers.
- *vert* = 1 (default) makes the boxes vertical.
- *vert* = 0 makes horizontal boxes. This seems goofy, but
that\'s how Matlab did it.
*whis* (default 1.5) defines the length of the whiskers as
a function of the inner quartile range. They extend to the
most extreme data point within ( ``whis*(75%-25%)`` ) data range.
*positions* (default 1,2,...,n) sets the horizontal positions of
the boxes. The ticks and limits are automatically set to match
the positions.
*widths* is either a scalar or a vector and sets the width of
each box. The default is 0.5, or ``0.15*(distance between extreme
positions)`` if that is smaller.
*x* is an array or a sequence of vectors.
Returns a dictionary mapping each component of the boxplot
to a list of the :class:`matplotlib.lines.Line2D`
instances created.
**Example:**
.. plot:: pyplots/boxplot_demo.py'
| def boxplot(self, x, notch=0, sym='b+', vert=1, whis=1.5, positions=None, widths=None):
| if (not self._hold):
self.cla()
holdStatus = self._hold
(whiskers, caps, boxes, medians, fliers) = ([], [], [], [], [])
if hasattr(x, 'shape'):
if (len(x.shape) == 1):
if hasattr(x[0], 'shape'):
x = list(x)
else:
x = [x]
elif (len(x.shape) == 2):
(nr, nc) = x.shape
if (nr == 1):
x = [x]
elif (nc == 1):
x = [x.ravel()]
else:
x = [x[:, i] for i in xrange(nc)]
else:
raise ValueError, 'input x can have no more than 2 dimensions'
if (not hasattr(x[0], '__len__')):
x = [x]
col = len(x)
if (positions is None):
positions = range(1, (col + 1))
if (widths is None):
distance = (max(positions) - min(positions))
widths = min((0.15 * max(distance, 1.0)), 0.5)
if (isinstance(widths, float) or isinstance(widths, int)):
widths = (np.ones((col,), float) * widths)
self.hold(True)
for (i, pos) in enumerate(positions):
d = np.ravel(x[i])
row = len(d)
(q1, med, q3) = mlab.prctile(d, [25, 50, 75])
iq = (q3 - q1)
hi_val = (q3 + (whis * iq))
wisk_hi = np.compress((d <= hi_val), d)
if (len(wisk_hi) == 0):
wisk_hi = q3
else:
wisk_hi = max(wisk_hi)
lo_val = (q1 - (whis * iq))
wisk_lo = np.compress((d >= lo_val), d)
if (len(wisk_lo) == 0):
wisk_lo = q1
else:
wisk_lo = min(wisk_lo)
flier_hi = []
flier_lo = []
flier_hi_x = []
flier_lo_x = []
if (len(sym) != 0):
flier_hi = np.compress((d > wisk_hi), d)
flier_lo = np.compress((d < wisk_lo), d)
flier_hi_x = (np.ones(flier_hi.shape[0]) * pos)
flier_lo_x = (np.ones(flier_lo.shape[0]) * pos)
box_x_min = (pos - (widths[i] * 0.5))
box_x_max = (pos + (widths[i] * 0.5))
wisk_x = (np.ones(2) * pos)
cap_x_min = (pos - (widths[i] * 0.25))
cap_x_max = (pos + (widths[i] * 0.25))
cap_x = [cap_x_min, cap_x_max]
med_y = [med, med]
if (notch == 0):
box_x = [box_x_min, box_x_max, box_x_max, box_x_min, box_x_min]
box_y = [q1, q1, q3, q3, q1]
med_x = [box_x_min, box_x_max]
else:
notch_max = (med + ((1.57 * iq) / np.sqrt(row)))
notch_min = (med - ((1.57 * iq) / np.sqrt(row)))
if (notch_max > q3):
notch_max = q3
if (notch_min < q1):
notch_min = q1
box_x = [box_x_min, box_x_max, box_x_max, cap_x_max, box_x_max, box_x_max, box_x_min, box_x_min, cap_x_min, box_x_min, box_x_min]
box_y = [q1, q1, notch_min, med, notch_max, q3, q3, notch_max, med, notch_min, q1]
med_x = [cap_x_min, cap_x_max]
med_y = [med, med]
if vert:
def doplot(*args):
return self.plot(*args)
else:
def doplot(*args):
shuffled = []
for i in xrange(0, len(args), 3):
shuffled.extend([args[(i + 1)], args[i], args[(i + 2)]])
return self.plot(*shuffled)
whiskers.extend(doplot(wisk_x, [q1, wisk_lo], 'b--', wisk_x, [q3, wisk_hi], 'b--'))
caps.extend(doplot(cap_x, [wisk_hi, wisk_hi], 'k-', cap_x, [wisk_lo, wisk_lo], 'k-'))
boxes.extend(doplot(box_x, box_y, 'b-'))
medians.extend(doplot(med_x, med_y, 'r-'))
fliers.extend(doplot(flier_hi_x, flier_hi, sym, flier_lo_x, flier_lo, sym))
if (1 == vert):
(setticks, setlim) = (self.set_xticks, self.set_xlim)
else:
(setticks, setlim) = (self.set_yticks, self.set_ylim)
newlimits = ((min(positions) - 0.5), (max(positions) + 0.5))
setlim(newlimits)
setticks(positions)
self.hold(holdStatus)
return dict(whiskers=whiskers, caps=caps, boxes=boxes, medians=medians, fliers=fliers)
|
'call signatures::
scatter(x, y, s=20, c=\'b\', marker=\'o\', cmap=None, norm=None,
vmin=None, vmax=None, alpha=1.0, linewidths=None,
verts=None, **kwargs)
Make a scatter plot of *x* versus *y*, where *x*, *y* are 1-D
sequences of the same length, *N*.
Keyword arguments:
*s*:
size in points^2. It is a scalar or an array of the same
length as *x* and *y*.
*c*:
a color. *c* can be a single color format string, or a
sequence of color specifications of length *N*, or a
sequence of *N* numbers to be mapped to colors using the
*cmap* and *norm* specified via kwargs (see below). Note
that *c* should not be a single numeric RGB or RGBA
sequence because that is indistinguishable from an array
of values to be colormapped. *c* can be a 2-D array in
which the rows are RGB or RGBA, however.
*marker*:
can be one of:
Value Description
\'s\' square
\'o\' circle
\'^\' triangle up
\'>\' triangle right
\'v\' triangle down
\'<\' triangle left
\'d\' diamond
\'p\' pentagram
\'h\' hexagon
\'8\' octagon
\'+\' plus
\'x\' cross
The marker can also be a tuple (*numsides*, *style*,
*angle*), which will create a custom, regular symbol.
*numsides*:
the number of sides
*style*:
the style of the regular symbol:
Value Description
0 a regular polygon
1 a star-like symbol
2 an asterisk
3 a circle (*numsides* and *angle* is ignored)
*angle*:
the angle of rotation of the symbol
Finally, *marker* can be (*verts*, 0): *verts* is a
sequence of (*x*, *y*) vertices for a custom scatter
symbol. Alternatively, use the kwarg combination
*marker* = *None*, *verts* = *verts*.
Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in
which case all masks will be combined and only unmasked points
will be plotted.
Other keyword arguments: the color mapping and normalization
arguments will be used only if *c* is an array of floats.
*cmap*: [ None | Colormap ]
A :class:`matplotlib.colors.Colormap` instance. If *None*,
defaults to rc ``image.cmap``. *cmap* is only used if *c*
is an array of floats.
*norm*: [ None | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0, 1. If *None*, use the default
:func:`normalize`. *norm* is only used if *c* is an array
of floats.
*vmin*/*vmax*:
*vmin* and *vmax* are used in conjunction with norm to
normalize luminance data. If either are None, the min and
max of the color array *C* is used. Note if you pass a
*norm* instance, your settings for *vmin* and *vmax* will
be ignored.
*alpha*: 0 <= scalar <= 1
The alpha value for the patches
*linewidths*: [ None | scalar | sequence ]
If *None*, defaults to (lines.linewidth,). Note that this
is a tuple, and if you set the linewidths argument you
must set it as a sequence of floats, as required by
:class:`~matplotlib.collections.RegularPolyCollection`.
Optional kwargs control the
:class:`~matplotlib.collections.Collection` properties; in
particular:
*edgecolors*:
\'none\' to plot faces with no outlines
*facecolors*:
\'none\' to plot unfilled outlines
Here are the standard descriptions of all the
:class:`~matplotlib.collections.Collection` kwargs:
%(Collection)s
A :class:`~matplotlib.collections.Collection` instance is
returned.'
| def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=1.0, linewidths=None, faceted=True, verts=None, **kwargs):
| if (not self._hold):
self.cla()
syms = {'s': (4, (math.pi / 4.0), 0), 'o': (20, 3, 0), '^': (3, 0, 0), '>': (3, (math.pi / 2.0), 0), 'v': (3, math.pi, 0), '<': (3, ((3 * math.pi) / 2.0), 0), 'd': (4, 0, 0), 'p': (5, 0, 0), 'h': (6, 0, 0), '8': (8, 0, 0), '+': (4, 0, 2), 'x': (4, (math.pi / 4.0), 2)}
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
(x, y, s, c) = cbook.delete_masked_points(x, y, s, c)
if (is_string_like(c) or cbook.is_sequence_of_strings(c)):
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
else:
sh = np.shape(c)
if ((len(sh) == 1) and (sh[0] == len(x))):
colors = None
else:
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
if (not iterable(s)):
scales = (s,)
else:
scales = s
if faceted:
edgecolors = None
else:
edgecolors = 'none'
warnings.warn('replace "faceted=False" with "edgecolors=\'none\'"', DeprecationWarning)
sym = None
symstyle = 0
if ((marker is None) and (not (verts is None))):
marker = (verts, 0)
verts = None
if is_string_like(marker):
sym = syms.get(marker)
if ((sym is None) and (verts is None)):
raise ValueError('Unknown marker symbol to scatter')
(numsides, rotation, symstyle) = syms[marker]
elif iterable(marker):
if ((len(marker) < 2) or (len(marker) > 3)):
raise ValueError('Cannot create markersymbol from marker')
if cbook.is_numlike(marker[0]):
if (len(marker) == 2):
(numsides, rotation) = (marker[0], 0.0)
elif (len(marker) == 3):
(numsides, rotation) = (marker[0], marker[2])
sym = True
if (marker[1] in (1, 2)):
symstyle = marker[1]
else:
verts = np.asarray(marker[0])
if (sym is not None):
if (symstyle == 0):
collection = mcoll.RegularPolyCollection(numsides, rotation, scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=zip(x, y), transOffset=self.transData)
elif (symstyle == 1):
collection = mcoll.StarPolygonCollection(numsides, rotation, scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=zip(x, y), transOffset=self.transData)
elif (symstyle == 2):
collection = mcoll.AsteriskPolygonCollection(numsides, rotation, scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=zip(x, y), transOffset=self.transData)
elif (symstyle == 3):
collection = mcoll.CircleCollection(scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=zip(x, y), transOffset=self.transData)
else:
rescale = np.sqrt(max(((verts[:, 0] ** 2) + (verts[:, 1] ** 2))))
verts /= rescale
collection = mcoll.PolyCollection((verts,), scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=zip(x, y), transOffset=self.transData)
collection.set_transform(mtransforms.IdentityTransform())
collection.set_alpha(alpha)
collection.update(kwargs)
if (colors is None):
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
if ((vmin is not None) or (vmax is not None)):
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
temp_x = x
temp_y = y
minx = np.amin(temp_x)
maxx = np.amax(temp_x)
miny = np.amin(temp_y)
maxy = np.amax(temp_y)
w = (maxx - minx)
h = (maxy - miny)
(padx, pady) = ((0.05 * w), (0.05 * h))
corners = (((minx - padx), (miny - pady)), ((maxx + padx), (maxy + pady)))
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
|
'call signature::
hexbin(x, y, C = None, gridsize = 100, bins = None,
xscale = \'linear\', yscale = \'linear\',
cmap=None, norm=None, vmin=None, vmax=None,
alpha=1.0, linewidths=None, edgecolors=\'none\'
reduce_C_function = np.mean,
**kwargs)
Make a hexagonal binning plot of *x* versus *y*, where *x*,
*y* are 1-D sequences of the same length, *N*. If *C* is None
(the default), this is a histogram of the number of occurences
of the observations at (x[i],y[i]).
If *C* is specified, it specifies values at the coordinate
(x[i],y[i]). These values are accumulated for each hexagonal
bin and then reduced according to *reduce_C_function*, which
defaults to numpy\'s mean function (np.mean). (If *C* is
specified, it must also be a 1-D sequence of the same length
as *x* and *y*.)
*x*, *y* and/or *C* may be masked arrays, in which case only
unmasked points will be plotted.
Optional keyword arguments:
*gridsize*: [ 100 | integer ]
The number of hexagons in the *x*-direction, default is
100. The corresponding number of hexagons in the
*y*-direction is chosen such that the hexagons are
approximately regular. Alternatively, gridsize can be a
tuple with two elements specifying the number of hexagons
in the *x*-direction and the *y*-direction.
*bins*: [ None | \'log\' | integer | sequence ]
If *None*, no binning is applied; the color of each hexagon
directly corresponds to its count value.
If \'log\', use a logarithmic scale for the color
map. Internally, :math:`log_{10}(i+1)` is used to
determine the hexagon color.
If an integer, divide the counts in the specified number
of bins, and color the hexagons accordingly.
If a sequence of values, the values of the lower bound of
the bins to be used.
*xscale*: [ \'linear\' | \'log\' ]
Use a linear or log10 scale on the horizontal axis.
*scale*: [ \'linear\' | \'log\' ]
Use a linear or log10 scale on the vertical axis.
Other keyword arguments controlling color mapping and normalization
arguments:
*cmap*: [ None | Colormap ]
a :class:`matplotlib.cm.Colormap` instance. If *None*,
defaults to rc ``image.cmap``.
*norm*: [ None | Normalize ]
:class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1.
*vmin*/*vmax*: scalar
*vmin* and *vmax* are used in conjunction with *norm* to normalize
luminance data. If either are *None*, the min and max of the color
array *C* is used. Note if you pass a norm instance, your settings
for *vmin* and *vmax* will be ignored.
*alpha*: scalar
the alpha value for the patches
*linewidths*: [ None | scalar ]
If *None*, defaults to rc lines.linewidth. Note that this
is a tuple, and if you set the linewidths argument you
must set it as a sequence of floats, as required by
:class:`~matplotlib.collections.RegularPolyCollection`.
Other keyword arguments controlling the Collection properties:
*edgecolors*: [ None | mpl color | color sequence ]
If \'none\', draws the edges in the same color as the fill color.
This is the default, as it avoids unsightly unpainted pixels
between the hexagons.
If *None*, draws the outlines in the default color.
If a matplotlib color arg or sequence of rgba tuples, draws the
outlines in the specified color.
Here are the standard descriptions of all the
:class:`~matplotlib.collections.Collection` kwargs:
%(Collection)s
The return value is a
:class:`~matplotlib.collections.PolyCollection` instance; use
:meth:`~matplotlib.collection.PolyCollection.get_array` on
this :class:`~matplotlib.collections.PolyCollection` to get
the counts in each hexagon.
**Example:**
.. plot:: mpl_examples/pylab_examples/hexbin_demo.py'
| def hexbin(self, x, y, C=None, gridsize=100, bins=None, xscale='linear', yscale='linear', cmap=None, norm=None, vmin=None, vmax=None, alpha=1.0, linewidths=None, edgecolors='none', reduce_C_function=np.mean, **kwargs):
| if (not self._hold):
self.cla()
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
(x, y, C) = cbook.delete_masked_points(x, y, C)
if iterable(gridsize):
(nx, ny) = gridsize
else:
nx = gridsize
ny = int((nx / math.sqrt(3)))
x = np.array(x, float)
y = np.array(y, float)
if (xscale == 'log'):
x = np.log10(x)
if (yscale == 'log'):
y = np.log10(y)
xmin = np.amin(x)
xmax = np.amax(x)
ymin = np.amin(y)
ymax = np.amax(y)
padding = (1e-09 * (xmax - xmin))
xmin -= padding
xmax += padding
sx = ((xmax - xmin) / nx)
sy = ((ymax - ymin) / ny)
x = ((x - xmin) / sx)
y = ((y - ymin) / sy)
ix1 = np.round(x).astype(int)
iy1 = np.round(y).astype(int)
ix2 = np.floor(x).astype(int)
iy2 = np.floor(y).astype(int)
nx1 = (nx + 1)
ny1 = (ny + 1)
nx2 = nx
ny2 = ny
n = ((nx1 * ny1) + (nx2 * ny2))
d1 = (((x - ix1) ** 2) + (3.0 * ((y - iy1) ** 2)))
d2 = ((((x - ix2) - 0.5) ** 2) + (3.0 * (((y - iy2) - 0.5) ** 2)))
bdist = (d1 < d2)
if (C is None):
accum = np.zeros(n)
lattice1 = accum[:(nx1 * ny1)]
lattice2 = accum[(nx1 * ny1):]
lattice1.shape = (nx1, ny1)
lattice2.shape = (nx2, ny2)
for i in xrange(len(x)):
if bdist[i]:
lattice1[(ix1[i], iy1[i])] += 1
else:
lattice2[(ix2[i], iy2[i])] += 1
else:
lattice1 = np.empty((nx1, ny1), dtype=object)
for i in xrange(nx1):
for j in xrange(ny1):
lattice1[(i, j)] = []
lattice2 = np.empty((nx2, ny2), dtype=object)
for i in xrange(nx2):
for j in xrange(ny2):
lattice2[(i, j)] = []
for i in xrange(len(x)):
if bdist[i]:
lattice1[(ix1[i], iy1[i])].append(C[i])
else:
lattice2[(ix2[i], iy2[i])].append(C[i])
for i in xrange(nx1):
for j in xrange(ny1):
vals = lattice1[(i, j)]
if len(vals):
lattice1[(i, j)] = reduce_C_function(vals)
else:
lattice1[(i, j)] = np.nan
for i in xrange(nx2):
for j in xrange(ny2):
vals = lattice2[(i, j)]
if len(vals):
lattice2[(i, j)] = reduce_C_function(vals)
else:
lattice2[(i, j)] = np.nan
accum = np.hstack((lattice1.astype(float).ravel(), lattice2.astype(float).ravel()))
good_idxs = (~ np.isnan(accum))
px = (xmin + (sx * np.array([0.5, 0.5, 0.0, (-0.5), (-0.5), 0.0])))
py = (ymin + ((sy * np.array([(-0.5), 0.5, 1.0, 0.5, (-0.5), (-1.0)])) / 3.0))
polygons = np.zeros((6, n, 2), float)
polygons[:, :(nx1 * ny1), 0] = np.repeat(np.arange(nx1), ny1)
polygons[:, :(nx1 * ny1), 1] = np.tile(np.arange(ny1), nx1)
polygons[:, (nx1 * ny1):, 0] = np.repeat((np.arange(nx2) + 0.5), ny2)
polygons[:, (nx1 * ny1):, 1] = (np.tile(np.arange(ny2), nx2) + 0.5)
if (C is not None):
polygons = polygons[:, good_idxs, :]
accum = accum[good_idxs]
polygons = np.transpose(polygons, axes=[1, 0, 2])
polygons[:, :, 0] *= sx
polygons[:, :, 1] *= sy
polygons[:, :, 0] += px
polygons[:, :, 1] += py
if (xscale == 'log'):
polygons[:, :, 0] = (10 ** polygons[:, :, 0])
xmin = (10 ** xmin)
xmax = (10 ** xmax)
self.set_xscale('log')
if (yscale == 'log'):
polygons[:, :, 1] = (10 ** polygons[:, :, 1])
ymin = (10 ** ymin)
ymax = (10 ** ymax)
self.set_yscale('log')
if (edgecolors == 'none'):
edgecolors = 'face'
collection = mcoll.PolyCollection(polygons, edgecolors=edgecolors, linewidths=linewidths, transOffset=self.transData)
if (bins == 'log'):
accum = np.log10((accum + 1))
elif (bins != None):
if (not iterable(bins)):
(minimum, maximum) = (min(accum), max(accum))
bins -= 1
bins = (minimum + (((maximum - minimum) * np.arange(bins)) / bins))
bins = np.sort(bins)
accum = bins.searchsorted(accum)
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
collection.set_array(accum)
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_alpha(alpha)
collection.update(kwargs)
if ((vmin is not None) or (vmax is not None)):
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
corners = ((xmin, ymin), (xmax, ymax))
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
|
'call signature::
arrow(x, y, dx, dy, **kwargs)
Draws arrow on specified axis from (*x*, *y*) to (*x* + *dx*,
*y* + *dy*).
Optional kwargs control the arrow properties:
%(FancyArrow)s
**Example:**
.. plot:: mpl_examples/pylab_examples/arrow_demo.py'
| def arrow(self, x, y, dx, dy, **kwargs):
| a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
self.add_artist(a)
return a
|
'%(barbs_doc)s
**Example:**
.. plot:: mpl_examples/pylab_examples/barb_demo.py'
| def barbs(self, *args, **kw):
| if (not self._hold):
self.cla()
b = mquiver.Barbs(self, *args, **kw)
self.add_collection(b)
self.update_datalim(b.get_offsets())
self.autoscale_view()
return b
|
'call signature::
fill(*args, **kwargs)
Plot filled polygons. *args* is a variable length argument,
allowing for multiple *x*, *y* pairs with an optional color
format string; see :func:`~matplotlib.pyplot.plot` for details
on the argument parsing. For example, to plot a polygon with
vertices at *x*, *y* in blue.::
ax.fill(x,y, \'b\' )
An arbitrary number of *x*, *y*, *color* groups can be specified::
ax.fill(x1, y1, \'g\', x2, y2, \'r\')
Return value is a list of :class:`~matplotlib.patches.Patch`
instances that were added.
The same color strings that :func:`~matplotlib.pyplot.plot`
supports are supported by the fill format string.
If you would like to fill below a curve, eg. shade a region
between 0 and *y* along *x*, use :meth:`fill_between`
The *closed* kwarg will close the polygon when *True* (default).
kwargs control the Polygon properties:
%(Polygon)s
**Example:**
.. plot:: mpl_examples/pylab_examples/fill_demo.py'
| def fill(self, *args, **kwargs):
| if (not self._hold):
self.cla()
patches = []
for poly in self._get_patches_for_fill(*args, **kwargs):
self.add_patch(poly)
patches.append(poly)
self.autoscale_view()
return patches
|
'call signature::
fill_between(x, y1, y2=0, where=None, **kwargs)
Create a :class:`~matplotlib.collections.PolyCollection`
filling the regions between *y1* and *y2* where
``where==True``
*x*
an N length np array of the x data
*y1*
an N length scalar or np array of the x data
*y2*
an N length scalar or np array of the x data
*where*
if None, default to fill between everywhere. If not None,
it is a a N length numpy boolean array and the fill will
only happen over the regions where ``where==True``
*kwargs*
keyword args passed on to the :class:`PolyCollection`
kwargs control the Polygon properties:
%(PolyCollection)s
.. plot:: mpl_examples/pylab_examples/fill_between.py'
| def fill_between(self, x, y1, y2=0, where=None, **kwargs):
| self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
self._process_unit_info(ydata=y2)
x = np.asarray(self.convert_xunits(x))
y1 = np.asarray(self.convert_yunits(y1))
y2 = np.asarray(self.convert_yunits(y2))
if (not cbook.iterable(y1)):
y1 = (np.ones_like(x) * y1)
if (not cbook.iterable(y2)):
y2 = (np.ones_like(x) * y2)
if (where is None):
where = np.ones(len(x), np.bool)
where = np.asarray(where)
assert ((len(x) == len(y1)) and (len(x) == len(y2)) and (len(x) == len(where)))
polys = []
for (ind0, ind1) in mlab.contiguous_regions(where):
theseverts = []
xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1]
if (not len(xslice)):
continue
N = len(xslice)
X = np.zeros((((2 * N) + 2), 2), np.float)
X[0] = (xslice[0], y2slice[0])
X[(N + 1)] = (xslice[(-1)], y2slice[(-1)])
X[1:(N + 1), 0] = xslice
X[1:(N + 1), 1] = y1slice
X[(N + 2):, 0] = xslice[::(-1)]
X[(N + 2):, 1] = y2slice[::(-1)]
polys.append(X)
collection = mcoll.PolyCollection(polys, **kwargs)
XY1 = np.array([x[where], y1[where]]).T
XY2 = np.array([x[where], y2[where]]).T
self.dataLim.update_from_data_xy(XY1, self.ignore_existing_data_limits, updatex=True, updatey=True)
self.dataLim.update_from_data_xy(XY2, self.ignore_existing_data_limits, updatex=False, updatey=True)
self.add_collection(collection)
self.autoscale_view()
return collection
|
'call signature::
imshow(X, cmap=None, norm=None, aspect=None, interpolation=None,
alpha=1.0, vmin=None, vmax=None, origin=None, extent=None,
**kwargs)
Display the image in *X* to current axes. *X* may be a float
array, a uint8 array or a PIL image. If *X* is an array, *X*
can have the following shapes:
* MxN -- luminance (grayscale, float array only)
* MxNx3 -- RGB (float or uint8 array)
* MxNx4 -- RGBA (float or uint8 array)
The value for each component of MxNx3 and MxNx4 float arrays should be
in the range 0.0 to 1.0; MxN float arrays may be normalised.
An :class:`matplotlib.image.AxesImage` instance is returned.
Keyword arguments:
*cmap*: [ None | Colormap ]
A :class:`matplotlib.cm.Colormap` instance, eg. cm.jet.
If *None*, default to rc ``image.cmap`` value.
*cmap* is ignored when *X* has RGB(A) information
*aspect*: [ None | \'auto\' | \'equal\' | scalar ]
If \'auto\', changes the image aspect ratio to match that of the axes
If \'equal\', and *extent* is *None*, changes the axes
aspect ratio to match that of the image. If *extent* is
not *None*, the axes aspect ratio is changed to match that
of the extent.
If *None*, default to rc ``image.aspect`` value.
*interpolation*:
Acceptable values are *None*, \'nearest\', \'bilinear\',
\'bicubic\', \'spline16\', \'spline36\', \'hanning\', \'hamming\',
\'hermite\', \'kaiser\', \'quadric\', \'catrom\', \'gaussian\',
\'bessel\', \'mitchell\', \'sinc\', \'lanczos\',
If *interpolation* is *None*, default to rc
``image.interpolation``. See also the *filternorm* and
*filterrad* parameters
*norm*: [ None | Normalize ]
An :class:`matplotlib.colors.Normalize` instance; if
*None*, default is ``normalization()``. This scales
luminance -> 0-1
*norm* is only used for an MxN float array.
*vmin*/*vmax*: [ None | scalar ]
Used to scale a luminance image to 0-1. If either is
*None*, the min and max of the luminance values will be
used. Note if *norm* is not *None*, the settings for
*vmin* and *vmax* will be ignored.
*alpha*: scalar
The alpha blending value, between 0 (transparent) and 1 (opaque)
*origin*: [ None | \'upper\' | \'lower\' ]
Place the [0,0] index of the array in the upper left or lower left
corner of the axes. If *None*, default to rc ``image.origin``.
*extent*: [ None | scalars (left, right, bottom, top) ]
Eata values of the axes. The default assigns zero-based row,
column indices to the *x*, *y* centers of the pixels.
*shape*: [ None | scalars (columns, rows) ]
For raw buffer images
*filternorm*:
A parameter for the antigrain image resize filter. From the
antigrain documentation, if *filternorm* = 1, the filter normalizes
integer values and corrects the rounding errors. It doesn\'t do
anything with the source floating point values, it corrects only
integers according to the rule of 1.0 which means that any sum of
pixel weights must be equal to 1.0. So, the filter function must
produce a graph of the proper shape.
*filterrad*:
The filter radius for filters that have a radius
parameter, i.e. when interpolation is one of: \'sinc\',
\'lanczos\' or \'blackman\'
Additional kwargs are :class:`~matplotlib.artist.Artist` properties:
%(Artist)s
**Example:**
.. plot:: mpl_examples/pylab_examples/image_demo.py'
| def imshow(self, X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=1.0, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, **kwargs):
| if (not self._hold):
self.cla()
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
if (aspect is None):
aspect = rcParams['image.aspect']
self.set_aspect(aspect)
im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent, filternorm=filternorm, filterrad=filterrad, resample=resample, **kwargs)
im.set_data(X)
im.set_alpha(alpha)
self._set_artist_props(im)
im.set_clip_path(self.patch)
if ((vmin is not None) or (vmax is not None)):
im.set_clim(vmin, vmax)
else:
im.autoscale_None()
im.set_url(url)
(xmin, xmax, ymin, ymax) = im.get_extent()
corners = ((xmin, ymin), (xmax, ymax))
self.update_datalim(corners)
if self._autoscaleon:
self.set_xlim((xmin, xmax))
self.set_ylim((ymin, ymax))
self.images.append(im)
return im
|
'call signatures::
pcolor(C, **kwargs)
pcolor(X, Y, C, **kwargs)
Create a pseudocolor plot of a 2-D array.
*C* is the array of color values.
*X* and *Y*, if given, specify the (*x*, *y*) coordinates of
the colored quadrilaterals; the quadrilateral for C[i,j] has
corners at::
(X[i, j], Y[i, j]),
(X[i, j+1], Y[i, j+1]),
(X[i+1, j], Y[i+1, j]),
(X[i+1, j+1], Y[i+1, j+1]).
Ideally the dimensions of *X* and *Y* should be one greater
than those of *C*; if the dimensions are the same, then the
last row and column of *C* will be ignored.
Note that the the column index corresponds to the
*x*-coordinate, and the row index corresponds to *y*; for
details, see the :ref:`Grid Orientation
<axes-pcolor-grid-orientation>` section below.
If either or both of *X* and *Y* are 1-D arrays or column vectors,
they will be expanded as needed into the appropriate 2-D arrays,
making a rectangular grid.
*X*, *Y* and *C* may be masked arrays. If either C[i, j], or one
of the vertices surrounding C[i,j] (*X* or *Y* at [i, j], [i+1, j],
[i, j+1],[i+1, j+1]) is masked, nothing is plotted.
Keyword arguments:
*cmap*: [ None | Colormap ]
A :class:`matplotlib.cm.Colormap` instance. If *None*, use
rc settings.
norm: [ None | Normalize ]
An :class:`matplotlib.colors.Normalize` instance is used
to scale luminance data to 0,1. If *None*, defaults to
:func:`normalize`.
*vmin*/*vmax*: [ None | scalar ]
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If either are *None*, the min
and max of the color array *C* is used. If you pass a
*norm* instance, *vmin* and *vmax* will be ignored.
*shading*: [ \'flat\' | \'faceted\' ]
If \'faceted\', a black grid is drawn around each rectangle; if
\'flat\', edges are not drawn. Default is \'flat\', contrary to
Matlab(TM).
This kwarg is deprecated; please use \'edgecolors\' instead:
* shading=\'flat\' -- edgecolors=\'None\'
* shading=\'faceted -- edgecolors=\'k\'
*edgecolors*: [ None | \'None\' | color | color sequence]
If *None*, the rc setting is used by default.
If \'None\', edges will not be visible.
An mpl color or sequence of colors will set the edge color
*alpha*: 0 <= scalar <= 1
the alpha blending value
Return value is a :class:`matplotlib.collection.Collection`
instance.
.. _axes-pcolor-grid-orientation:
The grid orientation follows the Matlab(TM) convention: an
array *C* with shape (*nrows*, *ncolumns*) is plotted with
the column number as *X* and the row number as *Y*, increasing
up; hence it is plotted the way the array would be printed,
except that the *Y* axis is reversed. That is, *C* is taken
as *C*(*y*, *x*).
Similarly for :func:`~matplotlib.pyplot.meshgrid`::
x = np.arange(5)
y = np.arange(3)
X, Y = meshgrid(x,y)
is equivalent to:
X = array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Y = array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2]])
so if you have::
C = rand( len(x), len(y))
then you need::
pcolor(X, Y, C.T)
or::
pcolor(C.T)
Matlab :func:`pcolor` always discards the last row and column
of *C*, but matplotlib displays the last row and column if *X* and
*Y* are not specified, or if *X* and *Y* have one more row and
column than *C*.
kwargs can be used to control the
:class:`~matplotlib.collection.PolyCollection` properties:
%(PolyCollection)s'
| def pcolor(self, *args, **kwargs):
| if (not self._hold):
self.cla()
alpha = kwargs.pop('alpha', 1.0)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
shading = kwargs.pop('shading', 'flat')
(X, Y, C) = self._pcolorargs('pcolor', *args)
(Ny, Nx) = X.shape
C = ma.asarray(C)
X = ma.asarray(X)
Y = ma.asarray(Y)
mask = (ma.getmaskarray(X) + ma.getmaskarray(Y))
xymask = (((mask[0:(-1), 0:(-1)] + mask[1:, 1:]) + mask[0:(-1), 1:]) + mask[1:, 0:(-1)])
mask = (ma.getmaskarray(C)[0:(Ny - 1), 0:(Nx - 1)] + xymask)
newaxis = np.newaxis
compress = np.compress
ravelmask = (mask == 0).ravel()
X1 = compress(ravelmask, ma.filled(X[0:(-1), 0:(-1)]).ravel())
Y1 = compress(ravelmask, ma.filled(Y[0:(-1), 0:(-1)]).ravel())
X2 = compress(ravelmask, ma.filled(X[1:, 0:(-1)]).ravel())
Y2 = compress(ravelmask, ma.filled(Y[1:, 0:(-1)]).ravel())
X3 = compress(ravelmask, ma.filled(X[1:, 1:]).ravel())
Y3 = compress(ravelmask, ma.filled(Y[1:, 1:]).ravel())
X4 = compress(ravelmask, ma.filled(X[0:(-1), 1:]).ravel())
Y4 = compress(ravelmask, ma.filled(Y[0:(-1), 1:]).ravel())
npoly = len(X1)
xy = np.concatenate((X1[:, newaxis], Y1[:, newaxis], X2[:, newaxis], Y2[:, newaxis], X3[:, newaxis], Y3[:, newaxis], X4[:, newaxis], Y4[:, newaxis], X1[:, newaxis], Y1[:, newaxis]), axis=1)
verts = xy.reshape((npoly, 5, 2))
C = compress(ravelmask, ma.filled(C[0:(Ny - 1), 0:(Nx - 1)]).ravel())
if (shading == 'faceted'):
edgecolors = ((0, 0, 0, 1),)
linewidths = (0.25,)
else:
edgecolors = 'face'
linewidths = (1.0,)
kwargs.setdefault('edgecolors', edgecolors)
kwargs.setdefault('antialiaseds', (0,))
kwargs.setdefault('linewidths', linewidths)
collection = mcoll.PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
collection.set_cmap(cmap)
collection.set_norm(norm)
if ((vmin is not None) or (vmax is not None)):
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
self.grid(False)
x = X.compressed()
y = Y.compressed()
minx = np.amin(x)
maxx = np.amax(x)
miny = np.amin(y)
maxy = np.amax(y)
corners = ((minx, miny), (maxx, maxy))
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
|
'call signatures::
pcolormesh(C)
pcolormesh(X, Y, C)
pcolormesh(C, **kwargs)
*C* may be a masked array, but *X* and *Y* may not. Masked
array support is implemented via *cmap* and *norm*; in
contrast, :func:`~matplotlib.pyplot.pcolor` simply does not
draw quadrilaterals with masked colors or vertices.
Keyword arguments:
*cmap*: [ None | Colormap ]
A :class:`matplotlib.cm.Colormap` instance. If None, use
rc settings.
*norm*: [ None | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1. If None, defaults to
:func:`normalize`.
*vmin*/*vmax*: [ None | scalar ]
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If either are *None*, the min
and max of the color array *C* is used. If you pass a
*norm* instance, *vmin* and *vmax* will be ignored.
*shading*: [ \'flat\' | \'faceted\' ]
If \'faceted\', a black grid is drawn around each rectangle; if
\'flat\', edges are not drawn. Default is \'flat\', contrary to
Matlab(TM).
This kwarg is deprecated; please use \'edgecolors\' instead:
* shading=\'flat\' -- edgecolors=\'None\'
* shading=\'faceted -- edgecolors=\'k\'
*edgecolors*: [ None | \'None\' | color | color sequence]
If None, the rc setting is used by default.
If \'None\', edges will not be visible.
An mpl color or sequence of colors will set the edge color
*alpha*: 0 <= scalar <= 1
the alpha blending value
Return value is a :class:`matplotlib.collection.QuadMesh`
object.
kwargs can be used to control the
:class:`matplotlib.collections.QuadMesh`
properties:
%(QuadMesh)s
.. seealso::
:func:`~matplotlib.pyplot.pcolor`:
For an explanation of the grid orientation and the
expansion of 1-D *X* and/or *Y* to 2-D arrays.'
| def pcolormesh(self, *args, **kwargs):
| if (not self._hold):
self.cla()
alpha = kwargs.pop('alpha', 1.0)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
shading = kwargs.pop('shading', 'flat')
edgecolors = kwargs.pop('edgecolors', 'None')
antialiased = kwargs.pop('antialiased', False)
(X, Y, C) = self._pcolorargs('pcolormesh', *args)
(Ny, Nx) = X.shape
C = ma.ravel(C[0:(Ny - 1), 0:(Nx - 1)])
X = X.ravel()
Y = Y.ravel()
coords = np.zeros(((Nx * Ny), 2), dtype=float)
coords[:, 0] = X
coords[:, 1] = Y
if ((shading == 'faceted') or (edgecolors != 'None')):
showedges = 1
else:
showedges = 0
collection = mcoll.QuadMesh((Nx - 1), (Ny - 1), coords, showedges, antialiased=antialiased)
collection.set_alpha(alpha)
collection.set_array(C)
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
collection.set_cmap(cmap)
collection.set_norm(norm)
if ((vmin is not None) or (vmax is not None)):
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
self.grid(False)
minx = np.amin(X)
maxx = np.amax(X)
miny = np.amin(Y)
maxy = np.amax(Y)
corners = ((minx, miny), (maxx, maxy))
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
|
'pseudocolor plot of a 2-D array
Experimental; this is a version of pcolor that
does not draw lines, that provides the fastest
possible rendering with the Agg backend, and that
can handle any quadrilateral grid.
Call signatures::
pcolor(C, **kwargs)
pcolor(xr, yr, C, **kwargs)
pcolor(x, y, C, **kwargs)
pcolor(X, Y, C, **kwargs)
C is the 2D array of color values corresponding to quadrilateral
cells. Let (nr, nc) be its shape. C may be a masked array.
``pcolor(C, **kwargs)`` is equivalent to
``pcolor([0,nc], [0,nr], C, **kwargs)``
*xr*, *yr* specify the ranges of *x* and *y* corresponding to the
rectangular region bounding *C*. If::
xr = [x0, x1]
and::
yr = [y0,y1]
then *x* goes from *x0* to *x1* as the second index of *C* goes
from 0 to *nc*, etc. (*x0*, *y0*) is the outermost corner of
cell (0,0), and (*x1*, *y1*) is the outermost corner of cell
(*nr*-1, *nc*-1). All cells are rectangles of the same size.
This is the fastest version.
*x*, *y* are 1D arrays of length *nc* +1 and *nr* +1, respectively,
giving the x and y boundaries of the cells. Hence the cells are
rectangular but the grid may be nonuniform. The speed is
intermediate. (The grid is checked, and if found to be
uniform the fast version is used.)
*X* and *Y* are 2D arrays with shape (*nr* +1, *nc* +1) that specify
the (x,y) coordinates of the corners of the colored
quadrilaterals; the quadrilateral for C[i,j] has corners at
(X[i,j],Y[i,j]), (X[i,j+1],Y[i,j+1]), (X[i+1,j],Y[i+1,j]),
(X[i+1,j+1],Y[i+1,j+1]). The cells need not be rectangular.
This is the most general, but the slowest to render. It may
produce faster and more compact output using ps, pdf, and
svg backends, however.
Note that the the column index corresponds to the x-coordinate,
and the row index corresponds to y; for details, see
the "Grid Orientation" section below.
Optional keyword arguments:
*cmap*: [ None | Colormap ]
A cm Colormap instance from cm. If None, use rc settings.
*norm*: [ None | Normalize ]
An mcolors.Normalize instance is used to scale luminance data to
0,1. If None, defaults to normalize()
*vmin*/*vmax*: [ None | scalar ]
*vmin* and *vmax* are used in conjunction with norm to normalize
luminance data. If either are *None*, the min and max of the color
array *C* is used. If you pass a norm instance, *vmin* and *vmax*
will be *None*.
*alpha*: 0 <= scalar <= 1
the alpha blending value
Return value is an image if a regular or rectangular grid
is specified, and a QuadMesh collection in the general
quadrilateral case.'
| def pcolorfast(self, *args, **kwargs):
| if (not self._hold):
self.cla()
alpha = kwargs.pop('alpha', 1.0)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if (norm is not None):
assert isinstance(norm, mcolors.Normalize)
if (cmap is not None):
assert isinstance(cmap, mcolors.Colormap)
C = args[(-1)]
(nr, nc) = C.shape
if (len(args) == 1):
style = 'image'
x = [0, nc]
y = [0, nr]
elif (len(args) == 3):
(x, y) = args[:2]
x = np.asarray(x)
y = np.asarray(y)
if ((x.ndim == 1) and (y.ndim == 1)):
if ((x.size == 2) and (y.size == 2)):
style = 'image'
else:
dx = np.diff(x)
dy = np.diff(y)
if ((np.ptp(dx) < (0.01 * np.abs(dx.mean()))) and (np.ptp(dy) < (0.01 * np.abs(dy.mean())))):
style = 'image'
else:
style = 'pcolorimage'
elif ((x.ndim == 2) and (y.ndim == 2)):
style = 'quadmesh'
else:
raise TypeError('arguments do not match valid signatures')
else:
raise TypeError('need 1 argument or 3 arguments')
if (style == 'quadmesh'):
C = ma.ravel(C)
X = x.ravel()
Y = y.ravel()
Nx = (nc + 1)
Ny = (nr + 1)
coords = np.empty(((Nx * Ny), 2), np.float64)
coords[:, 0] = X
coords[:, 1] = Y
collection = mcoll.QuadMesh(nc, nr, coords, 0)
collection.set_alpha(alpha)
collection.set_array(C)
collection.set_cmap(cmap)
collection.set_norm(norm)
self.add_collection(collection)
(xl, xr, yb, yt) = (X.min(), X.max(), Y.min(), Y.max())
ret = collection
else:
(xl, xr, yb, yt) = (x[0], x[(-1)], y[0], y[(-1)])
if (style == 'image'):
im = mimage.AxesImage(self, cmap, norm, interpolation='nearest', origin='lower', extent=(xl, xr, yb, yt), **kwargs)
im.set_data(C)
im.set_alpha(alpha)
self.images.append(im)
ret = im
if (style == 'pcolorimage'):
im = mimage.PcolorImage(self, x, y, C, cmap=cmap, norm=norm, alpha=alpha, **kwargs)
self.images.append(im)
ret = im
self._set_artist_props(ret)
if ((vmin is not None) or (vmax is not None)):
ret.set_clim(vmin, vmax)
else:
ret.autoscale_None()
self.update_datalim(np.array([[xl, yb], [xr, yt]]))
self.autoscale_view(tight=True)
return ret
|
'call signature::
table(cellText=None, cellColours=None,
cellLoc=\'right\', colWidths=None,
rowLabels=None, rowColours=None, rowLoc=\'left\',
colLabels=None, colColours=None, colLoc=\'center\',
loc=\'bottom\', bbox=None):
Add a table to the current axes. Returns a
:class:`matplotlib.table.Table` instance. For finer grained
control over tables, use the :class:`~matplotlib.table.Table`
class and add it to the axes with
:meth:`~matplotlib.axes.Axes.add_table`.
Thanks to John Gill for providing the class and table.
kwargs control the :class:`~matplotlib.table.Table`
properties:
%(Table)s'
| def table(self, **kwargs):
| return mtable.table(self, **kwargs)
|
'call signature::
ax = twinx()
create a twin of Axes for generating a plot with a sharex
x-axis but independent y axis. The y-axis of self will have
ticks on left and the returned axes will have ticks on the
right'
| def twinx(self):
| ax2 = self.figure.add_axes(self.get_position(True), sharex=self, frameon=False)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
self.yaxis.tick_left()
return ax2
|
'call signature::
ax = twiny()
create a twin of Axes for generating a plot with a shared
y-axis but independent x axis. The x-axis of self will have
ticks on bottom and the returned axes will have ticks on the
top'
| def twiny(self):
| ax2 = self.figure.add_axes(self.get_position(True), sharey=self, frameon=False)
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
self.xaxis.tick_bottom()
return ax2
|
'Return a copy of the shared axes Grouper object for x axes'
| def get_shared_x_axes(self):
| return self._shared_x_axes
|
'Return a copy of the shared axes Grouper object for y axes'
| def get_shared_y_axes(self):
| return self._shared_y_axes
|
'call signature::
hist(x, bins=10, range=None, normed=False, cumulative=False,
bottom=None, histtype=\'bar\', align=\'mid\',
orientation=\'vertical\', rwidth=None, log=False, **kwargs)
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.
Keyword arguments:
*bins*:
Either an integer number of bins or a sequence giving the
bins. *x* are the data to be binned. *x* can be an array,
a 2D array with multiple data in its columns, or a list of
arrays with data of different length. Note, if *bins*
is an integer input argument=numbins, *bins* + 1 bin edges
will be returned, compatible with the semantics of
:func:`numpy.histogram` with the *new* = True argument.
Unequally spaced bins are supported if *bins* is a sequence.
*range*:
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
set off (*autoscale_on* is set to *False*) and the xaxis limits
are set to encompass the full specified bin range.
*normed*:
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)``. In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::
pdf, bins, patches = ax.hist(...)
print np.sum(pdf * np.diff(bins))
*cumulative*:
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.
*histtype*: [ \'bar\' | \'barstacked\' | \'step\' | \'stepfilled\' ]
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.
*align*: [\'left\' | \'mid\' | \'right\' ]
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.
*orientation*: [ \'horizontal\' | \'vertical\' ]
If \'horizontal\', :func:`~matplotlib.pyplot.barh` will be
used for bar-type histograms and the *bottom* kwarg will be
the left edges.
*rwidth*:
The relative width of the bars as a fraction of the bin
width. If *None*, automatically compute the width. Ignored
if *histtype* = \'step\' or \'stepfilled\'.
*log*:
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.
kwargs are used to update the properties of the hist
:class:`~matplotlib.patches.Rectangle` instances:
%(Rectangle)s
You can use labels for your histogram, and only the first
:class:`~matplotlib.patches.Rectangle` gets the label (the
others get the magic string \'_nolegend_\'. This will make the
histograms work in the intuitive way for bar charts::
ax.hist(10+2*np.random.randn(1000), label=\'men\')
ax.hist(12+3*np.random.randn(1000), label=\'women\', alpha=0.5)
ax.legend()
**Example:**
.. plot:: mpl_examples/pylab_examples/histogram_demo.py'
| def hist(self, x, bins=10, range=None, normed=False, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, **kwargs):
| if (not self._hold):
self.cla()
if (kwargs.get('width') is not None):
raise DeprecationWarning('hist now uses the rwidth to give relative width and not absolute width')
try:
x = np.transpose(np.array(x))
if (len(x.shape) == 1):
x.shape = (1, x.shape[0])
elif ((len(x.shape) == 2) and (x.shape[1] < x.shape[0])):
warnings.warn('2D hist should be nsamples x nvariables; this looks transposed')
except ValueError:
if (iterable(x[0]) and (not is_string_like(x[0]))):
tx = []
for i in xrange(len(x)):
tx.append(np.array(x[i]))
x = tx
else:
raise ValueError, 'Can not use providet data to create a histogram'
binsgiven = (cbook.iterable(bins) or (range != None))
if (np.__version__ < '1.3'):
hist_kwargs = dict(range=range, normed=bool(normed), new=True)
else:
hist_kwargs = dict(range=range, normed=bool(normed))
n = []
for i in xrange(len(x)):
(m, bins) = np.histogram(x[i], bins, **hist_kwargs)
n.append(m)
if cumulative:
slc = slice(None)
if (cbook.is_numlike(cumulative) and (cumulative < 0)):
slc = slice(None, None, (-1))
if normed:
n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n]
else:
n = [m[slc].cumsum()[slc] for m in n]
patches = []
if histtype.startswith('bar'):
totwidth = np.diff(bins)
stacked = False
if (rwidth is not None):
dr = min(1.0, max(0.0, rwidth))
elif (len(n) > 1):
dr = 0.8
else:
dr = 1.0
if (histtype == 'bar'):
width = ((dr * totwidth) / len(n))
dw = width
if (len(n) > 1):
boffset = ((((-0.5) * dr) * totwidth) * (1.0 - (1.0 / len(n))))
else:
boffset = 0.0
elif (histtype == 'barstacked'):
width = (dr * totwidth)
(boffset, dw) = (0.0, 0.0)
stacked = True
else:
raise ValueError, ('invalid histtype: %s' % histtype)
if ((align == 'mid') or (align == 'edge')):
boffset += (0.5 * totwidth)
elif (align == 'right'):
boffset += totwidth
elif ((align != 'left') and (align != 'center')):
raise ValueError, ('invalid align: %s' % align)
if (orientation == 'horizontal'):
for m in n:
color = self._get_lines._get_next_cycle_color()
patch = self.barh((bins[:(-1)] + boffset), m, height=width, left=bottom, align='center', log=log, color=color)
patches.append(patch)
if stacked:
if (bottom is None):
bottom = 0.0
bottom += m
boffset += dw
elif (orientation == 'vertical'):
for m in n:
color = self._get_lines._get_next_cycle_color()
patch = self.bar((bins[:(-1)] + boffset), m, width=width, bottom=bottom, align='center', log=log, color=color)
patches.append(patch)
if stacked:
if (bottom is None):
bottom = 0.0
bottom += m
boffset += dw
else:
raise ValueError, ('invalid orientation: %s' % orientation)
elif histtype.startswith('step'):
x = np.zeros((2 * len(bins)), np.float)
y = np.zeros((2 * len(bins)), np.float)
(x[0::2], x[1::2]) = (bins, bins)
if ((align == 'left') or (align == 'center')):
x -= (0.5 * (bins[1] - bins[0]))
elif (align == 'right'):
x += (0.5 * (bins[1] - bins[0]))
elif ((align != 'mid') and (align != 'edge')):
raise ValueError, ('invalid align: %s' % align)
if log:
(y[0], y[(-1)]) = (1e-100, 1e-100)
if (orientation == 'horizontal'):
self.set_xscale('log')
elif (orientation == 'vertical'):
self.set_yscale('log')
fill = False
if (histtype == 'stepfilled'):
fill = True
elif (histtype != 'step'):
raise ValueError, ('invalid histtype: %s' % histtype)
for m in n:
(y[1:(-1):2], y[2::2]) = (m, m)
if (orientation == 'horizontal'):
(x, y) = (y, x)
elif (orientation != 'vertical'):
raise ValueError, ('invalid orientation: %s' % orientation)
color = self._get_lines._get_next_cycle_color()
if fill:
patches.append(self.fill(x, y, closed=False, facecolor=color))
else:
patches.append(self.fill(x, y, closed=False, edgecolor=color, fill=False))
if (orientation == 'horizontal'):
(xmin, xmax) = (0, self.dataLim.intervalx[1])
for m in n:
xmin = np.amin(m[(m != 0)])
xmin = max((xmin * 0.9), 1e-100)
self.dataLim.intervalx = (xmin, xmax)
elif (orientation == 'vertical'):
(ymin, ymax) = (0, self.dataLim.intervaly[1])
for m in n:
ymin = np.amin(m[(m != 0)])
ymin = max((ymin * 0.9), 1e-100)
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
else:
raise ValueError, ('invalid histtype: %s' % histtype)
label = kwargs.pop('label', '')
for patch in patches:
for p in patch:
p.update(kwargs)
p.set_label(label)
label = '_nolegend_'
if binsgiven:
self.set_autoscale_on(False)
if (orientation == 'vertical'):
self.autoscale_view(scalex=False, scaley=True)
XL = self.xaxis.get_major_locator().view_limits(bins[0], bins[(-1)])
self.set_xbound(XL)
else:
self.autoscale_view(scalex=True, scaley=False)
YL = self.yaxis.get_major_locator().view_limits(bins[0], bins[(-1)])
self.set_ybound(YL)
if (len(n) == 1):
return (n[0], bins, cbook.silent_list('Patch', patches[0]))
else:
return (n, bins, cbook.silent_list('Lists of Patches', patches))
|
'call signature::
psd(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides=\'default\', scale_by_freq=None, **kwargs)
The power spectral density by Welch\'s average periodogram
method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
of each segment :math:`i` are averaged to compute *Pxx*, with a
scaling to correct for power loss due to windowing. *Fs* is the
sampling frequency.
%(PSD)s
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns the tuple (*Pxx*, *freqs*).
For plotting, the power is plotted as
:math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself
is returned.
References:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/psd_demo.py'
| def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, **kwargs):
| if (not self._hold):
self.cla()
(pxx, freqs) = mlab.psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq)
pxx.shape = (len(freqs),)
freqs += Fc
if (scale_by_freq in (None, True)):
psd_units = 'dB/Hz'
else:
psd_units = 'dB'
self.plot(freqs, (10 * np.log10(pxx)), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel(('Power Spectral Density (%s)' % psd_units))
self.grid(True)
(vmin, vmax) = self.viewLim.intervaly
intv = (vmax - vmin)
logi = int(np.log10(intv))
if (logi == 0):
logi = 0.1
step = (10 * logi)
ticks = np.arange(math.floor(vmin), (math.ceil(vmax) + 1), step)
self.set_yticks(ticks)
return (pxx, freqs)
|
'call signature::
csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides=\'default\', scale_by_freq=None, **kwargs)
The cross spectral density :math:`P_{xy}` by Welch\'s average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. The product of
the direct FFTs of *x* and *y* are averaged over each segment
to compute :math:`P_{xy}`, with a scaling to correct for power
loss due to windowing.
Returns the tuple (*Pxy*, *freqs*). *P* is the cross spectrum
(complex valued), and :math:`10\log_{10}|P_{xy}|` is
plotted.
%(PSD)s
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
References:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the Line2D properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/csd_demo.py
.. seealso:
:meth:`psd`
For a description of the optional parameters.'
| def csd(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, **kwargs):
| if (not self._hold):
self.cla()
(pxy, freqs) = mlab.csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq)
pxy.shape = (len(freqs),)
freqs += Fc
self.plot(freqs, (10 * np.log10(np.absolute(pxy))), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Cross Spectrum Magnitude (dB)')
self.grid(True)
(vmin, vmax) = self.viewLim.intervaly
intv = (vmax - vmin)
step = (10 * int(np.log10(intv)))
ticks = np.arange(math.floor(vmin), (math.ceil(vmax) + 1), step)
self.set_yticks(ticks)
return (pxy, freqs)
|
'call signature::
cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none,
window = mlab.window_hanning, noverlap=0, pad_to=None,
sides=\'default\', scale_by_freq=None, **kwargs)
cohere the coherence between *x* and *y*. Coherence is the normalized
cross spectral density:
.. math::
C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
%(PSD)s
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
The return value is a tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector.
kwargs are applied to the lines.
References:
* Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the :class:`~matplotlib.lines.Line2D`
properties of the coherence plot:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/cohere_demo.py'
| def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, **kwargs):
| if (not self._hold):
self.cla()
(cxy, freqs) = mlab.cohere(x, y, NFFT, Fs, detrend, window, noverlap, scale_by_freq)
freqs += Fc
self.plot(freqs, cxy, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Coherence')
self.grid(True)
return (cxy, freqs)
|
'call signature::
specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides=\'default\',
scale_by_freq=None)
Compute a spectrogram of data in *x*. Data are split into
*NFFT* length segments and the PSD of each section is
computed. The windowing function *window* is applied to each
segment, and the amount of overlap of each segment is
specified with *noverlap*.
%(PSD)s
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the y extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
*cmap*:
A :class:`matplotlib.cm.Colormap` instance; if *None* use
default determined by rc
*xextent*:
The image extent along the x-axis. xextent = (xmin,xmax)
The default is (0,max(bins)), where bins is the return
value from :func:`mlab.specgram`
Return value is (*Pxx*, *freqs*, *bins*, *im*):
- *bins* are the time points the spectrogram is calculated over
- *freqs* is an array of frequencies
- *Pxx* is a len(times) x len(freqs) array of power
- *im* is a :class:`matplotlib.image.AxesImage` instance
Note: If *x* is real (i.e. non-complex), only the positive
spectrum is shown. If *x* is complex, both positive and
negative parts of the spectrum are shown. This can be
overridden using the *sides* keyword argument.
**Example:**
.. plot:: mpl_examples/pylab_examples/specgram_demo.py'
| def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=128, cmap=None, xextent=None, pad_to=None, sides='default', scale_by_freq=None):
| if (not self._hold):
self.cla()
(Pxx, freqs, bins) = mlab.specgram(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq)
Z = (10.0 * np.log10(Pxx))
Z = np.flipud(Z)
if (xextent is None):
xextent = (0, np.amax(bins))
(xmin, xmax) = xextent
freqs += Fc
extent = (xmin, xmax, freqs[0], freqs[(-1)])
im = self.imshow(Z, cmap, extent=extent)
self.axis('auto')
return (Pxx, freqs, bins, im)
|
'call signature::
spy(Z, precision=0, marker=None, markersize=None,
aspect=\'equal\', **kwargs)
``spy(Z)`` plots the sparsity pattern of the 2-D array *Z*.
If *precision* is 0, any non-zero value will be plotted;
else, values of :math:`|Z| > precision` will be plotted.
For :class:`scipy.sparse.spmatrix` instances, there is a
special case: if *precision* is \'present\', any value present in
the array will be plotted, even if it is identically zero.
The array will be plotted as it would be printed, with
the first index (row) increasing down and the second
index (column) increasing to the right.
By default aspect is \'equal\', so that each array element
occupies a square space; set the aspect kwarg to \'auto\'
to allow the plot to fill the plot box, or to any scalar
number to specify the aspect ratio of an array element
directly.
Two plotting styles are available: image or marker. Both
are available for full arrays, but only the marker style
works for :class:`scipy.sparse.spmatrix` instances.
If *marker* and *markersize* are *None*, an image will be
returned and any remaining kwargs are passed to
:func:`~matplotlib.pyplot.imshow`; else, a
:class:`~matplotlib.lines.Line2D` object will be returned with
the value of marker determining the marker type, and any
remaining kwargs passed to the
:meth:`~matplotlib.axes.Axes.plot` method.
If *marker* and *markersize* are *None*, useful kwargs include:
* *cmap*
* *alpha*
.. seealso::
:func:`~matplotlib.pyplot.imshow`
For controlling colors, e.g. cyan background and red marks,
use::
cmap = mcolors.ListedColormap([\'c\',\'r\'])
If *marker* or *markersize* is not *None*, useful kwargs include:
* *marker*
* *markersize*
* *color*
Useful values for *marker* include:
* \'s\' square (default)
* \'o\' circle
* \'.\' point
* \',\' pixel
.. seealso::
:func:`~matplotlib.pyplot.plot`'
| def spy(self, Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs):
| if (precision is None):
precision = 0
warnings.DeprecationWarning('Use precision=0 instead of None')
if ((marker is None) and (markersize is None) and hasattr(Z, 'tocoo')):
marker = 's'
if ((marker is None) and (markersize is None)):
Z = np.asarray(Z)
mask = (np.absolute(Z) > precision)
if ('cmap' not in kwargs):
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], name='binary')
(nr, nc) = Z.shape
extent = [(-0.5), (nc - 0.5), (nr - 0.5), (-0.5)]
ret = self.imshow(mask, interpolation='nearest', aspect=aspect, extent=extent, origin='upper', **kwargs)
else:
if hasattr(Z, 'tocoo'):
c = Z.tocoo()
if (precision == 'present'):
y = c.row
x = c.col
else:
nonzero = (np.absolute(c.data) > precision)
y = c.row[nonzero]
x = c.col[nonzero]
else:
Z = np.asarray(Z)
nonzero = (np.absolute(Z) > precision)
(y, x) = np.nonzero(nonzero)
if (marker is None):
marker = 's'
if (markersize is None):
markersize = 10
marks = mlines.Line2D(x, y, linestyle='None', marker=marker, markersize=markersize, **kwargs)
self.add_line(marks)
(nr, nc) = Z.shape
self.set_xlim(xmin=(-0.5), xmax=(nc - 0.5))
self.set_ylim(ymin=(nr - 0.5), ymax=(-0.5))
self.set_aspect(aspect)
ret = marks
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
return ret
|
'Plot a matrix or array as an image.
The matrix will be shown the way it would be printed,
with the first row at the top. Row and column numbering
is zero-based.
Argument:
*Z* anything that can be interpreted as a 2-D array
kwargs all are passed to :meth:`~matplotlib.axes.Axes.imshow`.
:meth:`matshow` sets defaults for *extent*, *origin*,
*interpolation*, and *aspect*; use care in overriding the
*extent* and *origin* kwargs, because they interact. (Also,
if you want to change them, you probably should be using
imshow directly in your own version of matshow.)
Returns: an :class:`matplotlib.image.AxesImage` instance.'
| def matshow(self, Z, **kwargs):
| Z = np.asarray(Z)
(nr, nc) = Z.shape
extent = [(-0.5), (nc - 0.5), (nr - 0.5), (-0.5)]
kw = {'extent': extent, 'origin': 'upper', 'interpolation': 'nearest', 'aspect': 'equal'}
kw.update(kwargs)
im = self.imshow(Z, **kw)
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
return im
|
'*fig* is a :class:`matplotlib.figure.Figure` instance.
*args* is the tuple (*numRows*, *numCols*, *plotNum*), where
the array of subplots in the figure has dimensions *numRows*,
*numCols*, and where *plotNum* is the number of the subplot
being created. *plotNum* starts at 1 in the upper left
corner and increases to the right.
If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the
decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*.'
| def __init__(self, fig, *args, **kwargs):
| self.figure = fig
if (len(args) == 1):
s = str(args[0])
if (len(s) != 3):
raise ValueError('Argument to subplot must be a 3 digits long')
(rows, cols, num) = map(int, s)
elif (len(args) == 3):
(rows, cols, num) = args
else:
raise ValueError('Illegal argument to subplot')
total = (rows * cols)
num -= 1
if (num >= total):
raise ValueError('Subplot number exceeds total subplots')
self._rows = rows
self._cols = cols
self._num = num
self.update_params()
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
|
'get the subplot geometry, eg 2,2,3'
| def get_geometry(self):
| return (self._rows, self._cols, (self._num + 1))
|
'change subplot geometry, eg. from 1,1,1 to 2,2,3'
| def change_geometry(self, numrows, numcols, num):
| self._rows = numrows
self._cols = numcols
self._num = (num - 1)
self.update_params()
self.set_position(self.figbox)
|
'update the subplot position from fig.subplotpars'
| def update_params(self):
| rows = self._rows
cols = self._cols
num = self._num
pars = self.figure.subplotpars
left = pars.left
right = pars.right
bottom = pars.bottom
top = pars.top
wspace = pars.wspace
hspace = pars.hspace
totWidth = (right - left)
totHeight = (top - bottom)
figH = (totHeight / (rows + (hspace * (rows - 1))))
sepH = (hspace * figH)
figW = (totWidth / (cols + (wspace * (cols - 1))))
sepW = (wspace * figW)
(rowNum, colNum) = divmod(num, cols)
figBottom = ((top - ((rowNum + 1) * figH)) - (rowNum * sepH))
figLeft = (left + (colNum * (figW + sepW)))
self.figbox = mtransforms.Bbox.from_bounds(figLeft, figBottom, figW, figH)
self.rowNum = rowNum
self.colNum = colNum
self.numRows = rows
self.numCols = cols
if 0:
print 'rcn', rows, cols, num
print 'lbrt', left, bottom, right, top
print 'self.figBottom', self.figBottom
print 'self.figLeft', self.figLeft
print 'self.figW', self.figW
print 'self.figH', self.figH
print 'self.rowNum', self.rowNum
print 'self.colNum', self.colNum
print 'self.numRows', self.numRows
print 'self.numCols', self.numCols
|
'set the visible property on ticklabels so xticklabels are
visible only if the subplot is in the last row and yticklabels
are visible only if the subplot is in the first column'
| def label_outer(self):
| lastrow = self.is_last_row()
firstcol = self.is_first_col()
for label in self.get_xticklabels():
label.set_visible(lastrow)
for label in self.get_yticklabels():
label.set_visible(firstcol)
|
'Initialize the object. This takes the filename as input and
opens the file; actually reading the file happens when
iterating through the pages of the file.'
| def __init__(self, filename, dpi):
| matplotlib.verbose.report(('Dvi: ' + filename), 'debug')
self.file = open(filename, 'rb')
self.dpi = dpi
self.fonts = {}
self.state = _dvistate.pre
|
'Iterate through the pages of the file.
Returns (text, pages) pairs, where:
text is a list of (x, y, fontnum, glyphnum, width) tuples
boxes is a list of (x, y, height, width) tuples
The coordinates are transformed into a standard Cartesian
coordinate system at the dpi value given when initializing.
The coordinates are floating point numbers, but otherwise
precision is not lost and coordinate values are not clipped to
integers.'
| def __iter__(self):
| while True:
have_page = self._read()
if have_page:
(yield self._output())
else:
break
|
'Close the underlying file if it is open.'
| def close(self):
| if (not self.file.closed):
self.file.close()
|
'Output the text and boxes belonging to the most recent page.
page = dvi._output()'
| def _output(self):
| (minx, miny, maxx, maxy) = (np.inf, np.inf, (- np.inf), (- np.inf))
maxy_pure = (- np.inf)
for elt in (self.text + self.boxes):
if (len(elt) == 4):
(x, y, h, w) = elt
e = 0
else:
(x, y, font, g, w) = elt
h = _mul2012(font._scale, font._tfm.height[g])
e = _mul2012(font._scale, font._tfm.depth[g])
minx = min(minx, x)
miny = min(miny, (y - h))
maxx = max(maxx, (x + w))
maxy = max(maxy, (y + e))
maxy_pure = max(maxy_pure, y)
if (self.dpi is None):
return mpl_cbook.Bunch(text=self.text, boxes=self.boxes, width=(maxx - minx), height=(maxy_pure - miny), descent=(maxy - maxy_pure))
d = (self.dpi / (72.27 * (2 ** 16)))
text = [(((x - minx) * d), ((maxy - y) * d), f, g, (w * d)) for (x, y, f, g, w) in self.text]
boxes = [(((x - minx) * d), ((maxy - y) * d), (h * d), (w * d)) for (x, y, h, w) in self.boxes]
return mpl_cbook.Bunch(text=text, boxes=boxes, width=((maxx - minx) * d), height=((maxy_pure - miny) * d), descent=((maxy - maxy_pure) * d))
|
'Read one page from the file. Return True if successful,
False if there were no more pages.'
| def _read(self):
| while True:
byte = ord(self.file.read(1))
self._dispatch(byte)
if (byte == 140):
return True
if (self.state == _dvistate.post_post):
self.close()
return False
|
'Read and return an integer argument "nbytes" long.
Signedness is determined by the "signed" keyword.'
| def _arg(self, nbytes, signed=False):
| str = self.file.read(nbytes)
value = ord(str[0])
if (signed and (value >= 128)):
value = (value - 256)
for i in range(1, nbytes):
value = ((256 * value) + ord(str[i]))
return value
|
'Based on the opcode "byte", read the correct kinds of
arguments from the dvi file and call the method implementing
that opcode with those arguments.'
| def _dispatch(self, byte):
| if (0 <= byte <= 127):
self._set_char(byte)
elif (byte == 128):
self._set_char(self._arg(1))
elif (byte == 129):
self._set_char(self._arg(2))
elif (byte == 130):
self._set_char(self._arg(3))
elif (byte == 131):
self._set_char(self._arg(4, True))
elif (byte == 132):
self._set_rule(self._arg(4, True), self._arg(4, True))
elif (byte == 133):
self._put_char(self._arg(1))
elif (byte == 134):
self._put_char(self._arg(2))
elif (byte == 135):
self._put_char(self._arg(3))
elif (byte == 136):
self._put_char(self._arg(4, True))
elif (byte == 137):
self._put_rule(self._arg(4, True), self._arg(4, True))
elif (byte == 138):
self._nop()
elif (byte == 139):
self._bop(*[self._arg(4, True) for i in range(11)])
elif (byte == 140):
self._eop()
elif (byte == 141):
self._push()
elif (byte == 142):
self._pop()
elif (byte == 143):
self._right(self._arg(1, True))
elif (byte == 144):
self._right(self._arg(2, True))
elif (byte == 145):
self._right(self._arg(3, True))
elif (byte == 146):
self._right(self._arg(4, True))
elif (byte == 147):
self._right_w(None)
elif (byte == 148):
self._right_w(self._arg(1, True))
elif (byte == 149):
self._right_w(self._arg(2, True))
elif (byte == 150):
self._right_w(self._arg(3, True))
elif (byte == 151):
self._right_w(self._arg(4, True))
elif (byte == 152):
self._right_x(None)
elif (byte == 153):
self._right_x(self._arg(1, True))
elif (byte == 154):
self._right_x(self._arg(2, True))
elif (byte == 155):
self._right_x(self._arg(3, True))
elif (byte == 156):
self._right_x(self._arg(4, True))
elif (byte == 157):
self._down(self._arg(1, True))
elif (byte == 158):
self._down(self._arg(2, True))
elif (byte == 159):
self._down(self._arg(3, True))
elif (byte == 160):
self._down(self._arg(4, True))
elif (byte == 161):
self._down_y(None)
elif (byte == 162):
self._down_y(self._arg(1, True))
elif (byte == 163):
self._down_y(self._arg(2, True))
elif (byte == 164):
self._down_y(self._arg(3, True))
elif (byte == 165):
self._down_y(self._arg(4, True))
elif (byte == 166):
self._down_z(None)
elif (byte == 167):
self._down_z(self._arg(1, True))
elif (byte == 168):
self._down_z(self._arg(2, True))
elif (byte == 169):
self._down_z(self._arg(3, True))
elif (byte == 170):
self._down_z(self._arg(4, True))
elif (171 <= byte <= 234):
self._fnt_num((byte - 171))
elif (byte == 235):
self._fnt_num(self._arg(1))
elif (byte == 236):
self._fnt_num(self._arg(2))
elif (byte == 237):
self._fnt_num(self._arg(3))
elif (byte == 238):
self._fnt_num(self._arg(4, True))
elif (239 <= byte <= 242):
len = self._arg((byte - 238))
special = self.file.read(len)
self._xxx(special)
elif (243 <= byte <= 246):
k = self._arg((byte - 242), (byte == 246))
(c, s, d, a, l) = [self._arg(x) for x in (4, 4, 4, 1, 1)]
n = self.file.read((a + l))
self._fnt_def(k, c, s, d, a, l, n)
elif (byte == 247):
(i, num, den, mag, k) = [self._arg(x) for x in (1, 4, 4, 4, 1)]
x = self.file.read(k)
self._pre(i, num, den, mag, x)
elif (byte == 248):
self._post()
elif (byte == 249):
self._post_post()
else:
raise ValueError, ('unknown command: byte %d' % byte)
|
'Width of char in dvi units. For internal use by dviread.py.'
| def _width_of(self, char):
| width = self._tfm.width.get(char, None)
if (width is not None):
return _mul2012(width, self._scale)
matplotlib.verbose.report(('No width for char %d in font %s' % (char, self.texname)), 'debug')
return 0
|
'Parse each line into words.'
| def _parse(self, file):
| for line in file:
line = line.strip()
if ((line == '') or line.startswith('%')):
continue
(words, pos) = ([], 0)
while (pos < len(line)):
if (line[pos] == '"'):
pos += 1
end = line.index('"', pos)
words.append(line[pos:end])
pos = (end + 1)
else:
end = line.find(' ', (pos + 1))
if (end == (-1)):
end = len(line)
words.append(line[pos:end])
pos = end
while ((pos < len(line)) and (line[pos] == ' ')):
pos += 1
self._register(words)
|
'Register a font described by "words".
The format is, AFAIK: texname fontname [effects and filenames]
Effects are PostScript snippets like ".177 SlantFont",
filenames begin with one or two less-than signs. A filename
ending in enc is an encoding file, other filenames are font
files. This can be overridden with a left bracket: <[foobar
indicates an encoding file named foobar.
There is some difference between <foo.pfb and <<bar.pfb in
subsetting, but I have no example of << in my TeX installation.'
| def _register(self, words):
| (texname, psname) = words[:2]
(effects, encoding, filename) = ([], None, None)
for word in words[2:]:
if (not word.startswith('<')):
effects.append(word)
else:
word = word.lstrip('<')
if word.startswith('['):
assert (encoding is None)
encoding = word[1:]
elif word.endswith('.enc'):
assert (encoding is None)
encoding = word
else:
assert (filename is None)
filename = word
self._font[texname] = mpl_cbook.Bunch(texname=texname, psname=psname, effects=effects, encoding=encoding, filename=filename)
|
'Create a Collection
%(Collection)s'
| def __init__(self, edgecolors=None, facecolors=None, linewidths=None, linestyles='solid', antialiaseds=None, offsets=None, transOffset=None, norm=None, cmap=None, pickradius=5.0, urls=None, **kwargs):
| artist.Artist.__init__(self)
cm.ScalarMappable.__init__(self, norm, cmap)
self.set_edgecolor(edgecolors)
self.set_facecolor(facecolors)
self.set_linewidth(linewidths)
self.set_linestyle(linestyles)
self.set_antialiased(antialiaseds)
self.set_urls(urls)
self._uniform_offsets = None
self._offsets = np.array([], np.float_)
if (offsets is not None):
offsets = np.asarray(offsets)
if (len(offsets.shape) == 1):
offsets = offsets[np.newaxis, :]
if (transOffset is not None):
self._offsets = offsets
self._transOffset = transOffset
else:
self._uniform_offsets = offsets
self._pickradius = pickradius
self.update(kwargs)
|
'Point prep for drawing and hit testing'
| def _prepare_points(self):
| transform = self.get_transform()
transOffset = self._transOffset
offsets = self._offsets
paths = self.get_paths()
if self.have_units():
paths = []
for path in self.get_paths():
vertices = path.vertices
(xs, ys) = (vertices[:, 0], vertices[:, 1])
xs = self.convert_xunits(xs)
ys = self.convert_yunits(ys)
paths.append(mpath.Path(zip(xs, ys), path.codes))
if len(self._offsets):
xs = self.convert_xunits(self._offsets[:0])
ys = self.convert_yunits(self._offsets[:1])
offsets = zip(xs, ys)
offsets = np.asarray(offsets, np.float_)
if (not transform.is_affine):
paths = [transform.transform_path_non_affine(path) for path in paths]
transform = transform.get_affine()
if (not transOffset.is_affine):
offsets = transOffset.transform_non_affine(offsets)
transOffset = transOffset.get_affine()
return (transform, transOffset, offsets, paths)
|
'Test whether the mouse event occurred in the collection.
Returns True | False, ``dict(ind=itemlist)``, where every
item in itemlist contains the event.'
| def contains(self, mouseevent):
| if callable(self._contains):
return self._contains(self, mouseevent)
if (not self.get_visible()):
return (False, {})
(transform, transOffset, offsets, paths) = self._prepare_points()
ind = mpath.point_in_path_collection(mouseevent.x, mouseevent.y, self._pickradius, transform.frozen(), paths, self.get_transforms(), offsets, transOffset, (len(self._facecolors) > 0))
return ((len(ind) > 0), dict(ind=ind))
|
'Set the offsets for the collection. *offsets* can be a scalar
or a sequence.
ACCEPTS: float or sequence of floats'
| def set_offsets(self, offsets):
| offsets = np.asarray(offsets, np.float_)
if (len(offsets.shape) == 1):
offsets = offsets[np.newaxis, :]
if (self._uniform_offsets is None):
self._offsets = offsets
else:
self._uniform_offsets = offsets
|
'Return the offsets for the collection.'
| def get_offsets(self):
| if (self._uniform_offsets is None):
return self._offsets
else:
return self._uniform_offsets
|
'Set the linewidth(s) for the collection. *lw* can be a scalar
or a sequence; if it is a sequence the patches will cycle
through the sequence
ACCEPTS: float or sequence of floats'
| def set_linewidth(self, lw):
| if (lw is None):
lw = mpl.rcParams['patch.linewidth']
self._linewidths = self._get_value(lw)
|
'alias for set_linewidth'
| def set_linewidths(self, lw):
| return self.set_linewidth(lw)
|
'alias for set_linewidth'
| def set_lw(self, lw):
| return self.set_linewidth(lw)
|
'Set the linestyle(s) for the collection.
ACCEPTS: [\'solid\' | \'dashed\', \'dashdot\', \'dotted\' |
(offset, on-off-dash-seq) ]'
| def set_linestyle(self, ls):
| try:
dashd = backend_bases.GraphicsContextBase.dashd
if cbook.is_string_like(ls):
if (ls in dashd):
dashes = [dashd[ls]]
elif (ls in cbook.ls_mapper):
dashes = [dashd[cbook.ls_mapper[ls]]]
else:
raise ValueError()
elif cbook.iterable(ls):
try:
dashes = []
for x in ls:
if cbook.is_string_like(x):
if (x in dashd):
dashes.append(dashd[x])
elif (x in cbook.ls_mapper):
dashes.append(dashd[cbook.ls_mapper[x]])
else:
raise ValueError()
elif (cbook.iterable(x) and (len(x) == 2)):
dashes.append(x)
else:
raise ValueError()
except ValueError:
if (len(ls) == 2):
dashes = ls
else:
raise ValueError()
else:
raise ValueError()
except ValueError:
raise ValueError(('Do not know how to convert %s to dashes' % ls))
self._linestyles = dashes
|
'alias for set_linestyle'
| def set_linestyles(self, ls):
| return self.set_linestyle(ls)
|
'alias for set_linestyle'
| def set_dashes(self, ls):
| return self.set_linestyle(ls)
|
'Set the antialiasing state for rendering.
ACCEPTS: Boolean or sequence of booleans'
| def set_antialiased(self, aa):
| if (aa is None):
aa = mpl.rcParams['patch.antialiased']
self._antialiaseds = self._get_bool(aa)
|
'alias for set_antialiased'
| def set_antialiaseds(self, aa):
| return self.set_antialiased(aa)
|
'Set both the edgecolor and the facecolor.
ACCEPTS: matplotlib color arg or sequence of rgba tuples
.. seealso::
:meth:`set_facecolor`, :meth:`set_edgecolor`'
| def set_color(self, c):
| self.set_facecolor(c)
self.set_edgecolor(c)
|
'Set the facecolor(s) of the collection. *c* can be a
matplotlib color arg (all patches have same color), or a
sequence or rgba tuples; if it is a sequence the patches will
cycle through the sequence
ACCEPTS: matplotlib color arg or sequence of rgba tuples'
| def set_facecolor(self, c):
| if (c is None):
c = mpl.rcParams['patch.facecolor']
self._facecolors_original = c
self._facecolors = _colors.colorConverter.to_rgba_array(c, self._alpha)
|
'alias for set_facecolor'
| def set_facecolors(self, c):
| return self.set_facecolor(c)
|
'Set the edgecolor(s) of the collection. *c* can be a
matplotlib color arg (all patches have same color), or a
sequence or rgba tuples; if it is a sequence the patches will
cycle through the sequence.
If *c* is \'face\', the edge color will always be the same as
the face color.
ACCEPTS: matplotlib color arg or sequence of rgba tuples'
| def set_edgecolor(self, c):
| if (c == 'face'):
self._edgecolors = 'face'
self._edgecolors_original = 'face'
else:
if (c is None):
c = mpl.rcParams['patch.edgecolor']
self._edgecolors_original = c
self._edgecolors = _colors.colorConverter.to_rgba_array(c, self._alpha)
|
'alias for set_edgecolor'
| def set_edgecolors(self, c):
| return self.set_edgecolor(c)
|
'Set the alpha tranparencies of the collection. *alpha* must be
a float.
ACCEPTS: float'
| def set_alpha(self, alpha):
| try:
float(alpha)
except TypeError:
raise TypeError('alpha must be a float')
else:
artist.Artist.set_alpha(self, alpha)
try:
self._facecolors = _colors.colorConverter.to_rgba_array(self._facecolors_original, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
try:
if (self._edgecolors_original != 'face'):
self._edgecolors = _colors.colorConverter.to_rgba_array(self._edgecolors_original, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
|
'If the scalar mappable array is not none, update colors
from scalar data'
| def update_scalarmappable(self):
| if (self._A is None):
return
if (self._A.ndim > 1):
raise ValueError('Collections can only map rank 1 arrays')
if len(self._facecolors):
self._facecolors = self.to_rgba(self._A, self._alpha)
else:
self._edgecolors = self.to_rgba(self._A, self._alpha)
|
'copy properties from other to self'
| def update_from(self, other):
| artist.Artist.update_from(self, other)
self._antialiaseds = other._antialiaseds
self._edgecolors_original = other._edgecolors_original
self._edgecolors = other._edgecolors
self._facecolors_original = other._facecolors_original
self._facecolors = other._facecolors
self._linewidths = other._linewidths
self._linestyles = other._linestyles
self._pickradius = other._pickradius
|
'Converts a given mesh into a sequence of
:class:`matplotlib.path.Path` objects for easier rendering by
backends that do not directly support quadmeshes.
This function is primarily of use to backend implementers.'
| def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
| Path = mpath.Path
if ma.isMaskedArray(coordinates):
c = coordinates.data
else:
c = coordinates
points = np.concatenate((c[0:(-1), 0:(-1)], c[0:(-1), 1:], c[1:, 1:], c[1:, 0:(-1)], c[0:(-1), 0:(-1)]), axis=2)
points = points.reshape(((meshWidth * meshHeight), 5, 2))
return [Path(x) for x in points]
|
'*verts* is a sequence of ( *verts0*, *verts1*, ...) where
*verts_i* is a sequence of *xy* tuples of vertices, or an
equivalent :mod:`numpy` array of shape (*nv*, 2).
*sizes* is *None* (default) or a sequence of floats that
scale the corresponding *verts_i*. The scaling is applied
before the Artist master transform; if the latter is an identity
transform, then the overall scaling is such that if
*verts_i* specify a unit square, then *sizes_i* is the area
of that square in points^2.
If len(*sizes*) < *nv*, the additional values will be
taken cyclically from the array.
*closed*, when *True*, will explicitly close the polygon.
%(Collection)s'
| def __init__(self, verts, sizes=None, closed=True, **kwargs):
| Collection.__init__(self, **kwargs)
self._sizes = sizes
self.set_verts(verts, closed)
|
'This allows one to delay initialization of the vertices.'
| def set_verts(self, verts, closed=True):
| if closed:
self._paths = []
for xy in verts:
if np.ma.isMaskedArray(xy):
if (len(xy) and (xy[0] != xy[(-1)]).any()):
xy = np.ma.concatenate([xy, [xy[0]]])
else:
xy = np.asarray(xy)
if (len(xy) and (xy[0] != xy[(-1)]).any()):
xy = np.concatenate([xy, [xy[0]]])
self._paths.append(mpath.Path(xy))
else:
self._paths = [mpath.Path(xy) for xy in verts]
|
'*xranges*
sequence of (*xmin*, *xwidth*)
*yrange*
*ymin*, *ywidth*
%(Collection)s'
| def __init__(self, xranges, yrange, **kwargs):
| (ymin, ywidth) = yrange
ymax = (ymin + ywidth)
verts = [[(xmin, ymin), (xmin, ymax), ((xmin + xwidth), ymax), ((xmin + xwidth), ymin), (xmin, ymin)] for (xmin, xwidth) in xranges]
PolyCollection.__init__(self, verts, **kwargs)
|
'Create a BrokenBarHCollection to plot horizontal bars from
over the regions in *x* where *where* is True. The bars range
on the y-axis from *ymin* to *ymax*
A :class:`BrokenBarHCollection` is returned.
*kwargs* are passed on to the collection'
| @staticmethod
def span_where(x, ymin, ymax, where, **kwargs):
| xranges = []
for (ind0, ind1) in mlab.contiguous_regions(where):
xslice = x[ind0:ind1]
if (not len(xslice)):
continue
xranges.append((xslice[0], (xslice[(-1)] - xslice[0])))
collection = BrokenBarHCollection(xranges, [ymin, (ymax - ymin)], **kwargs)
return collection
|
'*numsides*
the number of sides of the polygon
*rotation*
the rotation of the polygon in radians
*sizes*
gives the area of the circle circumscribing the
regular polygon in points^2
%(Collection)s
Example: see :file:`examples/dynamic_collection.py` for
complete example::
offsets = np.random.rand(20,2)
facecolors = [cm.jet(x) for x in np.random.rand(20)]
black = (0,0,0,1)
collection = RegularPolyCollection(
numsides=5, # a pentagon
rotation=0, sizes=(50,),
facecolors = facecolors,
edgecolors = (black,),
linewidths = (1,),
offsets = offsets,
transOffset = ax.transData,'
| def __init__(self, numsides, rotation=0, sizes=(1,), **kwargs):
| Collection.__init__(self, **kwargs)
self._sizes = sizes
self._numsides = numsides
self._paths = [self._path_generator(numsides)]
self._rotation = rotation
self.set_transform(transforms.IdentityTransform())
|
'*segments*
a sequence of (*line0*, *line1*, *line2*), where::
linen = (x0, y0), (x1, y1), ... (xm, ym)
or the equivalent numpy array with two columns. Each line
can be a different length.
*colors*
must be a sequence of RGBA tuples (eg arbitrary color
strings, etc, not allowed).
*antialiaseds*
must be a sequence of ones or zeros
*linestyles* [ \'solid\' | \'dashed\' | \'dashdot\' | \'dotted\' ]
a string or dash tuple. The dash tuple is::
(offset, onoffseq),
where *onoffseq* is an even length tuple of on and off ink
in points.
If *linewidths*, *colors*, or *antialiaseds* is None, they
default to their rcParams setting, in sequence form.
If *offsets* and *transOffset* are not None, then
*offsets* are transformed by *transOffset* and applied after
the segments have been transformed to display coordinates.
If *offsets* is not None but *transOffset* is None, then the
*offsets* are added to the segments before any transformation.
In this case, a single offset can be specified as::
offsets=(xo,yo)
and this value will be added cumulatively to each successive
segment, so as to produce a set of successively offset curves.
*norm*
None (optional for :class:`matplotlib.cm.ScalarMappable`)
*cmap*
None (optional for :class:`matplotlib.cm.ScalarMappable`)
*pickradius* is the tolerance for mouse clicks picking a line.
The default is 5 pt.
The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
If the :class:`~matplotlib.cm.ScalarMappable` matrix
:attr:`~matplotlib.cm.ScalarMappable._A` is not None (ie a call to
:meth:`~matplotlib.cm.ScalarMappable.set_array` has been made), at
draw time a call to scalar mappable will be made to set the colors.'
| def __init__(self, segments, linewidths=None, colors=None, antialiaseds=None, linestyles='solid', offsets=None, transOffset=None, norm=None, cmap=None, pickradius=5, **kwargs):
| if (colors is None):
colors = mpl.rcParams['lines.color']
if (linewidths is None):
linewidths = (mpl.rcParams['lines.linewidth'],)
if (antialiaseds is None):
antialiaseds = (mpl.rcParams['lines.antialiased'],)
self.set_linestyles(linestyles)
colors = _colors.colorConverter.to_rgba_array(colors)
Collection.__init__(self, edgecolors=colors, linewidths=linewidths, linestyles=linestyles, antialiaseds=antialiaseds, offsets=offsets, transOffset=transOffset, norm=norm, cmap=cmap, pickradius=pickradius, **kwargs)
self.set_facecolors([])
self.set_segments(segments)
|
'Set the color(s) of the line collection. *c* can be a
matplotlib color arg (all patches have same color), or a
sequence or rgba tuples; if it is a sequence the patches will
cycle through the sequence
ACCEPTS: matplotlib color arg or sequence of rgba tuples'
| def set_color(self, c):
| self._edgecolors = _colors.colorConverter.to_rgba_array(c)
|
'Set the color(s) of the line collection. *c* can be a
matplotlib color arg (all patches have same color), or a
sequence or rgba tuples; if it is a sequence the patches will
cycle through the sequence
ACCEPTS: matplotlib color arg or sequence of rgba tuples'
| def color(self, c):
| warnings.warn('LineCollection.color deprecated; use set_color instead')
return self.set_color(c)
|
'*sizes*
Gives the area of the circle in points^2
%(Collection)s'
| def __init__(self, sizes, **kwargs):
| Collection.__init__(self, **kwargs)
self._sizes = sizes
self.set_transform(transforms.IdentityTransform())
self._paths = [mpath.Path.unit_circle()]
|
'*widths*: sequence
half-lengths of first axes (e.g., semi-major axis lengths)
*heights*: sequence
half-lengths of second axes
*angles*: sequence
angles of first axes, degrees CCW from the X-axis
*units*: [\'points\' | \'inches\' | \'dots\' | \'width\' | \'height\' | \'x\' | \'y\']
units in which majors and minors are given; \'width\' and \'height\'
refer to the dimensions of the axes, while \'x\' and \'y\'
refer to the *offsets* data units.
Additional kwargs inherited from the base :class:`Collection`:
%(Collection)s'
| def __init__(self, widths, heights, angles, units='points', **kwargs):
| Collection.__init__(self, **kwargs)
self._widths = np.asarray(widths).ravel()
self._heights = np.asarray(heights).ravel()
self._angles = (np.asarray(angles).ravel() * (np.pi / 180.0))
self._units = units
self.set_transform(transforms.IdentityTransform())
self._transforms = []
self._paths = [mpath.Path.unit_circle()]
self._initialized = False
|
'*patches*
a sequence of Patch objects. This list may include
a heterogeneous assortment of different patch types.
*match_original*
If True, use the colors and linewidths of the original
patches. If False, new colors may be assigned by
providing the standard collection arguments, facecolor,
edgecolor, linewidths, norm or cmap.
If any of *edgecolors*, *facecolors*, *linewidths*,
*antialiaseds* are None, they default to their
:data:`matplotlib.rcParams` patch setting, in sequence form.
The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
None (ie a call to set_array has been made), at draw time a
call to scalar mappable will be made to set the face colors.'
| def __init__(self, patches, match_original=False, **kwargs):
| if match_original:
def determine_facecolor(patch):
if patch.fill:
return patch.get_facecolor()
return [0, 0, 0, 0]
facecolors = [determine_facecolor(p) for p in patches]
edgecolors = [p.get_edgecolor() for p in patches]
linewidths = [p.get_linewidths() for p in patches]
antialiaseds = [p.get_antialiased() for p in patches]
Collection.__init__(self, edgecolors=edgecolors, facecolors=facecolors, linewidths=linewidths, linestyles='solid', antialiaseds=antialiaseds)
else:
Collection.__init__(self, **kwargs)
paths = [p.get_transform().transform_path(p.get_path()) for p in patches]
self._paths = paths
|
'Parse the AFM file in file object *fh*'
| def __init__(self, fh):
| (dhead, dcmetrics_ascii, dcmetrics_name, dkernpairs, dcomposite) = parse_afm(fh)
self._header = dhead
self._kern = dkernpairs
self._metrics = dcmetrics_ascii
self._metrics_by_name = dcmetrics_name
self._composite = dcomposite
|
'Return the string width (including kerning) and string height
as a (*w*, *h*) tuple.'
| def string_width_height(self, s):
| if (not len(s)):
return (0, 0)
totalw = 0
namelast = None
miny = 1000000000.0
maxy = 0
for c in s:
if (c == '\n'):
continue
(wx, name, bbox) = self._metrics[ord(c)]
(l, b, w, h) = bbox
try:
kp = self._kern[(namelast, name)]
except KeyError:
kp = 0
totalw += (wx + kp)
thismax = (b + h)
if (thismax > maxy):
maxy = thismax
thismin = b
if (thismin < miny):
miny = thismin
return (totalw, (maxy - miny))
|
'Return the string bounding box'
| def get_str_bbox_and_descent(self, s):
| if (not len(s)):
return (0, 0, 0, 0)
totalw = 0
namelast = None
miny = 1000000000.0
maxy = 0
left = 0
if (not isinstance(s, unicode)):
s = s.decode()
for c in s:
if (c == '\n'):
continue
name = uni2type1.get(ord(c), 'question')
try:
(wx, bbox) = self._metrics_by_name[name]
except KeyError:
name = 'question'
(wx, bbox) = self._metrics_by_name[name]
(l, b, w, h) = bbox
if (l < left):
left = l
try:
kp = self._kern[(namelast, name)]
except KeyError:
kp = 0
totalw += (wx + kp)
thismax = (b + h)
if (thismax > maxy):
maxy = thismax
thismin = b
if (thismin < miny):
miny = thismin
return (left, miny, totalw, (maxy - miny), (- miny))
|
'Return the string bounding box'
| def get_str_bbox(self, s):
| return self.get_str_bbox_and_descent(s)[:4]
|
'Get the name of the character, ie, \';\' is \'semicolon\''
| def get_name_char(self, c, isord=False):
| if (not isord):
c = ord(c)
(wx, name, bbox) = self._metrics[c]
return name
|
'Get the width of the character from the character metric WX
field'
| def get_width_char(self, c, isord=False):
| if (not isord):
c = ord(c)
(wx, name, bbox) = self._metrics[c]
return wx
|
'Get the width of the character from a type1 character name'
| def get_width_from_char_name(self, name):
| (wx, bbox) = self._metrics_by_name[name]
return wx
|
'Get the height of character *c* from the bounding box. This
is the ink height (space is 0)'
| def get_height_char(self, c, isord=False):
| if (not isord):
c = ord(c)
(wx, name, bbox) = self._metrics[c]
return bbox[(-1)]
|
'Return the kerning pair distance (possibly 0) for chars *c1*
and *c2*'
| def get_kern_dist(self, c1, c2):
| (name1, name2) = (self.get_name_char(c1), self.get_name_char(c2))
return self.get_kern_dist_from_name(name1, name2)
|
'Return the kerning pair distance (possibly 0) for chars
*name1* and *name2*'
| def get_kern_dist_from_name(self, name1, name2):
| try:
return self._kern[(name1, name2)]
except:
return 0
|
'Return the font name, eg, \'Times-Roman\''
| def get_fontname(self):
| return self._header['FontName']
|
'Return the font full name, eg, \'Times-Roman\''
| def get_fullname(self):
| name = self._header.get('FullName')
if (name is None):
name = self._header['FontName']
return name
|
'Return the font family name, eg, \'Times\''
| def get_familyname(self):
| name = self._header.get('FamilyName')
if (name is not None):
return name
name = self.get_fullname()
extras = '(?i)([ -](regular|plain|italic|oblique|bold|semibold|light|ultralight|extra|condensed))+$'
return re.sub(extras, '', name)
|
'Return the font weight, eg, \'Bold\' or \'Roman\''
| def get_weight(self):
| return self._header['Weight']
|
'Return the fontangle as float'
| def get_angle(self):
| return self._header['ItalicAngle']
|
'Return the cap height as float'
| def get_capheight(self):
| return self._header['CapHeight']
|
'Return the xheight as float'
| def get_xheight(self):
| return self._header['XHeight']
|
'Return the underline thickness as float'
| def get_underline_thickness(self):
| return self._header['UnderlineThickness']
|
'Return the standard horizontal stem width as float, or *None* if
not specified in AFM file.'
| def get_horizontal_stem_width(self):
| return self._header.get('StdHW', None)
|
'Return the standard vertical stem width as float, or *None* if
not specified in AFM file.'
| def get_vertical_stem_width(self):
| return self._header.get('StdVW', None)
|
'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.'
| def remove(self):
| if (self._remove_method != None):
self._remove_method(self)
else:
raise NotImplementedError('cannot remove artist')
|
'Return *True* if units are set on the *x* or *y* axes'
| def have_units(self):
| ax = self.axes
if ((ax is None) or (ax.xaxis is None)):
return False
return (ax.xaxis.have_units() or ax.yaxis.have_units())
|
'For artists in an axes, if the xaxis has units support,
convert *x* using xaxis unit type'
| def convert_xunits(self, x):
| ax = getattr(self, 'axes', None)
if ((ax is None) or (ax.xaxis is None)):
return x
return ax.xaxis.convert_units(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.