Python matplotlib.patches() Examples
The following are 30
code examples of matplotlib.patches().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example #1
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #2
Source File: _plot.py From spm1d with GNU General Public License v3.0 | 6 votes |
def plot_cloud(self, Y, facecolor='0.8', edgecolor='0.8', alpha=0.5, edgelinestyle='-'): ### create patches: y0,y1 = Y x,y0,y1 = self.x.tolist(), y0.tolist(), y1.tolist() x = [x[0]] + x + [x[-1]] y0 = [y0[0]] + y0 + [y0[-1]] y1 = [y1[0]] + y1 + [y1[-1]] y1.reverse() ### concatenate: x1 = np.copy(x).tolist() x1.reverse() x,y = x + x1, y0 + y1 patches = PatchCollection( [ Polygon( np.array([x,y]).T ) ], edgecolors=None) ### plot: self.ax.add_collection(patches) pyplot.setp(patches, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, linestyle=edgelinestyle) return patches
Example #3
Source File: PlottingRaster.py From LSDMappingTools with MIT License | 6 votes |
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)
Example #4
Source File: _base.py From ImageFusion with MIT License | 6 votes |
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)
Example #5
Source File: _base.py From ImageFusion with MIT License | 6 votes |
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)
Example #6
Source File: segment_bbox_only.py From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 | 6 votes |
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
Example #7
Source File: _base.py From ImageFusion with MIT License | 6 votes |
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
Example #8
Source File: _base.py From neural-network-animation with MIT License | 6 votes |
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
Example #9
Source File: _base.py From neural-network-animation with MIT License | 6 votes |
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)
Example #10
Source File: test_axes.py From neural-network-animation with MIT License | 6 votes |
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)
Example #11
Source File: canvas.py From CNNArt with Apache License 2.0 | 6 votes |
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)
Example #12
Source File: _base.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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
Example #13
Source File: _base.py From neural-network-animation with MIT License | 6 votes |
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)
Example #14
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #15
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #16
Source File: plotting.py From kvae with MIT License | 6 votes |
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
Example #17
Source File: _base.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #18
Source File: _base.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #19
Source File: _base.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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
Example #20
Source File: _base.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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)
Example #21
Source File: logger.py From pytorch-asr with GNU General Public License v3.0 | 6 votes |
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)
Example #22
Source File: box_util.py From Geo-CNN with Apache License 2.0 | 5 votes |
def plot_polys(plist,scale=500.0): fig, ax = plt.subplots() patches = [] for p in plist: poly = Polygon(np.array(p)/scale, True) patches.append(poly)
Example #23
Source File: labeling_toolbox.py From DeepLabCut with GNU Lesser General Public License v3.0 | 5 votes |
def plot(self, img): """ Plots and call auxfun_drag class for moving and removing points. """ self.drs = [] self.updatedCoords = [] for bpindex, bp in enumerate(self.bodyparts): color = self.colormap(self.norm(self.colorIndex[bpindex])) self.points = [ self.dataFrame[self.scorer][bp]["x"].values[self.iter], self.dataFrame[self.scorer][bp]["y"].values[self.iter], ] circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc=color, alpha=self.alpha, ) ] self.axes.add_patch(circle[0]) self.dr = auxfun_drag_label.DraggablePoint( circle[0], self.bodyparts[bpindex] ) self.dr.connect() self.dr.coords = MainFrame.getLabels(self, self.iter)[bpindex] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) if np.isnan(self.points)[0] == False: self.buttonCounter.append(bpindex) self.figure.canvas.draw() return self.buttonCounter
Example #24
Source File: util.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def polygons_to_path_patches(element): """ Converts Polygons into list of lists of matplotlib.patches.PathPatch objects including any specified holes. Each list represents one (multi-)polygon. """ paths = element.split(datatype='array', dimensions=element.kdims) has_holes = isinstance(element, Polygons) and element.interface.has_holes(element) holes = element.interface.holes(element) if has_holes else None mpl_paths = [] for i, path in enumerate(paths): splits = np.where(np.isnan(path[:, :2].astype('float')).sum(axis=1))[0] arrays = np.split(path, splits+1) if len(splits) else [path] subpath = [] for j, array in enumerate(arrays): if j != (len(arrays)-1): array = array[:-1] if (array[0] != array[-1]).any(): array = np.append(array, array[:1], axis=0) interiors = [] for interior in (holes[i][j] if has_holes else []): if (interior[0] != interior[-1]).any(): interior = np.append(interior, interior[:1], axis=0) interiors.append(interior) vertices = np.concatenate([array]+interiors) codes = np.concatenate([ring_coding(array)]+ [ring_coding(h) for h in interiors]) subpath.append(PathPatch(Path(vertices, codes))) mpl_paths.append(subpath) return mpl_paths
Example #25
Source File: blockConverters.py From armi with Apache License 2.0 | 5 votes |
def plotConvertedBlock(self): """Render an image of the converted block.""" figName = self._sourceBlock.name + "_1D_cylinder.svg" runLog.extra( "Plotting equivalent cylindrical block of {} as {}".format( self._sourceBlock, figName ) ) fig, ax = plt.subplots() fig.patch.set_visible(False) ax.patch.set_visible(False) ax.axis("off") patches = [] colors = [] for circleComp in self.convertedBlock: innerR, outerR = ( circleComp.getDimension("id") / 2.0, circleComp.getDimension("od") / 2.0, ) runLog.debug( "Plotting {:40s} with {:10.3f} {:10.3f} ".format( circleComp, innerR, outerR ) ) circle = Wedge((0.0, 0.0), outerR, 0, 360.0, outerR - innerR) patches.append(circle) colors.append(circleComp.density()) colorMap = matplotlib.cm p = PatchCollection(patches, alpha=1.0, linewidths=0.1, cmap=colorMap.rainbow) p.set_array(numpy.array(colors)) p.set_clim(0, 20) ax.add_collection(p) ax.autoscale_view(True, True, True) plt.savefig(figName) return figName
Example #26
Source File: map.py From skymapper with MIT License | 5 votes |
def __init__(self, proj, ax=None, interactive=True, **kwargs): """Create Map with a given projection. A `skymapper.Map` holds a predefined projection and `matplotlib` axes and figures to enable plotting on the sphere with proper labeling and inter/extrapolations. It also allows for interactive and exploratory work by updateing the maps after pan/zoom events. Most of the methods are wrappers of `matplotlib` functions by the same names, so that one can mostly interact with a `Map` instance as one would do with a `matplotlib.axes`. For plotting purposes, it is recommended to switch `interactive` off. Args: proj: `skymapper.Projection` instance ax: `matplotlib.axes` instance, will be created otherwise interactive: if pan/zoom is enabled for map updates **kwargs: styling of the `matplotlib.patches.Polygon` that shows the outline of the map. """ # store arguments to regenerate the map self._config = {'__init__': _parseArgs(locals())} self.proj = proj self._setFigureAx(ax, interactive=interactive) self._resolution = 75 # for graticules self._setEdge(**kwargs) self.ax.relim() self.ax.autoscale_view() self._setFrame()
Example #27
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bar_uint8(): xs = [0, 1, 2, 3] b = plt.bar(np.array(xs, dtype=np.uint8), [2, 3, 4, 5], align="edge") for (patch, x) in zip(b.patches, xs): assert patch.xy[0] == x
Example #28
Source File: multiple_individuals_refinement_toolbox.py From DeepLabCut with GNU Lesser General Public License v3.0 | 5 votes |
def clear_plot(self, event): MainFrame.saveEachImage(self) self.figure.delaxes(self.figure.axes[1]) [p.remove() for p in reversed(self.axes.patches)] self.plot(self.img)
Example #29
Source File: outlier_frame_extraction_toolbox.py From DeepLabCut with GNU Lesser General Public License v3.0 | 5 votes |
def clear_plot(self, event): self.figure.delaxes(self.figure.axes[1]) [p.remove() for p in reversed(self.axes.patches)] self.plot_labels()
Example #30
Source File: pyplot.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def figlegend(*args, **kwargs): """ Place a legend in the figure. *labels* a sequence of strings *handles* a sequence of :class:`~matplotlib.lines.Line2D` or :class:`~matplotlib.patches.Patch` instances *loc* can be a string or an integer specifying the legend location A :class:`matplotlib.legend.Legend` instance is returned. Examples -------- To make a legend from existing artists on every axes:: figlegend() To make a legend for a list of lines and labels:: figlegend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right' ) .. seealso:: :func:`~matplotlib.pyplot.legend` """ return gcf().legend(*args, **kwargs) ## Axes ##