本文整理汇总了Python中matplotlib.transforms.Bbox类的典型用法代码示例。如果您正苦于以下问题:Python Bbox类的具体用法?Python Bbox怎么用?Python Bbox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Bbox类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find_best_position
def _find_best_position(self, width, height, renderer, consider=None):
"""
Determine the best location to place the legend.
`consider` is a list of (x, y) pairs to consider as a potential
lower-left corner of the legend. All are display coords.
"""
assert self.isaxes # should always hold because function is only called internally
verts, bboxes, lines = self._auto_legend_data()
bbox = Bbox.from_bounds(0, 0, width, height)
consider = [self._get_anchored_bbox(x, bbox, self.get_bbox_to_anchor(),
renderer) for x in range(1, len(self.codes))]
candidates = []
for l, b in consider:
legendBox = Bbox.from_bounds(l, b, width, height)
badness = 0
badness = legendBox.count_contains(verts)
badness += legendBox.count_overlaps(bboxes)
for line in lines:
if line.intersects_bbox(legendBox):
badness += 1
ox, oy = l, b
if badness == 0:
return ox, oy
candidates.append((badness, (l, b)))
minCandidate = candidates[0]
for candidate in candidates:
if candidate[0] < minCandidate[0]:
minCandidate = candidate
ox, oy = minCandidate[1]
return ox, oy
示例2: get_tight_bbox
def get_tight_bbox(fig, bbox_extra_artists=[], pad=None):
"""
Compute a tight bounding box around all the artists in the figure.
"""
renderer = fig.canvas.get_renderer()
bbox_inches = fig.get_tightbbox(renderer)
bbox_artists = bbox_extra_artists[:]
bbox_artists += fig.get_default_bbox_extra_artists()
bbox_filtered = []
for a in bbox_artists:
bbox = a.get_window_extent(renderer)
if isinstance(bbox, tuple):
continue
if a.get_clip_on():
clip_box = a.get_clip_box()
if clip_box is not None:
bbox = Bbox.intersection(bbox, clip_box)
clip_path = a.get_clip_path()
if clip_path is not None and bbox is not None:
clip_path = clip_path.get_fully_transformed_path()
bbox = Bbox.intersection(bbox,
clip_path.get_extents())
if bbox is not None and (bbox.width != 0 or
bbox.height != 0):
bbox_filtered.append(bbox)
if bbox_filtered:
_bbox = Bbox.union(bbox_filtered)
trans = Affine2D().scale(1.0 / fig.dpi)
bbox_extra = TransformedBbox(_bbox, trans)
bbox_inches = Bbox.union([bbox_inches, bbox_extra])
return bbox_inches.padded(pad) if pad else bbox_inches
示例3: adjust_bbox_pdf
def adjust_bbox_pdf(fig, bbox_inches):
"""
adjust_bbox for pdf & eps format
"""
if fig._cachedRenderer.__class__.__name__ == "RendererPgf":
tr = Affine2D().scale(fig.dpi)
f = 1.
else:
tr = Affine2D().scale(72)
f = 72. / fig.dpi
_bbox = TransformedBbox(bbox_inches, tr)
fig.bbox_inches = Bbox.from_bounds(0, 0,
bbox_inches.width,
bbox_inches.height)
x0, y0 = _bbox.x0, _bbox.y0
w1, h1 = fig.bbox.width * f, fig.bbox.height * f
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0,
w1, h1)
fig.transFigure.invalidate()
fig.bbox = TransformedBbox(fig.bbox_inches, tr)
fig.patch.set_bounds(x0 / w1, y0 / h1,
fig.bbox.width / w1, fig.bbox.height / h1)
示例4: _find_best_position
def _find_best_position(self, width, height, renderer, consider=None):
"""
Determine the best location to place the legend.
`consider` is a list of (x, y) pairs to consider as a potential
lower-left corner of the legend. All are display coords.
"""
# should always hold because function is only called internally
assert self.isaxes
verts, bboxes, lines, offsets = self._auto_legend_data()
bbox = Bbox.from_bounds(0, 0, width, height)
if consider is None:
consider = [self._get_anchored_bbox(x, bbox,
self.get_bbox_to_anchor(),
renderer)
for x in range(1, len(self.codes))]
# tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y()
candidates = []
for l, b in consider:
legendBox = Bbox.from_bounds(l, b, width, height)
badness = 0
# XXX TODO: If markers are present, it would be good to
# take their into account when checking vertex overlaps in
# the next line.
badness = legendBox.count_contains(verts)
badness += legendBox.count_contains(offsets)
badness += legendBox.count_overlaps(bboxes)
for line in lines:
# FIXME: the following line is ill-suited for lines
# that 'spiral' around the center, because the bbox
# may intersect with the legend even if the line
# itself doesn't. One solution would be to break up
# the line into its straight-segment components, but
# this may (or may not) result in a significant
# slowdown if lines with many vertices are present.
if line.intersects_bbox(legendBox):
badness += 1
ox, oy = l, b
if badness == 0:
return ox, oy
candidates.append((badness, (l, b)))
# rather than use min() or list.sort(), do this so that we are assured
# that in the case of two equal badnesses, the one first considered is
# returned.
# NOTE: list.sort() is stable.But leave as it is for now. -JJL
minCandidate = candidates[0]
for candidate in candidates:
if candidate[0] < minCandidate[0]:
minCandidate = candidate
ox, oy = minCandidate[1]
return ox, oy
示例5: draw_plot
def draw_plot(self):
if self._doRePlot:
self._resizeCreateContent()
if self.background is None:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.foo += 1
#self.y = numpy.cos(numpy.arange(0.0,1.0,0.1)+self.foo*0.1)
# Optimization on the blitting: we compute the box where the changes happen
changes_box = None
for i in range(len(self.lines)):
data=self.channels[i].getNext()
if len(data[1])>0:
if self.autolim:
print self.autolim[0], data[1], self.autolim[1]
self.autolim = [ min(self.autolim[0], min(data[1])), \
max(self.autolim[1], max(data[1])) ]
else:
self.autolim = [ min(data[1]), min(data[1]) ]
if changes_box is None:
changes_box = Bbox.unit()
print '>>>>>>>>'
print data[0], data[1]
changes_box.update_from_data(numpy.array(data[0]), \
numpy.array(data[1]), ignore=changes_box.is_unit())
if not self._doRePlot and len(data[0]) > 0 :
end = data[0][-1]
if end > self.begin+self.span:
self.begin += self.span
self._doRePlot = True
print 'do replot'
self.lines[i].set_data(data[0], data[1])
else:
self.lines[i].set_data([], [])
if not changes_box:
return
#self.canvas.restore_region(self.background)
for line in self.lines:
self.ax.draw_artist(line)
#print line.get_transform()
tr = line.get_transform()
changes_box_inframe = changes_box.transformed(tr)
box_padding = 5
(x,y,l,w) = changes_box_inframe.bounds
changes_box_inframe = Bbox.from_bounds(x-box_padding, \
y-box_padding, l+2*box_padding, w+2*box_padding)
#print
t0 = time.time()
self.canvas.blit(None)
#self.canvas.blit(changes_box_inframe)
self.blit_time += time.time() - t0
示例6: _calculate_bbox
def _calculate_bbox(self):
r = self.renderer
bboxes = self.xaxis.get_window_extent(r), self.yaxis.get_window_extent(r), self.subplot.bbox
all_bbox = Bbox.union(bboxes)
(x0, y0), (x1, y1) = all_bbox.get_points()
w = x1 - x0
h = y1 - y0
all_bbox = Bbox.from_bounds(x0, y0, w * 1.02, h * 1.02)
return all_bbox
示例7: plotIToEBrokenAxis
def plotIToEBrokenAxis(sp, gIdx, neuronIdx, trialNum=0, axBoundaries=None,
axesProportions=(0.5, 0.5), bottomLimits=None,
topLimits=None, **kw):
if axBoundaries is None:
axBoundaries = [0, 0, 1, 1]
left, bottom, right, top = axBoundaries
title = kw.pop('title', 'E cell')
fig = kw.pop('fig', plt.gcf())
h = top - bottom
w = right - left
hBottom = h*axesProportions[0]
hTop = h*axesProportions[1]
axBottom = fig.add_axes(Bbox.from_extents(left, bottom, right, bottom +
hBottom))
axTop = fig.add_axes(Bbox.from_extents(left, top - hTop, right, top),
sharex=axBottom)
_, gI = aggr.computeYX(sp, iterList)
M = sp[0][gIdx][trialNum].data['g_EI']
conns = M[neuronIdx, :]
pconn.plotConnHistogram(conns, title=title, ax=axBottom, **kw)
kw['ylabel'] = ''
pconn.plotConnHistogram(conns, title=title, ax=axTop, **kw)
annG = gI[0, gIdx]
if annG - int(annG) == 0:
annG = int(annG)
#ann = '$g_I$ = {0} nS'.format(annG)
#fig.text(left+0.95*w, bottom+0.9*h, ann, ha='right', va='bottom',
# fontsize='x-small')
axBottom.set_xlim([0, annG])
axBottom.set_xticks([0, annG])
axBottom.xaxis.set_ticklabels([0, '$g_I$'])
axBottom.set_ylim(bottomLimits)
axBottom.set_yticks(bottomLimits)
axBottom.yaxis.set_minor_locator(ti.NullLocator())
axTop.set_ylim(topLimits)
axTop.set_yticks([topLimits[1]])
axTop.xaxis.set_visible(False)
axTop.spines['bottom'].set_visible(False)
divLen = 0.07
d = .015
kwargs = dict(transform=fig.transFigure, color='k', clip_on=False)
axBottom.plot((left-divLen*w, left+divLen*w), (bottom+hBottom + d,
bottom+hBottom - d),
**kwargs)
axTop.plot((left-divLen*w, left+divLen*w), (top-hTop + d, top-hTop - d),
**kwargs)
return axBottom, axTop
示例8: zoom_effect
def zoom_effect(ax_zoomed, ax_origin, xlims = None, orientation='below', **kwargs):
"""
ax_zoomed : zoomed axes
ax_origin: the main axes
(xmin,xmax) : the limits of the colored area in both plot axes.
connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
be marked. The keywords parameters will be used ti create
patches.
"""
if xlims is None:
tt = ax_zoomed.transScale + (ax_zoomed.transLimits + ax_origin.transAxes)
transform = blended_transform_factory(ax_origin.transData, tt)
bbox_zoomed=ax_zoomed.bbox
bbox_origin=TransformedBbox(ax_zoomed.viewLim, transform)
else:
transform_zoomed=blended_transform_factory(ax_zoomed.transData, ax_zoomed.transAxes)
transform_origin=blended_transform_factory(ax_origin.transData, ax_origin.transAxes)
bbox_zoomed=TransformedBbox(Bbox.from_extents(xlims[0], 0, xlims[1], 1), transform_zoomed)
bbox_origin=TransformedBbox(Bbox.from_extents(xlims[0], 0, xlims[1], 1), transform_origin)
prop_patches = kwargs.copy()
prop_patches["ec"] = "none"
prop_patches["alpha"] = 0.2
if orientation=='below':
loc1a=2
loc2a=3
loc1b=1
loc2b=4
elif orientation=='above':
loc1a=3
loc2a=2
loc1b=4
loc2b=1
else:
raise Exception("orientation '%s' not recognized" % orientation)
c1, c2, bbox_zoomed_patch, bbox_origin_patch, p = \
connect_bbox(bbox_zoomed, bbox_origin,
loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,
prop_lines=kwargs, prop_patches=prop_patches)
ax_zoomed.add_patch(bbox_zoomed_patch)
ax_origin.add_patch(bbox_origin_patch)
ax_origin.add_patch(c1)
ax_origin.add_patch(c2)
ax_origin.add_patch(p)
return c1, c2, bbox_zoomed_patch, bbox_origin_patch, p
示例9: connect_bbox
def connect_bbox(bbox1, bbox2, loc1, loc2=None):
"""
Helper function to obtain a Path from one bbox to another.
Parameters
----------
bbox1, bbox2 : `matplotlib.transforms.Bbox`
Bounding boxes to connect.
loc1 : {1, 2, 3, 4}
Corner of *bbox1* to use. Valid values are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4
loc2 : {1, 2, 3, 4}, optional
Corner of *bbox2* to use. If None, defaults to *loc1*.
Valid values are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4
Returns
-------
path : `matplotlib.path.Path`
A line segment from the *loc1* corner of *bbox1* to the *loc2*
corner of *bbox2*.
"""
if isinstance(bbox1, Rectangle):
transform = bbox1.get_transform()
bbox1 = Bbox.from_bounds(0, 0, 1, 1)
bbox1 = TransformedBbox(bbox1, transform)
if isinstance(bbox2, Rectangle):
transform = bbox2.get_transform()
bbox2 = Bbox.from_bounds(0, 0, 1, 1)
bbox2 = TransformedBbox(bbox2, transform)
if loc2 is None:
loc2 = loc1
x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)
verts = [[x1, y1], [x2, y2]]
codes = [Path.MOVETO, Path.LINETO]
return Path(verts, codes)
示例10: plot
def plot(self, *args, **kwargs):
ps = self.env.ps
output_dir = self.config['output_dir']
rateLeft = rasterLeft
rateBottom = 0.2
rateRight = rasterRight
rateTop = self.myc['rateTop']
for idx, noise_sigma in enumerate(ps.noise_sigmas):
# E cells
fig = self._get_final_fig(self.myc['fig_size'])
ax = fig.add_axes(Bbox.from_extents(rateLeft, rateBottom, rateRight,
rateTop))
kw = {}
if (idx != 0):
kw['ylabel'] = ''
rasters.plotAvgFiringRate(ps.bumpGamma[idx],
spaceType='bump',
noise_sigma=ps.noise_sigmas[idx],
popType='E',
r=rasterRC[idx][0], c=rasterRC[idx][1],
ylabelPos=self.myc['ylabelPos'],
color='red',
tLimits=tLimits,
ax=ax, **kw)
fname = output_dir + "/bumps_rate_e{0}.pdf".format(noise_sigma)
fig.savefig(fname, dpi=300, transparent=transparent)
plt.close()
# I cells
fig = self._get_final_fig(self.myc['fig_size'])
ax = fig.add_axes(Bbox.from_extents(rateLeft, rateBottom, rateRight,
rateTop))
kw = {}
if (idx != 0):
kw['ylabel'] = ''
rasters.plotAvgFiringRate(ps.bumpGamma[idx],
spaceType='bump',
noise_sigma=ps.noise_sigmas[idx],
popType='I',
r=rasterRC[idx][0], c=rasterRC[idx][1],
ylabelPos=self.myc['ylabelPos'],
color='blue',
tLimits=tLimits,
ax=ax, **kw)
fname = output_dir + "/bumps_rate_i{0}.pdf".format(noise_sigma)
fig.savefig(fname, dpi=300, transparent=transparent)
plt.close()
示例11: plot
def plot(self, *args, **kwargs):
ps = self.env.ps
output_dir = self.config['output_dir']
transparent = self.myc['transparent']
for idx, noise_sigma in enumerate(ps.noise_sigmas):
# E cells
fig = self._get_final_fig(self.myc['fig_size'])
l, b, r, t = self.myc['bbox']
ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
kw = {}
if (idx != 0):
kw['ylabel'] = ''
rasters.plotAvgFiringRate(ps.v[idx],
spaceType='velocity',
noise_sigma=noise_sigma,
popType='E',
r=rasterRC[idx][0], c=rasterRC[idx][1],
color='red',
ylabelPos=self.config['vel_rasters']['ylabelPos'],
tLimits=self.config['vel_rasters']['tLimits'],
trialNum=self.config['vel_rasters']['trialNum'],
sigmaTitle=False,
ax=ax, **kw)
fname = output_dir + "/velocity_rate_e{0}.pdf".format(noise_sigma)
fig.savefig(fname, dpi=300, transparent=transparent)
plt.close()
# I cells
fig = self._get_final_fig(self.myc['fig_size'])
ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
kw = {}
if (idx != 0):
kw['ylabel'] = ''
rasters.plotAvgFiringRate(ps.v[idx],
spaceType='velocity',
noise_sigma=noise_sigma,
popType='I',
r=rasterRC[idx][0], c=rasterRC[idx][1],
color='blue',
ylabelPos=self.config['vel_rasters']['ylabelPos'],
tLimits=self.config['vel_rasters']['tLimits'],
trialNum=self.config['vel_rasters']['trialNum'],
sigmaTitle=False,
ax=ax, **kw)
fname = output_dir + "/velocity_rate_i{0}.pdf".format(noise_sigma)
fig.savefig(fname, dpi=300, transparent=transparent)
plt.close()
示例12: _compute_bbox
def _compute_bbox(self, fig, kw):
"""
Compute the tight bounding box for each figure once, reducing
number of required canvas draw calls from N*2 to N+1 as a
function of the number of frames.
Tight bounding box computing code here mirrors:
matplotlib.backend_bases.FigureCanvasBase.print_figure
as it hasn't been factored out as a function.
"""
fig_id = id(fig)
if kw['bbox_inches'] == 'tight':
if not fig_id in MPLRenderer.drawn:
fig.set_dpi(self.dpi)
fig.canvas.draw()
renderer = fig._cachedRenderer
bbox_inches = fig.get_tightbbox(renderer)
bbox_artists = kw.pop("bbox_extra_artists", [])
bbox_artists += fig.get_default_bbox_extra_artists()
bbox_filtered = []
for a in bbox_artists:
bbox = a.get_window_extent(renderer)
if isinstance(bbox, tuple):
continue
if a.get_clip_on():
clip_box = a.get_clip_box()
if clip_box is not None:
bbox = Bbox.intersection(bbox, clip_box)
clip_path = a.get_clip_path()
if clip_path is not None and bbox is not None:
clip_path = clip_path.get_fully_transformed_path()
bbox = Bbox.intersection(bbox,
clip_path.get_extents())
if bbox is not None and (bbox.width != 0 or
bbox.height != 0):
bbox_filtered.append(bbox)
if bbox_filtered:
_bbox = Bbox.union(bbox_filtered)
trans = Affine2D().scale(1.0 / self.dpi)
bbox_extra = TransformedBbox(_bbox, trans)
bbox_inches = Bbox.union([bbox_inches, bbox_extra])
pad = plt.rcParams['savefig.pad_inches']
bbox_inches = bbox_inches.padded(pad)
MPLRenderer.drawn[fig_id] = bbox_inches
kw['bbox_inches'] = bbox_inches
else:
kw['bbox_inches'] = MPLRenderer.drawn[fig_id]
return kw
示例13: _find_best_position
def _find_best_position(self, width, height, renderer, consider=None):
"""
Determine the best location to place the legend.
`consider` is a list of (x, y) pairs to consider as a potential
lower-left corner of the legend. All are display coords.
"""
# should always hold because function is only called internally
assert self.isaxes
verts, bboxes, lines = self._auto_legend_data()
bbox = Bbox.from_bounds(0, 0, width, height)
consider = [self._get_anchored_bbox(x, bbox, self.get_bbox_to_anchor(),
renderer)
for x
in range(1, len(self.codes))]
#tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y()
candidates = []
for l, b in consider:
legendBox = Bbox.from_bounds(l, b, width, height)
badness = 0
badness = legendBox.count_contains(verts)
badness += legendBox.count_overlaps(bboxes)
for line in lines:
if line.intersects_bbox(legendBox):
badness += 1
ox, oy = l, b
if badness == 0:
return ox, oy
candidates.append((badness, (l, b)))
# rather than use min() or list.sort(), do this so that we are assured
# that in the case of two equal badnesses, the one first considered is
# returned.
# NOTE: list.sort() is stable.But leave as it is for now. -JJL
minCandidate = candidates[0]
for candidate in candidates:
if candidate[0] < minCandidate[0]:
minCandidate = candidate
ox, oy = minCandidate[1]
return ox, oy
示例14: test_text_with_arrow_annotation_get_window_extent
def test_text_with_arrow_annotation_get_window_extent():
headwidth = 21
fig, ax = plt.subplots(dpi=100)
txt = ax.text(s='test', x=0, y=0)
ann = ax.annotate(
'test',
xy=(0.0, 50.0),
xytext=(50.0, 50.0), xycoords='figure pixels',
arrowprops={
'facecolor': 'black', 'width': 2,
'headwidth': headwidth, 'shrink': 0.0})
plt.draw()
renderer = fig.canvas.renderer
# bounding box of text
text_bbox = txt.get_window_extent(renderer=renderer)
# bounding box of annotation (text + arrow)
bbox = ann.get_window_extent(renderer=renderer)
# bounding box of arrow
arrow_bbox = ann.arrow.get_window_extent(renderer)
# bounding box of annotation text
ann_txt_bbox = Text.get_window_extent(ann)
# make sure annotation with in 50 px wider than
# just the text
eq_(bbox.width, text_bbox.width + 50.0)
# make sure the annotation text bounding box is same size
# as the bounding box of the same string as a Text object
eq_(ann_txt_bbox.height, text_bbox.height)
eq_(ann_txt_bbox.width, text_bbox.width)
# compute the expected bounding box of arrow + text
expected_bbox = Bbox.union([ann_txt_bbox, arrow_bbox])
assert_almost_equal(bbox.height, expected_bbox.height)
示例15: _set_lim_and_transforms
def _set_lim_and_transforms(self):
PolarAxes._set_lim_and_transforms(self)
try:
theta_position = self._theta_label1_position
except AttributeError:
theta_position = self.get_theta_offset()
self.transProjection = self.GlobeCrossSectionTransform()
self.transData = (
self.transScale +
self.transProjection +
(self.transProjectionAffine + self.transAxes))
self._xaxis_transform = (
self.transProjection +
self.PolarAffine(IdentityTransform(), Bbox.unit()) +
self.transAxes)
self._xaxis_text1_transform = (
theta_position +
self._xaxis_transform)
self._yaxis_transform = (
Affine2D().scale(num.pi * 2.0, 1.0) +
self.transData)
try:
rlp = getattr(self, '_r_label1_position')
except AttributeError:
rlp = getattr(self, '_r_label_position')
self._yaxis_text1_transform = (
rlp +
Affine2D().scale(1.0 / 360.0, 1.0) +
self._yaxis_transform)