本文整理汇总了Python中matplotlib.cbook.iterable函数的典型用法代码示例。如果您正苦于以下问题:Python iterable函数的具体用法?Python iterable怎么用?Python iterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iterable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hist
def hist(self, x, **kwargs): # pylint: disable=arguments-differ
if iterable(x) and not numpy.size(x):
x = numpy.ndarray((0,))
logbins = kwargs.pop('logbins', False)
bins = kwargs.get('bins', 30)
weights = kwargs.get('weights', None)
if isinstance(weights, (float, int)):
if isinstance(x, numpy.ndarray) or not iterable(x[0]):
kwargs['weights'] = numpy.ones_like(x) * weights
else:
kwargs['weights'] = []
for arr in x:
kwargs['weights'].append(numpy.ones_like(arr) * weights)
kwargs['weights'] = numpy.asarray(kwargs['weights'])
if logbins and (bins is None or isinstance(bins, (float, int))):
bins = bins or 30
range_ = kwargs.pop('range', self.common_limits(x))
if range_[1] == range_[0]:
kwargs['bins'] = bins
else:
kwargs['bins'] = self.bin_boundaries(range_[0], range_[1],
bins, log=True)
if kwargs.get('histtype', None) == 'stepfilled':
kwargs.setdefault('edgecolor', 'black')
return super(HistogramAxes, self).hist(x, **kwargs)
示例2: fetch_historical_yahoo
def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False):
"""
Fetch historical data for ticker between date1 and date2. date1 and
date2 are date or datetime instances, or (year, month, day) sequences.
Ex:
fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))
cachename is the name of the local file cache. If None, will
default to the md5 hash or the url (which incorporates the ticker
and date range)
set dividends=True to return dividends instead of price data. With
this option set, parse functions will not work
a file handle is returned
"""
ticker = ticker.upper()
if iterable(date1):
d1 = (date1[1]-1, date1[2], date1[0])
else:
d1 = (date1.month-1, date1.day, date1.year)
if iterable(date2):
d2 = (date2[1]-1, date2[2], date2[0])
else:
d2 = (date2.month-1, date2.day, date2.year)
if dividends:
g='v'
verbose.report('Retrieving dividends instead of prices')
else:
g='d'
urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'
url = urlFmt % (d1[0], d1[1], d1[2],
d2[0], d2[1], d2[2], ticker, g)
if cachename is None:
cachename = os.path.join(cachedir, md5(url).hexdigest())
if os.path.exists(cachename):
fh = open(cachename)
verbose.report('Using cachefile %s for %s'%(cachename, ticker))
else:
mkdirs(cachedir)
urlfh = urlopen(url)
fh = open(cachename, 'wb')
fh.write(urlfh.read())
fh.close()
verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
fh = open(cachename, 'r')
return fh
示例3: from_list
def from_list(name, colors, N=256, gamma=1.0):
"""
Make a linear segmented colormap with *name* from a sequence
of *colors* which evenly transitions from colors[0] at val=0
to colors[-1] at val=1. *N* is the number of rgb quantization
levels.
Alternatively, a list of (value, color) tuples can be given
to divide the range unevenly.
"""
if not cbook.iterable(colors):
raise ValueError('colors must be iterable')
if cbook.iterable(colors[0]) and len(colors[0]) == 2 and \
not cbook.is_string_like(colors[0]):
# List of value, color pairs
vals, colors = zip(*colors)
else:
vals = np.linspace(0., 1., len(colors))
cdict = dict(red=[], green=[], blue=[])
for val, color in zip(vals, colors):
r,g,b = colorConverter.to_rgb(color)
cdict['red'].append((val, r, r))
cdict['green'].append((val, g, g))
cdict['blue'].append((val, b, b))
return LinearSegmentedColormap(name, cdict, N, gamma)
示例4: getStock
def getStock(ticker, d1, d2, verbose=False):
if not iterable(d1): d1 = (d1, 1, 1)
if not iterable(d2): d2 = (d2, 1, 1)
saveStock(ticker, d1, d2)
pickleFile = "%s/%s.pklz" % (storageDir, ticker)
d = { }
d["days"] = { }
try:
fh = gzip.open(pickleFile, "rb")
dOld = pickle.load(fh)
fh.close()
except:
if(verbose): print "[MM] Error: file (%s/%s.pklz) does not exist" % (storageDir, ticker)
return d
dt1, dt2 = datetime.datetime(*d1), datetime.datetime(*d2)
day1, day2 = u.tuple2inum(d1), u.tuple2inum(d2)
for day in dOld["days"].keys():
if( day1 <= day <= day2 ):
d["days"][day] = dOld["days"][day]
return d
示例5: add_lines
def add_lines(self, levels, colors, linewidths, erase=True):
"""
Draw lines on the colorbar.
*colors* and *linewidths* must be scalars or
sequences the same length as *levels*.
Set *erase* to False to add lines without first
removing any previously added lines.
"""
y = self._locate(levels)
igood = (y < 1.001) & (y > -0.001)
y = y[igood]
if cbook.iterable(colors):
colors = np.asarray(colors)[igood]
if cbook.iterable(linewidths):
linewidths = np.asarray(linewidths)[igood]
N = len(y)
x = np.array([0.0, 1.0])
X, Y = np.meshgrid(x, y)
if self.orientation == "vertical":
xy = [list(zip(X[i], Y[i])) for i in range(N)]
else:
xy = [list(zip(Y[i], X[i])) for i in range(N)]
col = collections.LineCollection(xy, linewidths=linewidths)
if erase and self.lines:
for lc in self.lines:
lc.remove()
self.lines = []
self.lines.append(col)
col.set_color(colors)
self.ax.add_collection(col)
示例6: _fetch_historical_yahoo
def _fetch_historical_yahoo(self, ticker, date1, date2, freq=None, cachename=None):
"""matplotlib's implementation, modified to provide proxy support and frequency
Fetch historical data for ticker between date1 and date2. date1 and
date2 are date or datetime instances, or (year, month, day) sequences.
Ex:
fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))
cachename is the name of the local file cache. If None, will
default to the md5 hash or the url (which incorporates the ticker
and date range)
a file handle is returned
"""
if freq is None or type(freq) != str:
raise ValueError('Must enter a frequency as a string, m, w, or d')
proxy = self._proxy
ticker = ticker.upper()
configdir = get_configdir()
cachedir = os.path.join(configdir, 'finance.cache')
if iterable(date1):
d1 = (date1[1]-1, date1[2], date1[0])
else:
d1 = (date1.month-1, date1.day, date1.year)
if iterable(date2):
d2 = (date2[1]-1, date2[2], date2[0])
else:
d2 = (date2.month-1, date2.day, date2.year)
urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'
url = urlFmt % (d1[0], d1[1], d1[2],
d2[0], d2[1], d2[2], ticker, freq)
if proxy:
proxy_support = urllib2.ProxyHandler(proxy)
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
if cachename is None:
cachename = os.path.join(cachedir, md5(url).hexdigest())
if os.path.exists(cachename):
fh = file(cachename)
verbose.report('Using cachefile %s for %s'%(cachename, ticker))
else:
if not os.path.isdir(cachedir):
os.mkdir(cachedir)
urlfh = urllib2.urlopen(url)
fh = file(cachename, 'w')
fh.write(urlfh.read())
fh.close()
verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
fh = file(cachename, 'r')
return fh
示例7: plot
def plot(self, xs, ys, *args, **kwargs):
'''
Plot 2D or 3D data.
========== ================================================
Argument Description
========== ================================================
*xs*, *ys* X, y coordinates of vertices
*zs* z value(s), either one for all points or one for
each point.
*zdir* Which direction to use as z ('x', 'y' or 'z')
when plotting a 2d set.
========== ================================================
Other arguments are passed on to
:func:`~matplotlib.axes.Axes.plot`
'''
# FIXME: This argument parsing might be better handled
# when we set later versions of python for
# minimum requirements. Currently at 2.4.
# Note that some of the reason for the current difficulty
# is caused by the fact that we want to insert a new
# (semi-optional) positional argument 'Z' right before
# many other traditional positional arguments occur
# such as the color, linestyle and/or marker.
had_data = self.has_data()
zs = kwargs.pop('zs', 0)
zdir = kwargs.pop('zdir', 'z')
argsi = 0
# First argument is array of zs
if len(args) > 0 and cbook.iterable(args[0]) and \
len(xs) == len(args[0]) :
# So, we know that it is an array with
# first dimension the same as xs.
# Next, check to see if the data contained
# therein (if any) is scalar (and not another array).
if len(args[0]) == 0 or cbook.is_scalar(args[0][0]) :
zs = args[argsi]
argsi += 1
# First argument is z value
elif len(args) > 0 and cbook.is_scalar(args[0]):
zs = args[argsi]
argsi += 1
# Match length
if not cbook.iterable(zs):
zs = np.ones(len(xs)) * zs
lines = Axes.plot(self, xs, ys, *args[argsi:], **kwargs)
for line in lines:
art3d.line_2d_to_3d(line, zs=zs, zdir=zdir)
self.auto_scale_xyz(xs, ys, zs, had_data)
return lines
示例8: append_fields
def append_fields(rec, names, arr, dtype=None):
"""
Appends a field to an existing record array, handling masked fields
if necessary.
Parameters
----------
rec : numpy record array
Array to which the new field should be appended
names : string
Names to be given to the new fields
arr : ndarray
Array containing the data for the new fields.
dtype : data-type or None, optional
Data type of the new fields. If this is None, the data types will
be obtained from `arr`.
Returns
-------
out : numpy record array
`rec` with the new field appended.
rec = append_fields(rec, name, arr)
"""
if not iterable(names):
names = [names]
if not iterable(arr):
arr = [arr]
if dtype is None:
dtype = [a.dtype for a in arr]
newdtype = np.dtype(rec.dtype.descr + zip(names, dtype))
newrec = np.empty(rec.shape, dtype=newdtype).view(type(rec))
for name in rec.dtype.names:
newrec[name] = rec[name]
try:
newrec.mask[name] = rec.mask[name]
except AttributeError:
pass #Not a masked array
for n,a in zip(names, arr):
newrec[n] = a
try:
old_mask = a.mask
except AttributeError:
old_mask = np.array([False]*a.size).reshape(a.shape)
try:
newrec[n].mask = old_mask
except AttributeError:
pass
return newrec
示例9: getTimeIntervall
def getTimeIntervall(stream, start=None, end=None, relative='starttime', ret_rel='utc'):
"""
Create two lists of UTCDateTimes - start list and end list
'time' can stand for UTCDateTime, list of UTCDateTimes, header entry out of
('ponset', 'sonset', 'startime', 'endtime') or 'middle'
:param start, end: - None (means start- resp. endtime)
- time object
- or seconds relative to param relative
:param relative: times (if given as seconds=numbers) are taken relative to
this parameter, is also needed for param ret_rel='relative
-time object
:param ret_rel: - 'utc' output in absolute UTCDateTime
- 'relative': output in seconds relative to param relative
- time object: output in seconds relative to time
:return: start and end list of UTCDateTime or None if stream has length 0
"""
N = len(stream)
if N == 0:
return
# get list of UTCDateTimes for start_out and end_out
if start == None:
start = 'starttime'
if end == None:
end = 'endtime'
start_out = _getUTCListFromSth(stream, start)
end_out = _getUTCListFromSth(stream, end)
# get list of UTCDateTimes for relative if needed
if start_out == None or end_out == None or ret_rel == 'relative':
relative = _getUTCListFromSth(stream, relative, raisenumber=True)
# get list of UTCDateTimes for start_out and end_out
if start_out == None:
if cbook.iterable(start):
start_out = [utc + start[i] for i, utc in enumerate(relative)]
else:
start_out = [i + start for i in relative]
if end_out == None:
if cbook.iterable(start):
end_out = [utc + end[i] for i, utc in enumerate(relative)]
else:
end_out = [i + end for i in relative]
# convert UTCDateTimes to seconds if ret_rel demands it
if ret_rel == 'utc':
return start_out, end_out
elif ret_rel != 'relative':
relative = _getUTCListFromSth(stream, ret_rel)
start_out = [start_out[i] - relative[i] for i in range(N)]
end_out = [end_out[i] - relative[i] for i in range(N)]
return start_out, end_out
示例10: wsat
def wsat(Temp, press):
"""
wsat(Temp, press)
Calculates the saturation vapor mixing ratio of an air parcel.
Parameters
- - - - - -
Temp : float or array_like
Temperature in Kelvin.
press : float or array_like
Pressure in Pa.
Returns
- - - -
theWs : float or array_like
Saturation water vapor mixing ratio in (kg/kg).
Raises
- - - -
IOError
If both 'Temp' and 'press' are array_like.
Examples
- - - - -
>>> test.assert_almost_equal(wsat(300, 8e4),0.02875,decimal=4)
>>> test.assert_array_almost_equal(wsat([300,310], 8e4),[0.0287, 0.0525],decimal=4)
>>> test.assert_array_almost_equal(wsat(300, [8e4, 7e4]),[0.0287, 0.0330],decimal=4)
>>> wsat([300, 310], [8e4, 7e4])
Traceback (most recent call last):
...
IOError: Can't have two vector inputs.
"""
is_scalar_temp=True
if cbook.iterable(Temp):
is_scalar_temp = False
is_scalar_press=True
if cbook.iterable(press):
is_scalar_press = False
Temp=np.atleast_1d(Temp)
press=np.atleast_1d(press)
if (np.size(Temp) !=1) and (np.size(press) != 1):
raise IOError, "Can't have two vector inputs."
es = esat(Temp);
theWs=(c.eps * es/ (press - es))
theWs[theWs > 0.060]=0.06
theWs[theWs < 0.0] = 0.
if is_scalar_temp and is_scalar_press:
theWs=theWs[0]
return theWs
示例11: __call__
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
if cbook.iterable(value):
vtype = 'array'
val = np.ma.asarray(value).astype(np.float)
else:
vtype = 'scalar'
val = np.ma.array([value]).astype(np.float)
self.autoscale_None(val)
vmin, vmax = float(self.vmin), float(self.vmax)
if vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif vmin==vmax:
return 0.0 * val
else:
if clip:
mask = np.ma.getmask(val)
val = np.ma.array(np.clip(val.filled(vmax), vmin, vmax),
mask=mask)
result = np.ma.array(np.interp(val, self.xval, self.yval),
mask=np.ma.getmask(val))
result[np.isinf(val.data)] = -np.inf
if vtype == 'scalar':
result = result[0]
return result
示例12: __call__
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
if cbook.iterable(value):
vtype = 'array'
val = ma.asarray(value).astype(np.float)
else:
vtype = 'scalar'
val = ma.array([value]).astype(np.float)
self.autoscale_None(val)
vmin, vmax = self.vmin, self.vmax
if vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif vmin<=0:
raise ValueError("values must all be positive")
elif vmin==vmax:
return 0.0 * val
else:
if clip:
mask = ma.getmask(val)
val = ma.array(np.clip(val.filled(vmax), vmin, vmax),
mask=mask)
result = (ma.log(val)-np.log(vmin))/(np.log(vmax)-np.log(vmin))
if vtype == 'scalar':
result = result[0]
return result
示例13: __init__
def __init__(self, artists, tolerance=5, offsets=(-20, 20), template="x: %0.2f\ny: %0.2f", display_all=False):
"""Create the data cursor and connect it to the relevant figure.
"artists" is the matplotlib artist or sequence of artists that will be
selected.
"tolerance" is the radius (in points) that the mouse click must be
within to select the artist.
"offsets" is a tuple of (x,y) offsets in points from the selected
point to the displayed annotation box
"template" is the format string to be used. Note: For compatibility
with older versions of python, this uses the old-style (%)
formatting specification.
"display_all" controls whether more than one annotation box will
be shown if there are multiple axes. Only one will be shown
per-axis, regardless.
"""
self.template = template
self.offsets = offsets
self.display_all = display_all
if not cbook.iterable(artists):
artists = [artists]
self.artists = artists
self.axes = tuple(set(art.axes for art in self.artists))
self.figures = tuple(set(ax.figure for ax in self.axes))
self.annotations = {}
for ax in self.axes:
self.annotations[ax] = self.annotate(ax)
for artist in self.artists:
artist.set_picker(tolerance)
for fig in self.figures:
fig.canvas.mpl_connect("pick_event", self)
示例14: hist
def hist(*args, **kwargs):
"""
Plots a histogram of the provided data. Can provide optional argument
"grid='x'" or "grid='y'" to draw a white grid over the histogram. Almost like "erasing" some of the plot,
but it adds more information!
"""
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
color_cycle = ax._get_lines.color_cycle
# Reassign the default colors to Set2 by Colorbrewer
if iterable(args[0]):
if isinstance(args[0], list):
ncolors = len(args[0])
else:
if len(args[0].shape) == 2:
ncolors = args[0].shape[1]
else:
ncolors = 1
kwargs.setdefault('color', [next(color_cycle) for _ in range(ncolors)])
else:
kwargs.setdefault('color', next(color_cycle))
kwargs.setdefault('edgecolor', 'white')
show_ticks = kwargs.pop('show_ticks', False)
# If no grid specified, don't draw one.
grid = kwargs.pop('grid', None)
# print 'hist kwargs', kwargs
patches = ax.hist(*args, **kwargs)
remove_chartjunk(ax, ['top', 'right'], grid=grid, show_ticks=show_ticks)
return ax
示例15: __init__
def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20),
formatter = fmt, display_all = False):
"""Create the data cursor and connect it to the relevant figure.
"artists" is the matplotlib artist or sequence of artists that will be
selected.
"tolerance" is the radius (in points) that the mouse click must be
within to select the artist.
"offsets" is a tuple of (x,y) offsets in points from the selected
point to the displayed annotation box
"formatter" is a callback function which takes 2 numeric arguments and
returns a string
"display_all" controls whether more than one annotation box will
be shown if there are multiple axes. Only one will be shown
per-axis, regardless.
"""
self._points = np.column_stack((x,y))
self.formatter = formatter
self.offsets = offsets
self.display_all = display_all
if not cbook.iterable(artists):
artists = [artists]
self.artists = artists
self.axes = tuple(set(art.axes for art in self.artists))
self.figures = tuple(set(ax.figure for ax in self.axes))
self.annotations = {}
for ax in self.axes:
self.annotations[ax] = self.annotate(ax)
for artist in self.artists:
artist.set_picker(tolerance)
for fig in self.figures:
fig.canvas.mpl_connect('pick_event', self)