本文整理汇总了Python中matplotlib.patches.FancyBboxPatch类的典型用法代码示例。如果您正苦于以下问题:Python FancyBboxPatch类的具体用法?Python FancyBboxPatch怎么用?Python FancyBboxPatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FancyBboxPatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test2
def test2(ax):
# bbox=round has two optional argument. pad and rounding_size.
# They can be set during the initialization.
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
# boxstyle and its argument can be later modified with
# set_boxstyle method. Note that the old attributes are simply
# forgotten even if the boxstyle name is same.
p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2")
# or
# p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.1\n rounding_size=0.2"',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
# l = p_fancy.get_path().vertices
# ax.plot(l[:,0], l[:,1], ".")
draw_bbox(ax, bb)
示例2: __init__
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
"""
*pad* : boundary pad
.. note::
*pad* need to given in points and will be
scale with the renderer dpi, while *width* and *hight*
need to be in pixels.
"""
super(PaddedBox, self).__init__()
self.pad = pad
self._children = [child]
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=1, #self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square",pad=0)
if patch_attrs is not None:
self.patch.update(patch_attrs)
self._drawFrame = draw_frame
示例3: _basic_outline
def _basic_outline(self, colors):
if self.need != 0:
#center = Circle(
# self.coords,
# self.r / float(20),
# color=color['lc'], zorder=4, facecolor=color['lc'], fill=True, alpha=self.alpha
#)
if self.layout_mode:
border = Circle(
self.coords, 0.99 * self.r, color=colors['lc'], zorder=3, fill=False, edgecolor=colors['lc'],
alpha=self.alpha, linewidth=70 * self.scale
)
role_fill = Circle(
self.coords, self.r, color=self.role_color, zorder=4, facecolor=self.role_color, fill=True,
alpha=0.5 * self.alpha
)
self.basic_structure = [role_fill, border]
else:
border = Circle(
self.coords, self.r, color=colors['lc'], zorder=3, fill=False, edgecolor=colors['lc'],
alpha=self.alpha, linewidth=0.5
)
self.basic_structure = [border, ]#center]
else:
center = Circle(
self.coords, self.r / self._transit_fraction, color=colors['lc'], zorder=4, facecolor=colors['lc'],
fill=True, alpha=self.alpha
)
self.basic_structure = [center]
if not self.functional:
size = self.r if self.need != 0. else self.r / self._transit_fraction
cross_bar = FancyBboxPatch(
(0, 0), 2.4 * size, 0.2 * size,
boxstyle="square,pad={}".format(0.05 * self.scale * self.label_scale),
color=colors['ac'], alpha=min(1, 2 * self.alpha), zorder=6
)
rotator = Affine2D().rotate_deg(-40)
corner_coords = (
self.coords[0] - size,
self.coords[1] + 0.7 * size
)
translator = Affine2D().translate(*corner_coords)
transform = rotator + translator
cross_bar.set_transform(transform)
self.super_patch_collection.append(cross_bar)
示例4: PaddedBox
class PaddedBox(OffsetBox):
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
"""
*pad* : boundary pad
.. note::
*pad* need to given in points and will be
scale with the renderer dpi, while *width* and *hight*
need to be in pixels.
"""
super(PaddedBox, self).__init__()
self.pad = pad
self._children = [child]
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=1, #self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square",pad=0)
if patch_attrs is not None:
self.patch.update(patch_attrs)
self._drawFrame = draw_frame
def get_extent_offsets(self, renderer):
"""
update offset of childrens and return the extents of the box
"""
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
w, h, xd, yd = self._children[0].get_extent(renderer)
return w + 2*pad, h + 2*pad, \
xd+pad, yd+pad, \
[(0, 0)]
def draw(self, renderer):
"""
Update the location of children if necessary and draw them
to the given *renderer*.
"""
width, height, xdescent, ydescent, offsets = self.get_extent_offsets(renderer)
px, py = self.get_offset(width, height, xdescent, ydescent, renderer)
for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px+ox, py+oy))
self.draw_frame(renderer)
for c in self.get_visible_children():
c.draw(renderer)
#bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
def update_frame(self, bbox, fontsize=None):
self.patch.set_bounds(bbox.x0, bbox.y0,
bbox.width, bbox.height)
if fontsize:
self.patch.set_mutation_scale(fontsize)
def draw_frame(self, renderer):
# update the location and size of the legend
bbox = self.get_window_extent(renderer)
self.update_frame(bbox)
if self._drawFrame:
self.patch.draw(renderer)
示例5: AnnotationBbox
class AnnotationBbox(martist.Artist, _AnnotationBase):
"""
Annotation-like class, but with offsetbox instead of Text.
"""
zorder = 3
def __str__(self):
return "AnnotationBbox(%g,%g)"%(self.xy[0],self.xy[1])
@docstring.dedent_interpd
def __init__(self, offsetbox, xy,
xybox=None,
xycoords='data',
boxcoords=None,
frameon=True, pad=0.4, # BboxPatch
annotation_clip=None,
box_alignment=(0.5, 0.5),
bboxprops=None,
arrowprops=None,
fontsize=None,
**kwargs):
"""
*offsetbox* : OffsetBox instance
*xycoords* : same as Annotation but can be a tuple of two
strings which are interpreted as x and y coordinates.
*boxcoords* : similar to textcoords as Annotation but can be a
tuple of two strings which are interpreted as x and y
coordinates.
*box_alignment* : a tuple of two floats for a vertical and
horizontal alignment of the offset box w.r.t. the *boxcoords*.
The lower-left corner is (0.0) and upper-right corner is (1.1).
other parameters are identical to that of Annotation.
"""
self.offsetbox = offsetbox
self.arrowprops = arrowprops
self.set_fontsize(fontsize)
if arrowprops is not None:
self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
self.arrow_patch = FancyArrowPatch((0, 0), (1,1),
**self.arrowprops)
else:
self._arrow_relpos = None
self.arrow_patch = None
_AnnotationBase.__init__(self,
xy, xytext=xybox,
xycoords=xycoords, textcoords=boxcoords,
annotation_clip=annotation_clip)
martist.Artist.__init__(self, **kwargs)
#self._fw, self._fh = 0., 0. # for alignment
self._box_alignment = box_alignment
# frame
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square",pad=pad)
if bboxprops:
self.patch.set(**bboxprops)
self._drawFrame = frameon
def contains(self,event):
t,tinfo = self.offsetbox.contains(event)
#if self.arrow_patch is not None:
# a,ainfo=self.arrow_patch.contains(event)
# t = t or a
# self.arrow_patch is currently not checked as this can be a line - JJ
return t,tinfo
def get_children(self):
children = [self.offsetbox, self.patch]
if self.arrow_patch:
children.append(self.arrow_patch)
return children
def set_figure(self, fig):
if self.arrow_patch is not None:
self.arrow_patch.set_figure(fig)
self.offsetbox.set_figure(fig)
martist.Artist.set_figure(self, fig)
def set_fontsize(self, s=None):
#.........这里部分代码省略.........
示例6: _label
def _label(self, colors):
"""
Method to create an edges label
:return:
"""
its_label = '{:g}'.format(abs(self.edge.capacity) if self.edge.capacity is not None else '')
status_color = colors['bc']
if not self.layout_mode:
in_percent = int(round(100 * self.edge.flux / float(self.edge.capacity), 0))
if in_percent < 100:
status_color = colors['wc']
its_label += '; {:g}%'.format(in_percent)
# get the label coordinates based on self.segments (use the end of the first segment if several segments are
# present, if it is a single, place the label half the way
s_coords, e_coords = self.segments[0]
edge_vec = Vec(s_coords, e_coords)
start_vec = Vec(s_coords)
# maybe always use the last part...
if len(self.segments) == 1: # single segment: place it half way
part_way_vec = start_vec + self.label_position * edge_vec
coords_label = part_way_vec.coords[:2]
else: # several segments: place label at the end of the first
#half_way_vec = start_vec + 0.5 * edge_vec
#coords_label = half_way_vec.coords[:2]
coords_label = e_coords
if self.with_label:
self.labels = [
# so far there is just a single label for an edge
(
its_label,
coords_label,
{
'horizontalalignment': 'center',
'verticalalignment': 'center',
'size': self.scale * 200 * self.label_scale,
'color': colors['tc'],
'box_fc': status_color
}
)
]
else:
self.labels = None
# cross through the label if it is not functional
if not self.functional:
cross_bar = FancyBboxPatch(
(0, 0), self.scale * self.label_scale, 0.07 * self.scale * self.label_scale,
boxstyle="square,pad={}".format(0.05 * self.scale * self.label_scale),
color=colors['ac'], alpha=min(1, 2 * self.alpha), zorder=6
)
rotator = Affine2D().rotate_deg(-45)
corner_coords = (
coords_label[0] - 0.4 * self.scale * self.label_scale,
coords_label[1] + 0.3 * self.scale * self.label_scale
)
translator = Affine2D().translate(*corner_coords)
transform = rotator + translator
cross_bar.set_transform(transform)
self.super_patch_collection.append(cross_bar)
示例7: __init__
#.........这里部分代码省略.........
del localdict
handles = list(handles)
if len(handles)<2:
ncol = 1
self._ncol = ncol
if self.numpoints <= 0:
raise ValueError("numpoints must be > 0; it was %d"% numpoints)
# introduce y-offset for handles of the scatter plot
if scatteryoffsets is None:
self._scatteryoffsets = np.array([3./8., 4./8., 2.5/8.])
else:
self._scatteryoffsets = np.asarray(scatteryoffsets)
reps = int(self.scatterpoints / len(self._scatteryoffsets)) + 1
self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints]
# _legend_box is an OffsetBox instance that contains all
# legend items and will be initialized from _init_legend_box()
# method.
self._legend_box = None
if isinstance(parent,Axes):
self.isaxes = True
self.set_axes(parent)
self.set_figure(parent.figure)
elif isinstance(parent,Figure):
self.isaxes = False
self.set_figure(parent)
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0,'best']:
loc = 'upper right'
if is_string_like(loc):
if loc not in self.codes:
if self.isaxes:
warnings.warn('Unrecognized location "%s". Falling back on "best"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.iterkeys())))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.iterkeys())))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=rcParams["axes.facecolor"],
edgecolor=rcParams["axes.edgecolor"],
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox == True:
self.legendPatch.set_boxstyle("round",pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square",pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels)
self._loc = loc
self.set_title(title)
self._last_fontsize_points = self._fontsize
self._draggable = None
示例8: Legend
#.........这里部分代码省略.........
self.set_figure(parent)
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0,'best']:
loc = 'upper right'
if is_string_like(loc):
if loc not in self.codes:
if self.isaxes:
warnings.warn('Unrecognized location "%s". Falling back on "best"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.keys())))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.keys())))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._loc = loc
self._mode = mode
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox == True:
self.legendPatch.set_boxstyle("round",pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square",pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = True
# init with null renderer
self._init_legend_box(handles, labels)
self._last_fontsize_points = self.fontsize
def _set_artist_props(self, a):
"""
set the boilerplate props for artists added to axes
"""
示例9: __init__
#.........这里部分代码省略.........
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
self._loc_used_default = loc is None
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0, 'best']:
loc = 'upper right'
if isinstance(loc, str):
if loc not in self.codes:
if self.isaxes:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling "
"back on 'best'; valid locations are\n\t{}\n"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 0
else:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling "
"back on 'upper right'; valid locations are\n\t{}\n'"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
cbook.warn_deprecated(
"3.1", message="Automatic legend placement (loc='best') not "
"implemented for figure legend. Falling back on 'upper "
"right'. This will raise an exception %(removal)s.")
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
if facecolor is None:
facecolor = rcParams["legend.facecolor"]
if facecolor == 'inherit':
facecolor = rcParams["axes.facecolor"]
if edgecolor is None:
edgecolor = rcParams["legend.edgecolor"]
if edgecolor == 'inherit':
edgecolor = rcParams["axes.edgecolor"]
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=facecolor,
edgecolor=edgecolor,
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox:
self.legendPatch.set_boxstyle("round", pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square", pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels, markerfirst)
# If shadow is activated use framealpha if not
# explicitly passed. See Issue 8943
if framealpha is None:
if shadow:
self.get_frame().set_alpha(1)
else:
self.get_frame().set_alpha(rcParams["legend.framealpha"])
else:
self.get_frame().set_alpha(framealpha)
tmp = self._loc_used_default
self._set_loc(loc)
self._loc_used_default = tmp # ignore changes done by _set_loc
# figure out title fontsize:
if title_fontsize is None:
title_fontsize = rcParams['legend.title_fontsize']
tprop = FontProperties(size=title_fontsize)
self.set_title(title, prop=tprop)
self._last_fontsize_points = self._fontsize
self._draggable = None
示例10: Legend
#.........这里部分代码省略.........
loc = 0
else:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling "
"back on 'upper right'; valid locations are\n\t{}\n'"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
cbook.warn_deprecated(
"3.1", message="Automatic legend placement (loc='best') not "
"implemented for figure legend. Falling back on 'upper "
"right'. This will raise an exception %(removal)s.")
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
if facecolor is None:
facecolor = rcParams["legend.facecolor"]
if facecolor == 'inherit':
facecolor = rcParams["axes.facecolor"]
if edgecolor is None:
edgecolor = rcParams["legend.edgecolor"]
if edgecolor == 'inherit':
edgecolor = rcParams["axes.edgecolor"]
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=facecolor,
edgecolor=edgecolor,
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox:
self.legendPatch.set_boxstyle("round", pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square", pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels, markerfirst)
# If shadow is activated use framealpha if not
# explicitly passed. See Issue 8943
if framealpha is None:
if shadow:
示例11: Legend
#.........这里部分代码省略.........
'on "best"; valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes)))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back '
'on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes)))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not '
'implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
if facecolor is None:
facecolor = rcParams["legend.facecolor"]
if facecolor == 'inherit':
facecolor = rcParams["axes.facecolor"]
if edgecolor is None:
edgecolor = rcParams["legend.edgecolor"]
if edgecolor == 'inherit':
edgecolor = rcParams["axes.edgecolor"]
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=facecolor,
edgecolor=edgecolor,
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox:
self.legendPatch.set_boxstyle("round", pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square", pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels, markerfirst)
if framealpha is None:
self.get_frame().set_alpha(rcParams["legend.framealpha"])
else:
self.get_frame().set_alpha(framealpha)
示例12: AnchoredOffsetbox
class AnchoredOffsetbox(OffsetBox):
"""
An offset box placed according to the legend location
loc. AnchoredOffsetbox has a single child. When multiple children
is needed, use other OffsetBox class to enlose them. By default,
the offset box is anchored against its parent axes. You may
explicitly specify the bbox_to_anchor.
"""
zorder = 5 # zorder of the legend
def __init__(self, loc,
pad=0.4, borderpad=0.5,
child=None, prop=None, frameon=True,
bbox_to_anchor=None,
bbox_transform=None,
**kwargs):
"""
loc is a string or an integer specifying the legend location.
The valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
pad : pad around the child for drawing a frame. given in
fraction of fontsize.
borderpad : pad between offsetbox frame and the bbox_to_anchor,
child : OffsetBox instance that will be anchored.
prop : font property. This is only used as a reference for paddings.
frameon : draw a frame box if True.
bbox_to_anchor : bbox to anchor. Use self.axes.bbox if None.
bbox_transform : with which the bbox_to_anchor will be transformed.
"""
super(AnchoredOffsetbox, self).__init__(**kwargs)
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
self.set_child(child)
self.loc = loc
self.borderpad=borderpad
self.pad = pad
if prop is None:
self.prop=FontProperties(size=rcParams["legend.fontsize"])
elif isinstance(prop, dict):
self.prop=FontProperties(**prop)
if "size" not in prop:
self.prop.set_size(rcParams["legend.fontsize"])
else:
self.prop = prop
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square",pad=0)
self._drawFrame = frameon
def set_child(self, child):
"set the child to be anchored"
self._child = child
def get_child(self):
"return the child"
return self._child
def get_children(self):
"return the list of children"
return [self._child]
def get_extent(self, renderer):
"""
return the extent of the artist. The extent of the child
added with the pad is returned
"""
w, h, xd, yd = self.get_child().get_extent(renderer)
fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
pad = self.pad * fontsize
#.........这里部分代码省略.........
示例13: __init__
#.........这里部分代码省略.........
# _legend_box is an OffsetBox instance that contains all
# legend items and will be initialized from _init_legend_box()
# method.
self._legend_box = None
if isinstance(parent, Axes):
self.isaxes = True
self.axes = parent
self.set_figure(parent.figure)
elif isinstance(parent, Figure):
self.isaxes = False
self.set_figure(parent)
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0, 'best']:
loc = 'upper right'
if is_string_like(loc):
if loc not in self.codes:
if self.isaxes:
warnings.warn('Unrecognized location "%s". Falling back '
'on "best"; valid locations are\n\t%s\n'
% (loc, '\n\t'.join(
six.iterkeys(self.codes))))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back '
'on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(
six.iterkeys(self.codes))))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not '
'implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
if rcParams["legend.facecolor"] == 'inherit':
facecolor = rcParams["axes.facecolor"]
else:
facecolor = rcParams["legend.facecolor"]
if rcParams["legend.edgecolor"] == 'inherit':
edgecolor = rcParams["axes.edgecolor"]
else:
edgecolor = rcParams["legend.edgecolor"]
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=facecolor,
edgecolor=edgecolor,
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox:
self.legendPatch.set_boxstyle("round", pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square", pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels, markerfirst)
if framealpha is None:
self.get_frame().set_alpha(rcParams["legend.framealpha"])
else:
self.get_frame().set_alpha(framealpha)
self._loc = loc
self.set_title(title)
self._last_fontsize_points = self._fontsize
self._draggable = None
if displace is not None:
self.set_displace(displace)
示例14: Legend
#.........这里部分代码省略.........
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0,'best']:
loc = 'upper right'
if is_string_like(loc):
if loc not in self.codes:
if self.isaxes:
warnings.warn('Unrecognized location "%s". Falling back on "best"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.iterkeys())))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.iterkeys())))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=rcParams["axes.facecolor"],
edgecolor=rcParams["axes.edgecolor"],
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox == True:
self.legendPatch.set_boxstyle("round",pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square",pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels)
self._loc = loc
self.set_title(title)
示例15: __init__
#.........这里部分代码省略.........
# convert values of deprecated keywords (ginve in axes coords)
# to new vaules in a fraction of the font size
# conversion factor
bbox = parent.bbox
axessize_fontsize = min(bbox.width, bbox.height)/self.fontsize
for k, v in deprecated_kwds.items():
# use deprecated value if not None and if their newer
# counter part is None.
if localdict[k] is not None and localdict[v] is None:
warnings.warn("Use '%s' instead of '%s'." % (v, k),
DeprecationWarning)
setattr(self, v, localdict[k]*axessize_fontsize)
continue
# Otherwise, use new keywords
if localdict[v] is None:
setattr(self, v, rcParams["legend."+v])
else:
setattr(self, v, localdict[v])
del localdict
self._ncol = ncol
if self.numpoints <= 0:
raise ValueError("numpoints must be >= 0; it was %d"% numpoints)
# introduce y-offset for handles of the scatter plot
if scatteryoffsets is None:
self._scatteryoffsets = np.array([3./8., 4./8., 2.5/8.])
else:
self._scatteryoffsets = np.asarray(scatteryoffsets)
reps = int(self.numpoints / len(self._scatteryoffsets)) + 1
self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints]
# _legend_box is an OffsetBox instance that contains all
# legend items and will be initialized from _init_legend_box()
# method.
self._legend_box = None
if isinstance(parent,Axes):
self.isaxes = True
self.set_figure(parent.figure)
elif isinstance(parent,Figure):
self.isaxes = False
self.set_figure(parent)
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0,'best']:
loc = 'upper right'
if is_string_like(loc):
if loc not in self.codes:
if self.isaxes:
warnings.warn('Unrecognized location "%s". Falling back on "best"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.keys())))
loc = 0
else:
warnings.warn('Unrecognized location "%s". Falling back on "upper right"; '
'valid locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes.keys())))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. '
'Falling back on "upper right".')
loc = 1
self._loc = loc
self._mode = mode
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.fontsize,
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
self.legendPatch.set_boxstyle("round",pad=0, #self.borderpad,
rounding_size=0.2)
self._set_artist_props(self.legendPatch)
self._drawFrame = True
# populate the legend_box with legend items.
self._init_legend_box(handles, labels)
self._legend_box.set_figure(self.figure)