Python matplotlib.collections.PolyCollection() Examples
The following are 30
code examples of matplotlib.collections.PolyCollection().
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.collections
, or try the search function
.
Example #1
Source File: quiver.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def set_offsets(self, xy): """ Set the offsets for the barb polygons. This saves the offsets passed in and actually sets version masked as appropriate for the existing U/V data. *offsets* should be a sequence. Parameters ---------- offsets : sequence of pairs of floats """ self.x = xy[:, 0] self.y = xy[:, 1] x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v) _check_consistent_shapes(x, y, u, v) xy = np.column_stack((x, y)) mcollections.PolyCollection.set_offsets(self, xy) self.stale = True
Example #2
Source File: quiver.py From Computable with MIT License | 6 votes |
def _init(self): if True: # not self._initialized: self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] # Hack: save and restore the Umask _mask = self.Q.Umask self.Q.Umask = ma.nomask self.verts = self.Q._make_verts(np.array([self.U]), np.zeros((1,))) self.Q.Umask = _mask self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = collections.PolyCollection( self.verts, offsets=[(self.X, self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self._initialized = True
Example #3
Source File: convexHull.py From xrt with MIT License | 6 votes |
def plot_in_hull(p, cloud): """ plot relative to `in_hull` for 2d data """ hull = Delaunay(cloud) # plot triangulation poly = PolyCollection(hull.points[hull.vertices], facecolors='grey', edgecolors='grey', alpha=0.1) plt.clf() plt.title('in hull: green, out of hull: red') plt.gca().add_collection(poly) plt.plot(hull.points[:, 0], hull.points[:, 1], 'o', color='grey', alpha=0.2) # plot tested points `p` - green are inside hull, red outside inside = hull.find_simplex(p) >= 0 plt.plot(p[inside, 0], p[inside, 1], 'og') plt.plot(p[~inside, 0], p[~inside, 1], 'or') plt.show()
Example #4
Source File: quiver.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def set_offsets(self, xy): """ Set the offsets for the barb polygons. This saves the offsets passed in and actually sets version masked as appropriate for the existing U/V data. *offsets* should be a sequence. Parameters ---------- offsets : sequence of pairs of floats """ self.x = xy[:, 0] self.y = xy[:, 1] x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v) _check_consistent_shapes(x, y, u, v) xy = np.column_stack((x, y)) mcollections.PolyCollection.set_offsets(self, xy) self.stale = True
Example #5
Source File: quiver.py From matplotlib-4-abaqus with MIT License | 6 votes |
def _init(self): if True: # not self._initialized: self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] # Hack: save and restore the Umask _mask = self.Q.Umask self.Q.Umask = ma.nomask self.verts = self.Q._make_verts(np.array([self.U]), np.zeros((1,))) self.Q.Umask = _mask self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = collections.PolyCollection( self.verts, offsets=[(self.X, self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self._initialized = True
Example #6
Source File: quiver.py From coffeegrindsize with MIT License | 6 votes |
def set_offsets(self, xy): """ Set the offsets for the barb polygons. This saves the offsets passed in and actually sets version masked as appropriate for the existing U/V data. *offsets* should be a sequence. Parameters ---------- offsets : sequence of pairs of floats """ self.x = xy[:, 0] self.y = xy[:, 1] x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v) _check_consistent_shapes(x, y, u, v) xy = np.column_stack((x, y)) mcollections.PolyCollection.set_offsets(self, xy) self.stale = True
Example #7
Source File: axes3d.py From CogAlg with MIT License | 5 votes |
def add_collection3d(self, col, zs=0, zdir='z'): ''' Add a 3D collection object to the plot. 2D collection types are converted to a 3D version by modifying the object and adding z coordinate information. Supported are: - PolyCollection - LineCollection - PatchCollection ''' zvals = np.atleast_1d(zs) zsortval = (np.min(zvals) if zvals.size else 0) # FIXME: arbitrary default # FIXME: use issubclass() (although, then a 3D collection # object would also pass.) Maybe have a collection3d # abstract class to test for and exclude? if type(col) is mcoll.PolyCollection: art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.LineCollection: art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.PatchCollection: art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) super().add_collection(col)
Example #8
Source File: quiver.py From CogAlg with MIT License | 5 votes |
def _init(self): if True: # not self._initialized: if not self.Q._initialized: self.Q._init() self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] # Hack: save and restore the Umask _mask = self.Q.Umask self.Q.Umask = ma.nomask u = self.U * np.cos(np.radians(self.angle)) v = self.U * np.sin(np.radians(self.angle)) angle = self.Q.angles if isinstance(self.Q.angles, str) else 'uv' self.verts = self.Q._make_verts( np.array([u]), np.array([v]), angle) self.Q.Umask = _mask self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = mcollections.PolyCollection( self.verts, offsets=[(self.X, self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self.vector.set_figure(self.get_figure()) self._initialized = True
Example #9
Source File: quiver.py From twitter-stock-recommendation with MIT License | 5 votes |
def _init(self): if True: # not self._initialized: if not self.Q._initialized: self.Q._init() self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] # Hack: save and restore the Umask _mask = self.Q.Umask self.Q.Umask = ma.nomask self.verts = self.Q._make_verts(np.array([self.U]), np.zeros((1,)), self.angle) self.Q.Umask = _mask self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = mcollections.PolyCollection( self.verts, offsets=[(self.X, self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self.vector.set_figure(self.get_figure()) self._initialized = True
Example #10
Source File: test_collections.py From twitter-stock-recommendation with MIT License | 5 votes |
def test_polycollection_close(): from mpl_toolkits.mplot3d import Axes3D vertsQuad = [ [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] fig = plt.figure() ax = Axes3D(fig) colors = ['r', 'g', 'b', 'y', 'k'] zpos = list(range(5)) poly = mcollections.PolyCollection( vertsQuad * len(zpos), linewidth=0.25) poly.set_alpha(0.7) # need to have a z-value for *each* polygon = element! zs = [] cs = [] for z, c in zip(zpos, colors): zs.extend([z] * len(vertsQuad)) cs.extend([c] * len(vertsQuad)) poly.set_color(cs) ax.add_collection3d(poly, zs=zs, zdir='y') # axis limit settings: ax.set_xlim3d(0, 4) ax.set_zlim3d(0, 3) ax.set_ylim3d(0, 4)
Example #11
Source File: test_axes.py From twitter-stock-recommendation with MIT License | 5 votes |
def test_polycollection_joinstyle(): # Bug #2890979 reported by Matthew West from matplotlib import collections as mcoll fig, ax = plt.subplots() verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]) c = mcoll.PolyCollection([verts], linewidths=40) ax.add_collection(c) ax.set_xbound(0, 3) ax.set_ybound(0, 3)
Example #12
Source File: plt_draw.py From tyssue with GNU General Public License v3.0 | 5 votes |
def draw_face(sheet, coords, ax, **draw_spec_kw): """Draws epithelial sheet polygonal faces in matplotlib Keyword values can be specified at the element level as columns of the sheet.face_df """ draw_spec = sheet_spec()["face"] draw_spec.update(**draw_spec_kw) collection_specs = parse_face_specs(draw_spec, sheet) if "visible" in sheet.face_df.columns: edges = sheet.edge_df[sheet.upcast_face(sheet.face_df["visible"])].index _sheet = get_sub_eptm(sheet, edges) if _sheet is not None: sheet = _sheet color = collection_specs["facecolors"] if isinstance(color, np.ndarray): faces = sheet.face_df["face_o"].values.astype(np.uint32) collection_specs["facecolors"] = color.take(faces, axis=0) if not sheet.is_ordered: sheet_ = sheet.copy() sheet_.reset_index(order=True) polys = sheet_.face_polygons(coords) else: polys = sheet.face_polygons(coords) p = PolyCollection(polys, closed=True, **collection_specs) ax.add_collection(p) return ax
Example #13
Source File: geom_rect.py From plotnine with GNU General Public License v2.0 | 5 votes |
def draw_group(data, panel_params, coord, ax, **params): data = coord.transform(data, panel_params, munch=True) data['size'] *= SIZE_FACTOR verts = [None] * len(data) limits = zip(data['xmin'], data['xmax'], data['ymin'], data['ymax']) for i, (l, r, b, t) in enumerate(limits): verts[i] = [(l, b), (l, t), (r, t), (r, b)] fill = to_rgba(data['fill'], data['alpha']) color = data['color'] # prevent unnecessary borders if all(color.isnull()): color = 'none' col = PolyCollection( verts, facecolors=fill, edgecolors=color, linestyles=data['linetype'], linewidths=data['size'], transOffset=ax.transData, zorder=params['zorder']) ax.add_collection(col)
Example #14
Source File: quiver.py From CogAlg with MIT License | 5 votes |
def draw(self, renderer): self._init() verts = self._make_verts(self.U, self.V, self.angles) self.set_verts(verts, closed=False) self._new_UV = False mcollections.PolyCollection.draw(self, renderer) self.stale = False
Example #15
Source File: quiver.py From CogAlg with MIT License | 5 votes |
def remove(self): """ Overload the remove method """ # disconnect the call back self.ax.figure.callbacks.disconnect(self._cid) self._cid = None # pass the remove call up the stack mcollections.PolyCollection.remove(self)
Example #16
Source File: quickplotter.py From phidl with MIT License | 5 votes |
def _draw_polygons(polygons, ax, quickdraw = False, **kwargs): """ This function uses a trick where all polygon points are concatenated, separated only by NaN values. This speeds up drawing considerably, see http://exnumerus.blogspot.com/2011/02/how-to-quickly-plot-polygons-in.html """ coll = PolyCollection(polygons, **kwargs) ax.add_collection(coll) stacked_polygons = np.vstack(polygons) xmin,ymin = np.min(stacked_polygons, axis = 0) xmax,ymax = np.max(stacked_polygons, axis = 0) bbox = [xmin,ymin,xmax,ymax] return bbox
Example #17
Source File: test_axes.py From coffeegrindsize with MIT License | 5 votes |
def test_polycollection_joinstyle(): # Bug #2890979 reported by Matthew West from matplotlib import collections as mcoll fig, ax = plt.subplots() verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]) c = mcoll.PolyCollection([verts], linewidths=40) ax.add_collection(c) ax.set_xbound(0, 3) ax.set_ybound(0, 3)
Example #18
Source File: test_collections.py From coffeegrindsize with MIT License | 5 votes |
def test_polycollection_close(): from mpl_toolkits.mplot3d import Axes3D vertsQuad = [ [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] fig = plt.figure() ax = Axes3D(fig) colors = ['r', 'g', 'b', 'y', 'k'] zpos = list(range(5)) poly = mcollections.PolyCollection( vertsQuad * len(zpos), linewidth=0.25) poly.set_alpha(0.7) # need to have a z-value for *each* polygon = element! zs = [] cs = [] for z, c in zip(zpos, colors): zs.extend([z] * len(vertsQuad)) cs.extend([c] * len(vertsQuad)) poly.set_color(cs) ax.add_collection3d(poly, zs=zs, zdir='y') # axis limit settings: ax.set_xlim3d(0, 4) ax.set_zlim3d(0, 3) ax.set_ylim3d(0, 4)
Example #19
Source File: test_collections.py From ImageFusion with MIT License | 5 votes |
def test_polycollection_close(): from mpl_toolkits.mplot3d import Axes3D vertsQuad = [ [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] fig = plt.figure() ax = Axes3D(fig) colors = ['r', 'g', 'b', 'y', 'k'] zpos = list(range(5)) poly = mcollections.PolyCollection( vertsQuad * len(zpos), linewidth=0.25) poly.set_alpha(0.7) ## need to have a z-value for *each* polygon = element! zs = [] cs = [] for z, c in zip(zpos, colors): zs.extend([z] * len(vertsQuad)) cs.extend([c] * len(vertsQuad)) poly.set_color(cs) ax.add_collection3d(poly, zs=zs, zdir='y') ## axis limit settings: ax.set_xlim3d(0, 4) ax.set_zlim3d(0, 3) ax.set_ylim3d(0, 4)
Example #20
Source File: test_axes.py From ImageFusion with MIT License | 5 votes |
def test_polycollection_joinstyle(): # Bug #2890979 reported by Matthew West from matplotlib import collections as mcoll fig = plt.figure() ax = fig.add_subplot(111) verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]) c = mcoll.PolyCollection([verts], linewidths=40) ax.add_collection(c) ax.set_xbound(0, 3) ax.set_ybound(0, 3)
Example #21
Source File: guide_colorbar.py From plotnine with GNU General Public License v2.0 | 5 votes |
def add_segmented_colorbar(da, colors, direction): """ Add 'non-rastered' colorbar to DrawingArea """ nbreak = len(colors) if direction == 'vertical': linewidth = da.height/nbreak verts = [None] * nbreak x1, x2 = 0, da.width for i, color in enumerate(colors): y1 = i * linewidth y2 = y1 + linewidth verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1)) else: linewidth = da.width/nbreak verts = [None] * nbreak y1, y2 = 0, da.height for i, color in enumerate(colors): x1 = i * linewidth x2 = x1 + linewidth verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1)) coll = mcoll.PolyCollection(verts, facecolors=colors, linewidth=0, antialiased=False) da.add_artist(coll)
Example #22
Source File: hawaii.py From seapy with MIT License | 5 votes |
def land(self, color="black"): """ Draw the GIS coastline data from the state of Hawaii to draw the land boundaries. This does not include rivers, etc., only the coastline. Parameters ---------- color: string, optional Color to draw the land mask with Returns ------- None """ if hasattr(self.basemap, "coast") == False or hasattr(self, "landpoly"): self.basemap.readshapefile(_shape_file, "coast") vert = [] for shape in self.basemap.coast: vert.append(shape) self.landpoly = PolyCollection( vert, facecolors=color, edgecolors=color) # Draw the loaded shapes self.ax.add_collection(self.landpoly)
Example #23
Source File: geom_polygon.py From plotnine with GNU General Public License v2.0 | 5 votes |
def draw_group(data, panel_params, coord, ax, **params): data = coord.transform(data, panel_params, munch=True) data['size'] *= SIZE_FACTOR # Each group is a polygon with a single facecolor # with potentially an edgecolor for every edge. ngroups = data['group'].unique().size verts = [None] * ngroups facecolor = [None] * ngroups edgecolor = [None] * ngroups linestyle = [None] * ngroups linewidth = [None] * ngroups # Some stats may order the data in ways that prevent # objects from occluding other objects. We do not want # to undo that order. grouper = data.groupby('group', sort=False) for i, (group, df) in enumerate(grouper): verts[i] = tuple(zip(df['x'], df['y'])) fill = to_rgba(df['fill'].iloc[0], df['alpha'].iloc[0]) facecolor[i] = 'none' if fill is None else fill edgecolor[i] = df['color'].iloc[0] or 'none' linestyle[i] = df['linetype'].iloc[0] linewidth[i] = df['size'].iloc[0] col = PolyCollection( verts, facecolors=facecolor, edgecolors=edgecolor, linestyles=linestyle, linewidths=linewidth, transOffset=ax.transData, zorder=params['zorder']) ax.add_collection(col)
Example #24
Source File: plotlayer.py From omg-tools with GNU Lesser General Public License v3.0 | 5 votes |
def _init_axis_2d(axis, info): axis.set_xlabel(info['labels'][0]) axis.set_ylabel(info['labels'][1]) if 'xlim' in info and info['xlim'] is not None: axis.set_xlim(info['xlim'][0], info['xlim'][1]) if 'ylim' in info and info['ylim'] is not None: axis.set_ylim(info['ylim'][0], info['ylim'][1]) if 'lines' in info: for line in info['lines']: axis.plot([], [], zorder=0, **line)[0] if 'surfaces' in info: for surf in info['surfaces']: col = PolyCollection([], **surf) col.set_zorder(1) axis.add_collection(col)
Example #25
Source File: coverage.py From YAFS with MIT License | 5 votes |
def get_polygons_on_map(self): return PolyCollection(self.cells, facecolors=self.colors_cells, alpha=.25,edgecolors="gray")
Example #26
Source File: finance.py From backtrader with GNU General Public License v3.0 | 5 votes |
def barcollection(self, x, opens, closes, vols, width, edgeadjust=0, vscaling=1.0, vbot=0, **kwargs): # Prepare the data openclose = lambda: zip(opens, closes) # NOQA: E731 # Calculate bars colors colord = {True: self.colorup, False: self.colordown} colors = [colord[open < close] for open, close in openclose()] edgecolord = {True: self.edgeup, False: self.edgedown} edgecolors = [edgecolord[open < close] for open, close in openclose()] # bar width to the sides delta = width / 2 - edgeadjust # small auxiliary func to return the bar coordinates def volbar(i, v): left, right = i - delta, i + delta v = vbot + v * vscaling return (left, vbot), (left, v), (right, v), (right, vbot) barareas = [volbar(i, v) for i, v in zip(x, vols)] barcol = mcol.PolyCollection( barareas, facecolors=colors, edgecolors=edgecolors, antialiaseds=(0,), linewidths=(0.5,), **kwargs) return barcol
Example #27
Source File: axes3d.py From opticspy with MIT License | 5 votes |
def add_collection3d(self, col, zs=0, zdir='z'): ''' Add a 3D collection object to the plot. 2D collection types are converted to a 3D version by modifying the object and adding z coordinate information. Supported are: - PolyCollection - LineColleciton - PatchCollection ''' zvals = np.atleast_1d(zs) if len(zvals) > 0 : zsortval = min(zvals) else : zsortval = 0 # FIXME: Fairly arbitrary. Is there a better value? # FIXME: use issubclass() (although, then a 3D collection # object would also pass.) Maybe have a collection3d # abstract class to test for and exclude? if type(col) is mcoll.PolyCollection: art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.LineCollection: art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.PatchCollection: art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) Axes.add_collection(self, col)
Example #28
Source File: map.py From skymapper with MIT License | 5 votes |
def footprint(self, survey, nside, **kwargs): """Plot survey footprint onto map Uses `contains()` method of a `skymapper.Survey` derived class instance Args: survey: name of the survey, must be in keys of `skymapper.survey_register` nside: HealPix nside **kwargs: styling of `matplotlib.collections.PolyCollection` """ pixels, rap, decp, vertices = healpix.getGrid(nside, return_vertices=True) inside = survey.contains(rap, decp) return self.vertex(vertices[inside], **kwargs)
Example #29
Source File: map.py From skymapper with MIT License | 5 votes |
def vertex(self, vertices, color=None, vmin=None, vmax=None, **kwargs): """Plot polygons (e.g. Healpix vertices) Args: vertices: cell boundaries in RA/Dec, from getCountAtLocations() color: string or matplib color, or numeric array to set polygon colors vmin: if color is numeric array, use vmin to set color of minimum vmax: if color is numeric array, use vmin to set color of minimum **kwargs: matplotlib.collections.PolyCollection keywords Returns: matplotlib.collections.PolyCollection """ vertices_ = np.empty_like(vertices) vertices_[:,:,0], vertices_[:,:,1] = self.proj.transform(vertices[:,:,0], vertices[:,:,1]) # remove vertices which are split at the outer meridians # find variance of vertice nodes large compared to dispersion of centers centers = np.mean(vertices, axis=1) x, y = self.proj.transform(centers[:,0], centers[:,1]) var = np.sum(np.var(vertices_, axis=1), axis=-1) / (x.var() + y.var()) sel = var < 0.05 vertices_ = vertices_[sel] from matplotlib.collections import PolyCollection zorder = kwargs.pop("zorder", 0) # same as for imshow: underneath everything rasterized = kwargs.pop('rasterized', True) alpha = kwargs.pop('alpha', 1) if alpha < 1: lw = kwargs.pop('lw', 0) else: lw = kwargs.pop('lw', None) coll = PolyCollection(vertices_, zorder=zorder, rasterized=rasterized, alpha=alpha, lw=lw, **kwargs) if color is not None: coll.set_array(color[sel]) coll.set_clim(vmin=vmin, vmax=vmax) coll.set_edgecolor("face") self.ax.add_collection(coll) self.ax.set_rasterization_zorder(zorder) return coll
Example #30
Source File: quiver.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def draw(self, renderer): self._init() verts = self._make_verts(self.U, self.V, self.angles) self.set_verts(verts, closed=False) self._new_UV = False mcollections.PolyCollection.draw(self, renderer) self.stale = False