本文整理汇总了Python中matplotlib.cbook.is_string_like函数的典型用法代码示例。如果您正苦于以下问题:Python is_string_like函数的具体用法?Python is_string_like怎么用?Python is_string_like使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_string_like函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_line_tups
def _get_line_tups(*args):
"""
Helper func to parse input to plot()
"""
# Assume all args are either data or format strings, plt.plot will
# deal with raising exceptions.
# A line's arguments consist of [x], y, [fmt]
lines = []
while args:
fmt = ''
y = Q_(args[0])
if len(args) > 1:
if is_string_like(args[1]):
fmt = args[1]
x = Q_(np.arange(y.shape[0], dtype=float))
args = args[2:]
else:
x = y
y = Q_(args[1])
if len(args) > 2 and is_string_like(args[2]):
fmt = args[2]
args = args[3:]
else:
args = args[2:]
else:
x = Q_(np.arange(y.shape[0], dtype=float))
args = args[1:]
lines.append((x, y, fmt))
return lines
示例2: imread
def imread(fname, format=None):
"""
Return image file in *fname* as :class:`numpy.array`. *fname* may
be a string path or a Python file-like object. If using a file
object, it must be opened in binary mode.
If *format* is provided, will try to read file of that type,
otherwise the format is deduced from the filename. If nothing can
be deduced, PNG is tried.
Return value is a :class:`numpy.array`. For grayscale images, the
return array is MxN. For RGB images, the return value is MxNx3.
For RGBA images the return value is MxNx4.
matplotlib can only read PNGs natively, but if `PIL
<http://www.pythonware.com/products/pil/>`_ is installed, it will
use it to load the image and return an array (if possible) which
can be used with :func:`~matplotlib.pyplot.imshow`.
"""
def pilread():
"try to load the image with PIL or return None"
try:
from PIL import Image
except ImportError:
return None
image = Image.open(fname)
return pil_to_array(image)
handlers = {"png": _png.read_png}
if format is None:
if cbook.is_string_like(fname):
basename, ext = os.path.splitext(fname)
ext = ext.lower()[1:]
else:
ext = "png"
else:
ext = format
if ext not in handlers.iterkeys():
im = pilread()
if im is None:
raise ValueError(
"Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images"
% handlers.keys()
)
return im
handler = handlers[ext]
# To handle Unicode filenames, we pass a file object to the PNG
# reader extension, since Python handles them quite well, but it's
# tricky in C.
if cbook.is_string_like(fname):
fname = open(fname, "rb")
return handler(fname)
示例3: use
def use(style):
"""Use matplotlib style settings from a style specification.
The style name of 'default' is reserved for reverting back to
the default style settings.
Parameters
----------
style : str, dict, or list
A style specification. Valid options are:
+------+-------------------------------------------------------------+
| str | The name of a style or a path/URL to a style file. For a |
| | list of available style names, see `style.available`. |
+------+-------------------------------------------------------------+
| dict | Dictionary with valid key/value pairs for |
| | `matplotlib.rcParams`. |
+------+-------------------------------------------------------------+
| list | A list of style specifiers (str or dict) applied from first |
| | to last in the list. |
+------+-------------------------------------------------------------+
"""
if cbook.is_string_like(style) or hasattr(style, "keys"):
# If name is a single str or dict, make it a single element list.
styles = [style]
else:
styles = style
for style in styles:
if not cbook.is_string_like(style):
mpl.rcParams.update(style)
continue
elif style == "default":
mpl.rcdefaults()
continue
if style in library:
mpl.rcParams.update(library[style])
else:
try:
rc = rc_params_from_file(style, use_default_template=False)
mpl.rcParams.update(rc)
except IOError:
msg = (
"'%s' not found in the style library and input is "
"not a valid URL or path. See `style.available` for "
"list of available styles."
)
raise IOError(msg % style)
示例4: is_sequence_of_strings
def is_sequence_of_strings(obj):
"""
Returns true if *obj* is iterable and contains strings
"""
# Note: cbook.is_sequence_of_strings has a bug because
# a numpy array of strings is recognized as being
# string_like and therefore not a sequence of strings
if not cbook.iterable(obj):
return False
if not isinstance(obj, np.ndarray) and cbook.is_string_like(obj):
return False
for o in obj:
if not cbook.is_string_like(o):
return False
return True
示例5: set_family
def set_family(self, family):
"""
Change the font family. May be either an alias (generic name
is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
'fantasy', or 'monospace', a real font name or a list of real
font names. Real font names are not supported when
`text.usetex` is `True`.
"""
if family is None:
family = rcParams['font.family']
if is_string_like(family):
family = [six.text_type(family)]
elif (not is_string_like(family) and isinstance(family, Iterable)):
family = [six.text_type(f) for f in family]
self._family = family
示例6: draw_labels
def draw_labels(self, G, pos,
sizes=None,
labels=None,
font_family='sans-serif'):
ax = plt.gca()
i = 0
for n, label in labels.items():
(x, y) = pos[n]
y += 0.015 + 0.03 * math.sqrt(sizes[i])/3.14/10.0
if not cb.is_string_like(label):
label = str(label) # this will cause "1" and 1 to be labeled the same
font_size = 8
font_color = 'white'
font_weight = 'normal'
if sizes[i] > 50:
font_size = 12
font_weight = 'semibold'
if sizes[i] > 120:
font_color = 'yellow'
if sizes[i] > 10:
t = ax.text(x, y,
label,
size = font_size,
color = font_color,
family = font_family,
weight = font_weight,
style = 'italic',
horizontalalignment = 'center',
verticalalignment = 'center',
transform=ax.transData,
clip_on=True,
)
i += 1
return
示例7: _process_attributes
def _process_attributes(attrs, source, agr, prefix=''):
for attr, attr_dict in attrs.items():
attr_type = attr_dict['type']
if 'static' in attr_type:
value = ''
elif 'function' in attr_type:
value = attr_dict['function'](source)
else:
value = getattr(source, 'get_{}'.format(attr))()
if 'condition' in attr_dict:
if not attr_dict['condition'](value):
continue
if is_string_like(value):
value = latex_to_xmgrace(value)
if 'index' in attr_type:
attr_list = agr_attr_lists[attr_dict.get('maplist', attr)]
index = indexed(attr_list)(value)
if index is None:
if 'map' in attr_type:
attr_list.append(value)
index = attr_list.index(value)
else:
index = 1
value = index
agr.writeline(prefix + attr_dict['fmt'], attr=attr, value=value)
示例8: _print_image
def _print_image(self, filename, format):
if self.flags() & gtk.REALIZED == 0:
# for self.window(for pixmap) and has a side effect of altering
# figure width,height (via configure-event?)
gtk.DrawingArea.realize(self)
width, height = self.get_width_height()
pixmap = gdk.Pixmap (self.window, width, height)
self._renderer.set_pixmap (pixmap)
self._render_figure(pixmap, width, height)
# jpg colors don't match the display very well, png colors match
# better
pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, 0, 8, width, height)
pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(),
0, 0, 0, 0, width, height)
if is_string_like(filename):
try:
pixbuf.save(filename, format)
except gobject.GError as exc:
error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self)
elif is_writable_file_like(filename):
if hasattr(pixbuf, 'save_to_callback'):
def save_callback(buf, data=None):
data.write(buf)
try:
pixbuf.save_to_callback(save_callback, format, user_data=filename)
except gobject.GError as exc:
error_msg_gtk('Save figure failure:\n%s' % (exc,), parent=self)
else:
raise ValueError("Saving to a Python file-like object is only supported by PyGTK >= 2.8")
else:
raise ValueError("filename must be a path or a file-like object")
示例9: use
def use(name):
"""Use matplotlib style settings from a known style sheet or from a file.
Parameters
----------
name : str or list of str
Name of style or path/URL to a style file. For a list of available
style names, see `style.available`. If given a list, each style is
applied from first to last in the list.
"""
if cbook.is_string_like(name):
name = [name]
for style in name:
if style in library:
mpl.rcParams.update(library[style])
else:
try:
rc = rc_params_from_file(style, use_default_template=False)
mpl.rcParams.update(rc)
except:
msg = ("'%s' not found in the style library and input is "
"not a valid URL or path. See `style.available` for "
"list of available styles.")
raise ValueError(msg % style)
示例10: __init__
def __init__(self,
x=0, y=0, text='',
color=None, # defaults to rc params
verticalalignment='bottom',
horizontalalignment='left',
multialignment=None,
fontproperties=None, # defaults to FontProperties()
rotation=None,
linespacing=None,
**kwargs
):
Artist.__init__(self)
if color is None:
colors= rcParams['text.color']
if fontproperties is None:
fontproperties = FontProperties()
elif is_string_like(fontproperties):
fontproperties = FontProperties(fontproperties)
self._animated = False
# if is_string_like(text):
# text = [text]
self._textobjs = [Text(x[ind], y[ind], text[ind], color,
verticalalignment, horizontalalignment, multialignment,
fontproperties, rotation, linespacing, **kwargs)
for ind in xrange(len(x))]
self.update(kwargs)
示例11: print_png
def print_png(self, filename_or_obj, *args, **kwargs):
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
original_dpi = renderer.dpi
renderer.dpi = self.figure.dpi
if is_string_like(filename_or_obj):
filename_or_obj = open(filename_or_obj, 'wb')
close = True
else:
close = False
version_str = 'matplotlib version ' + __version__ + \
', http://matplotlib.org/'
metadata = OrderedDict({'Software': version_str})
user_metadata = kwargs.pop("metadata", None)
if user_metadata is not None:
metadata.update(user_metadata)
try:
_png.write_png(renderer._renderer, filename_or_obj,
self.figure.dpi, metadata=metadata)
finally:
if close:
filename_or_obj.close()
renderer.dpi = original_dpi
示例12: 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)
示例13: to_rgba
def to_rgba(self, arg, alpha=None):
"""
Returns an *RGBA* tuple of four floats from 0-1.
For acceptable values of *arg*, see :meth:`to_rgb`.
If *arg* is an *RGBA* sequence and *alpha* is not *None*,
*alpha* will replace the original *A*.
"""
try:
if not cbook.is_string_like(arg) and cbook.iterable(arg):
if len(arg) == 4:
if [x for x in arg if (float(x) < 0) or (x > 1)]:
# This will raise TypeError if x is not a number.
raise ValueError('number in rbga sequence outside 0-1 range')
if alpha is None:
return tuple(arg)
if alpha < 0.0 or alpha > 1.0:
raise ValueError("alpha must be in range 0-1")
return arg[0], arg[1], arg[2], arg[3] * alpha
r,g,b = arg[:3]
if [x for x in (r,g,b) if (float(x) < 0) or (x > 1)]:
raise ValueError('number in rbg sequence outside 0-1 range')
else:
r,g,b = self.to_rgb(arg)
if alpha is None:
alpha = 1.0
return r,g,b,alpha
except (TypeError, ValueError), exc:
raise ValueError('to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
示例14: get_converter
def get_converter(self, x):
'get the converter interface instance for x, or None'
if not len(self): return None # nothing registered
#DISABLED idx = id(x)
#DISABLED cached = self._cached.get(idx)
#DISABLED if cached is not None: return cached
converter = None
classx = getattr(x, '__class__', None)
if classx is not None:
converter = self.get(classx)
# Check explicity for strings here because they would otherwise
# lead to an infinite recursion, because a single character will
# pass the iterable() check.
if converter is None and iterable(x) and not is_string_like(x):
# if this is anything but an object array, we'll assume
# there are no custom units
if isinstance(x, np.ndarray) and x.dtype != np.object:
return None
for thisx in x:
converter = self.get_converter( thisx )
return converter
#DISABLED self._cached[idx] = converter
return converter
示例15: draw_networkx_labels
def draw_networkx_labels(
G,
pos,
labels=None,
font_size=12,
font_color="k",
font_family="sans-serif",
font_weight="normal",
alpha=1.0,
ax=None,
**kwds
):
"""Draw node labels on the graph G
pos is a dictionary keyed by vertex with a two-tuple
of x-y positions as the value.
See networkx.layout for functions that compute node positions.
labels is an optional dictionary keyed by vertex with node labels
as the values. If provided only labels for the keys in the dictionary
are drawn.
See draw_networkx for the list of other optional parameters.
"""
try:
import matplotlib.pylab as pylab
import matplotlib.cbook as cb
except ImportError:
raise ImportError, "Matplotlib required for draw()"
except RuntimeError:
pass # unable to open display
if ax is None:
ax = pylab.gca()
if labels is None:
labels = dict(zip(G.nodes(), G.nodes()))
text_items = {} # there is no text collection so we'll fake one
for (n, label) in labels.items():
(x, y) = pos[n]
if not cb.is_string_like(label):
label = str(label) # this will cause "1" and 1 to be labeled the same
t = ax.text(
x,
y,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
horizontalalignment="center",
verticalalignment="center",
transform=ax.transData,
)
text_items[n] = t
return text_items