本文整理汇总了Python中matplotlib.patches方法的典型用法代码示例。如果您正苦于以下问题:Python matplotlib.patches方法的具体用法?Python matplotlib.patches怎么用?Python matplotlib.patches使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib
的用法示例。
在下文中一共展示了matplotlib.patches方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: construct_ball_trajectory
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
# https://matplotlib.org/examples/color/colormaps_reference.html
patches = []
for pos in var:
if shape == 'c':
patches.append(mpatches.Circle(pos, r))
elif shape == 'r':
patches.append(mpatches.RegularPolygon(pos, 4, r))
elif shape == 's':
patches.append(mpatches.RegularPolygon(pos, 6, r))
colors = np.linspace(start_color, .9, len(patches))
collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
collection.set_array(np.array(colors))
collection.set_clim(0, 1)
return collection
示例2: plot_filled_polygons
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def plot_filled_polygons(self,polygons, facecolour='green', edgecolour='black', linewidth=1, alpha=0.5):
"""
This function plots a series of shapely polygons but fills them in
Args:
ax_list: list of axes
polygons: list of shapely polygons
Author: FJC
"""
from shapely.geometry import Polygon
from descartes import PolygonPatch
from matplotlib.collections import PatchCollection
print('Plotting the polygons...')
#patches = []
for key, poly in polygons.items():
this_patch = PolygonPatch(poly, fc=facecolour, ec=edgecolour, alpha=alpha)
self.ax_list[0].add_patch(this_patch)
示例3: read_JSON_file
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def read_JSON_file(f):
with open(f, 'r') as g:
d = json.loads(g.read())
img_paths = [x['file_name'] for x in d['images']]
rects = [{'bbox': x['segmentation'][0], 'class': x['category_id'], 'image_id': x['image_id']} for x in d['annotations']]
annotations = defaultdict(list)
for rect in rects:
r = rect['bbox']
x0, y0 = min(r[0], r[2], r[4], r[6]), min(r[1], r[3], r[5], r[7])
x1, y1 = max(r[0], r[2], r[4], r[6]), max(r[1], r[3], r[5], r[7])
r = patches.Rectangle((x0,y0),x1-x0,y1-y0,linewidth=1,edgecolor='g',facecolor='g', alpha=0.4)
annotations[img_paths[rect['image_id']]].append({'bbox': r, 'cls': d['classes'][rect['class']-1]})
return d['classes'], img_paths, annotations
示例4: add_patch
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def add_patch(self, p):
"""
Add a :class:`~matplotlib.patches.Patch` *p* to the list of
axes patches; the clipbox will be set to the Axes clipping
box. If the transform is not set, it will be set to
:attr:`transData`.
Returns the patch.
"""
self._set_artist_props(p)
if p.get_clip_path() is None:
p.set_clip_path(self.patch)
self._update_patch_limits(p)
self.patches.append(p)
p._remove_method = lambda h: self.patches.remove(h)
return p
示例5: _update_patch_limits
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def _update_patch_limits(self, patch):
"""update the data limits for patch *p*"""
# hist can add zero height Rectangles, which is useful to keep
# the bins, counts and patches lined up, but it throws off log
# scaling. We'll ignore rects with zero height or width in
# the auto-scaling
# cannot check for '==0' since unitized data may not compare to zero
# issue #2150 - we update the limits if patch has non zero width
# or height.
if (isinstance(patch, mpatches.Rectangle) and
((not patch.get_width()) and (not patch.get_height()))):
return
vertices = patch.get_path().vertices
if vertices.size > 0:
xys = patch.get_patch_transform().transform(vertices)
if patch.get_data_transform() != self.transData:
patch_to_data = (patch.get_data_transform() -
self.transData)
xys = patch_to_data.transform(xys)
updatex, updatey = patch.get_transform().\
contains_branch_seperately(self.transData)
self.update_datalim(xys, updatex=updatex,
updatey=updatey)
示例6: relim
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def relim(self, visible_only=False):
"""
Recompute the data limits based on current artists. If you want to
exclude invisible artists from the calculation, set
``visible_only=True``
At present, :class:`~matplotlib.collections.Collection`
instances are not supported.
"""
# Collections are deliberately not supported (yet); see
# the TODO note in artists.py.
self.dataLim.ignore(True)
self.dataLim.set_points(mtransforms.Bbox.null().get_points())
self.ignore_existing_data_limits = True
for line in self.lines:
if not visible_only or line.get_visible():
self._update_line_limits(line)
for p in self.patches:
if not visible_only or p.get_visible():
self._update_patch_limits(p)
示例7: test_arc_ellipse
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def test_arc_ellipse():
from matplotlib import patches
xcenter, ycenter = 0.38, 0.52
width, height = 1e-1, 3e-1
angle = -30
theta = np.arange(0.0, 360.0, 1.0)*np.pi/180.0
x = width/2. * np.cos(theta)
y = height/2. * np.sin(theta)
rtheta = angle*np.pi/180.
R = np.array([
[np.cos(rtheta), -np.sin(rtheta)],
[np.sin(rtheta), np.cos(rtheta)],
])
x, y = np.dot(R, np.array([x, y]))
x += xcenter
y += ycenter
fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)
e1 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e1)
ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e2)
示例8: add_patch
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def add_patch(self, p):
"""
Add a :class:`~matplotlib.patches.Patch` *p* to the list of
axes patches; the clipbox will be set to the Axes clipping
box. If the transform is not set, it will be set to
:attr:`transData`.
Returns the patch.
"""
self._set_artist_props(p)
if p.get_clip_path() is None:
p.set_clip_path(self.patch)
self._update_patch_limits(p)
self.patches.append(p)
p._remove_method = self.patches.remove
return p
示例9: _update_patch_limits
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def _update_patch_limits(self, patch):
"""update the data limits for patch *p*"""
# hist can add zero height Rectangles, which is useful to keep
# the bins, counts and patches lined up, but it throws off log
# scaling. We'll ignore rects with zero height or width in
# the auto-scaling
# cannot check for '==0' since unitized data may not compare to zero
# issue #2150 - we update the limits if patch has non zero width
# or height.
if (isinstance(patch, mpatches.Rectangle) and
((not patch.get_width()) and (not patch.get_height()))):
return
vertices = patch.get_path().vertices
if vertices.size > 0:
xys = patch.get_patch_transform().transform(vertices)
if patch.get_data_transform() != self.transData:
patch_to_data = (patch.get_data_transform() -
self.transData)
xys = patch_to_data.transform(xys)
updatex, updatey = patch.get_transform().\
contains_branch_seperately(self.transData)
self.update_datalim(xys, updatex=updatex,
updatey=updatey)
示例10: get_children
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def get_children(self):
"""return a list of child artists"""
children = []
children.extend(self.collections)
children.extend(self.patches)
children.extend(self.lines)
children.extend(self.texts)
children.extend(self.artists)
children.extend(self.spines.values())
children.append(self.xaxis)
children.append(self.yaxis)
children.append(self.title)
children.append(self._left_title)
children.append(self._right_title)
children.extend(self.tables)
children.extend(self.images)
children.extend(self.child_axes)
if self.legend_ is not None:
children.append(self.legend_)
children.append(self.patch)
return children
示例11: test_arc_angles
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def test_arc_angles():
from matplotlib import patches
# Ellipse parameters
w = 2
h = 1
centre = (0.2, 0.5)
scale = 2
fig, axs = plt.subplots(3, 3)
for i, ax in enumerate(axs.flat):
theta2 = i * 360 / 9
theta1 = theta2 - 45
ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3))
ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
# Straight lines intersecting start and end of arc
ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
centre[0],
scale * np.cos(np.deg2rad(theta2)) + centre[0]],
[scale * np.sin(np.deg2rad(theta1)) + centre[1],
centre[1],
scale * np.sin(np.deg2rad(theta2)) + centre[1]])
ax.set_xlim(-scale, scale)
ax.set_ylim(-scale, scale)
# This looks the same, but it triggers a different code path when it
# gets large enough.
w *= 10
h *= 10
centre = (centre[0] * 10, centre[1] * 10)
scale *= 10
示例12: test_arc_ellipse
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def test_arc_ellipse():
from matplotlib import patches
xcenter, ycenter = 0.38, 0.52
width, height = 1e-1, 3e-1
angle = -30
theta = np.deg2rad(np.arange(360))
x = width / 2. * np.cos(theta)
y = height / 2. * np.sin(theta)
rtheta = np.deg2rad(angle)
R = np.array([
[np.cos(rtheta), -np.sin(rtheta)],
[np.sin(rtheta), np.cos(rtheta)]])
x, y = np.dot(R, np.array([x, y]))
x += xcenter
y += ycenter
fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow',
linewidth=1, zorder=1)
e1 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e1)
ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e2)
示例13: test_hist_step_filled
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def test_hist_step_filled():
np.random.seed(0)
x = np.random.randn(1000, 3)
n_bins = 10
kwargs = [{'fill': True}, {'fill': False}, {'fill': None}, {}]*2
types = ['step']*4+['stepfilled']*4
fig, axes = plt.subplots(nrows=2, ncols=4)
axes = axes.flatten()
for kg, _type, ax in zip(kwargs, types, axes):
ax.hist(x, n_bins, histtype=_type, stacked=True, **kg)
ax.set_title('%s/%s' % (kg, _type))
ax.set_ylim(bottom=-50)
patches = axes[0].patches
assert all(p.get_facecolor() == p.get_edgecolor() for p in patches)
示例14: add_heatmap
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def add_heatmap(self, title, x, tensor, drawbox=None):
assert tensor.dim() == 3
def plot_heatmap(ax, tensor, drawbox=None):
ax.imshow(tensor.detach().cpu().numpy())
ax.invert_yaxis()
ax.label_outer()
if drawbox is not None:
rect = patches.Rectangle((0, 0), *drawbox.tolist(), linewidth=1, edgecolor='b', facecolor='none')
ax.add_patch(rect)
if tensor.size(0) == 1:
fig, ax = plt.subplots()
plot_heatmap(ax, tensor[0], drawbox)
else:
fig, axs = plt.subplots(tensor.size(0), sharex=True)
for i, ax in enumerate(axs):
plot_heatmap(ax, tensor[i], drawbox)
fig.subplots_adjust(hspace=2)
fig.patch.set_color('white')
fig.tight_layout()
self.writer.add_figure(title, fig, x)
示例15: lasso_onselect
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import patches [as 别名]
def lasso_onselect(self, verts):
self.pathlasso = path.Path(verts)
patch = patches.PathPatch(self.pathlasso, fill=True, alpha=.2, edgecolor=None)
self.ax1.add_patch(patch)
self.figure.canvas.draw()
if self.mode == 1 or self.mode == 4 or self.mode == 7:
onslice = 'Z %s' % (self.ind + 1)
elif self.mode == 2 or self.mode == 5 or self.mode == 8:
onslice = 'X %s' % (self.ind + 1)
elif self.mode == 3 or self.mode == 6 or self.mode == 9:
onslice = 'Y %s' % (self.ind + 1)
self.df = pandas.read_csv('Markings/marking_records.csv')
df_size = pandas.DataFrame.count(self.df)
df_rows = df_size['artist']
self.df.loc[df_rows, 'artist'] = patch
plist = np.ndarray.tolist(self.pathlasso.vertices)
plist = ', '.join(str(x) for x in plist)
self.df.loc[df_rows, 'labelshape'] = 'lasso'
self.df.loc[df_rows, 'slice'] = onslice
self.df.loc[df_rows, 'path'] = plist
self.df.loc[df_rows, 'status'] = 0
self.df.to_csv('Markings/marking_records.csv', index=False)