Python matplotlib.collections.PatchCollection() Examples
The following are 30
code examples of matplotlib.collections.PatchCollection().
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: graph.py From nusa with MIT License | 6 votes |
def __init__(self,xcoord,ycoord,**kwargs): collections.PatchCollection.__init__(self,[],**kwargs) tol = 0.02 _xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol]) _ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol]) _xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol]) _ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol]) # Polygons p1 = patches.Polygon(zip(_xdata1,_ydata1)) p1.set_color("r") p2 = patches.Polygon(zip(_xdata2,_ydata2)) #print p1,p2 #p2.set_color("g") # Set data self.set_paths((p1,p2)) self.set_color("k") #self.set_marker("-") #self.set_mfc('r') #self.set_ms(10)
Example #2
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=1e3, pmin=0, color="#999999", ytext=20): """Highlights bursts in a timetrace plot.""" b = d.mburst[i] if b.num_bursts == 0: return burst_mask = (tmin_clk < b.start) * (b.start < tmax_clk) bs = b[burst_mask] burst_indices = np.where(burst_mask)[0] start = bs.start * d.clk_p end = bs.stop * d.clk_p R = [] width = end - start ax = gca() for b, bidx, s, w, sign, va in zip(bs, burst_indices, start, width, cycle([-1, 1]), cycle(['top', 'bottom'])): r = Rectangle(xy=(s, pmin), height=pmax - pmin, width=w) r.set_clip_box(ax.bbox) r.set_zorder(0) R.append(r) ax.text(s, sign * ytext, _burst_info(d, i, bidx), fontsize=6, rotation=45, horizontalalignment='center', va=va) ax.add_artist(PatchCollection(R, lw=0, color=color))
Example #3
Source File: segment.py From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 | 6 votes |
def submit(self, event): if not self.right_click: print ('Right click before submit is a must!!') else: self.text+=self.radio.value_selected+'\n'+'%.2f'%self.find_poly_area()+'\n'+self.print_points()+'\n\n' self.right_click = False #print (self.points) self.lines, self.circles = [], [] self.click_id = fig.canvas.mpl_connect('button_press_event', self.onclick) self.polys.append(Polygon(self.points_to_polygon(), closed=True, color=np.random.rand(3), alpha=0.4, fill=True)) if self.submit_p: self.submit_p.remove() self.submit_p = PatchCollection(self.polys, cmap=matplotlib.cm.jet, alpha=0.4) self.ax.add_collection(self.submit_p) self.points = []
Example #4
Source File: segment.py From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 | 6 votes |
def onclick_release(self, event): if any([x.in_axes(event) for x in self.button_axes]) or self.selected_poly: return if hasattr(self, 'r_x') and hasattr(self, 'r_y') and None not in [self.r_x, self.r_y, event.xdata, event.ydata]: if np.abs(event.xdata - self.r_x)>10 and np.abs(event.ydata - self.r_y)>10: # 10 pixels limit for rectangle creation if len(self.points)<4: self.right_click=True self.fig.canvas.mpl_disconnect(self.click_id) self.click_id = None bbox = [np.min([event.xdata, self.r_x]), np.min([event.ydata, self.r_y]), np.max([event.xdata, self.r_x]), np.max([event.ydata, self.r_y])] self.r_x = self.r_y = None self.points = [bbox[0], bbox[1], bbox[0], bbox[3], bbox[2], bbox[3], bbox[2], bbox[1], bbox[0], bbox[1]] self.p = PatchCollection([Polygon(self.points_to_polygon(), closed=True)], facecolor='red', linewidths=0, alpha=0.4) self.ax.add_collection(self.p) self.fig.canvas.draw()
Example #5
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 #6
Source File: Util.py From pyFTS with GNU General Public License v3.0 | 6 votes |
def plot_density_rectange(ax, cmap, density, fig, resolution, time_from, time_to): """ Auxiliar function to plot_compared_intervals_ahead """ from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection patches = [] colors = [] for x in density.index: for y in density.columns: s = Rectangle((time_from + x, y), 1, resolution, fill=True, lw = 0) patches.append(s) colors.append(density[y][x]*5) pc = PatchCollection(patches=patches, match_original=True) pc.set_clim([0, 1]) pc.set_cmap(cmap) pc.set_array(np.array(colors)) ax.add_collection(pc) cb = fig.colorbar(pc, ax=ax) cb.set_label('Density')
Example #7
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 #8
Source File: polygonize.py From SpaceNetExploration with MIT License | 6 votes |
def visualize_poly(poly_list, mask, out_path): """ Visualizes the polygons produced by mask_to_poly() and save them at the specified path Args: poly_list: list of shapely.geometry.polygon.Polygon on this image mask: the predicted mask, needed for laying out the axes out_path: path at which the visualization of the list of polygons is to be saved """ fig, ax = plt.subplots() ax.imshow(mask, alpha=0) # don't show the mask, but need this to be added to the axes for polygons to show up patch_list = [] for poly in poly_list: x, y = poly.exterior.coords.xy xy = np.column_stack((x, y)) polygon = matplotlib.patches.Polygon(xy, linewidth=1, edgecolor='b', facecolor='none') patch_list.append(polygon) p = PatchCollection(patch_list, cmap=matplotlib.cm.jet, alpha=1) ax.add_collection(p) fig.savefig(out_path, bbox_inches='tight') plt.close(fig)
Example #9
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 #10
Source File: coco.py From DenseVideoCaptioning with MIT License | 5 votes |
def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if self.dataset['type'] == 'instances': ax = plt.gca() polygons = [] color = [] for ann in anns: c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape((len(seg)/2, 2)) polygons.append(Polygon(poly, True,alpha=0.4)) color.append(c) else: # mask mask = COCO.decodeMask(ann['segmentation']) img = np.ones( (mask.shape[0], mask.shape[1], 3) ) if ann['iscrowd'] == 1: color_mask = np.array([2.0,166.0,101.0])/255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:,:,i] = color_mask[i] ax.imshow(np.dstack( (img, mask*0.5) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) if self.dataset['type'] == 'captions': for ann in anns: print(ann['caption'])
Example #11
Source File: Util.py From pyFTS with GNU General Public License v3.0 | 5 votes |
def plot_distribution(ax, cmap, probabilitydist, fig, time_from, reference_data=None): """ Plot forecasted ProbabilityDistribution objects on a matplotlib axis :param ax: matplotlib axis :param cmap: matplotlib colormap name :param probabilitydist: list of ProbabilityDistribution objects :param fig: matplotlib figure :param time_from: starting time (on x axis) to begin the plots :param reference_data: :return: """ from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection patches = [] colors = [] for ct, dt in enumerate(probabilitydist): disp = 0.0 if reference_data is not None: disp = reference_data[time_from+ct] for y in dt.bins: s = Rectangle((time_from+ct, y+disp), 1, dt.resolution, fill=True, lw = 0) patches.append(s) colors.append(dt.density(y)) scale = Transformations.Scale() colors = scale.apply(colors) pc = PatchCollection(patches=patches, match_original=True) pc.set_clim([0, 1]) pc.set_cmap(cmap) pc.set_array(np.array(colors)) ax.add_collection(pc) cb = fig.colorbar(pc, ax=ax) cb.set_label('Density')
Example #12
Source File: DOTA.py From RoITransformer_DOTA with MIT License | 5 votes |
def showAnns(self, objects, imgId, range): """ :param catNms: category names :param objects: objects to show :param imgId: img to show :param range: display range in the img :return: """ img = self.loadImgs(imgId)[0] plt.imshow(img) plt.axis('off') ax = plt.gca() ax.set_autoscale_on(False) polygons = [] color = [] circles = [] r = 5 # pdb.set_trace() for obj in objects: if obj['difficult'] != '0': continue c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] poly = obj['poly'] import pdb # pdb.set_trace() polygons.append(Polygon(poly)) color.append(c) point = poly[0] circle = Circle((point[0], point[1]), r) circles.append(circle) p = PatchCollection(polygons, facecolors=color, linewidths=0, alpha=0.4) ax.add_collection(p) p = PatchCollection(polygons, facecolors='none', edgecolors=color, linewidths=2) ax.add_collection(p) p = PatchCollection(circles, facecolors='red') ax.add_collection(p) plt.show()
Example #13
Source File: plot.py From PyPSA with GNU General Public License v3.0 | 5 votes |
def directed_flow(coords, flow, color, area_factor=1, cmap=None): """ Helper function to generate arrows from flow data. """ # this funtion is used for diplaying arrows representing the network flow data = pd.DataFrame( {'arrowsize': flow.abs().pipe(np.sqrt).clip(lower=1e-8), 'direction': np.sign(flow), 'linelength': (np.sqrt((coords.x1 - coords.x2)**2. + (coords.y1 - coords.y2)**2))}) data = data.join(coords) if area_factor: data['arrowsize']= data['arrowsize'].mul(area_factor) data['arrowtolarge'] = (1.5 * data.arrowsize > data.linelength) # swap coords for negativ directions data.loc[data.direction == -1., ['x1', 'x2', 'y1', 'y2']] = \ data.loc[data.direction == -1., ['x2', 'x1', 'y2', 'y1']].values if ((data.linelength > 0.) & (~data.arrowtolarge)).any(): data['arrows'] = ( data[(data.linelength > 0.) & (~data.arrowtolarge)] .apply(lambda ds: FancyArrow(ds.x1, ds.y1, 0.6*(ds.x2 - ds.x1) - ds.arrowsize * 0.75 * (ds.x2 - ds.x1) / ds.linelength, 0.6 * (ds.y2 - ds.y1) - ds.arrowsize * 0.75 * (ds.y2 - ds.y1)/ds.linelength, head_width=ds.arrowsize), axis=1)) data.loc[(data.linelength > 0.) & (data.arrowtolarge), 'arrows'] = \ (data[(data.linelength > 0.) & (data.arrowtolarge)] .apply(lambda ds: FancyArrow(ds.x1, ds.y1, 0.001*(ds.x2 - ds.x1), 0.001*(ds.y2 - ds.y1), head_width=ds.arrowsize), axis=1)) data = data.dropna(subset=['arrows']) arrowcol = PatchCollection(data.arrows, color=color, edgecolors='k', linewidths=0., zorder=4, alpha=1) return arrowcol
Example #14
Source File: test_axes.py From ImageFusion with MIT License | 5 votes |
def test_mixed_collection(): from matplotlib import patches from matplotlib import collections x = list(xrange(10)) # First illustrate basic pyplot interface, using defaults where possible. fig = plt.figure() ax = fig.add_subplot(1, 1, 1) c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green') # PDF can optimize this one p1 = collections.PatchCollection([c], match_original=True) p1.set_offsets([[0, 0], [24, 24]]) p1.set_linewidths([1, 5]) # PDF can't optimize this one, because the alpha of the edge changes p2 = collections.PatchCollection([c], match_original=True) p2.set_offsets([[48, 0], [-32, -16]]) p2.set_linewidths([1, 5]) p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]]) ax.patch.set_color('0.5') ax.add_collection(p1) ax.add_collection(p2) ax.set_xlim(0, 16) ax.set_ylim(0, 16)
Example #15
Source File: line_orientation.py From ArcPy with GNU General Public License v2.0 | 5 votes |
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs): """A bar plot colored by a scalar sequence.""" if ax is None: ax = plt.gca() width = itertools.cycle(np.atleast_1d(width)) bottom = itertools.cycle(np.atleast_1d(bottom)) rects = [] for x, y, h, w in zip(left, bottom, height, width): rects.append(Rectangle((x,y), w, h)) coll = PatchCollection(rects, array=z, **kwargs) ax.add_collection(coll) ax.autoscale() return coll
Example #16
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 #17
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 #18
Source File: coverage.py From YAFS with MIT License | 5 votes |
def get_polygons_on_map(self): """ This functions display network endpoint on the map representation Returns: a list of matplotlib Polygons """ return PatchCollection(self.regions_to_map, facecolors=self.colors_cells, alpha=.25)
Example #19
Source File: geometry.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_artists(self, ax, plot_args, plot_kwargs): if 'c' in plot_kwargs: plot_kwargs['array'] = plot_kwargs.pop('c') if 'vmin' in plot_kwargs and 'vmax' in plot_kwargs: plot_kwargs['clim'] = plot_kwargs.pop('vmin'), plot_kwargs.pop('vmax') line_segments = PatchCollection(*plot_args, **plot_kwargs) ax.add_collection(line_segments) return {'artist': line_segments}
Example #20
Source File: geom_dotplot.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) fill = to_rgba(data['fill'], data['alpha']) color = to_rgba(data['color'], data['alpha']) ranges = coord.range(panel_params) # For perfect circles the width/height of the circle(ellipse) # should factor in the dimensions of axes bbox = ax.get_window_extent().transformed( ax.figure.dpi_scale_trans.inverted()) ax_width, ax_height = bbox.width, bbox.height factor = ((ax_width/ax_height) * np.ptp(ranges.y)/np.ptp(ranges.x)) size = data.loc[0, 'binwidth'] * params['dotsize'] offsets = data['stackpos'] * params['stackratio'] if params['binaxis'] == 'x': width, height = size, size*factor xpos, ypos = data['x'], data['y'] + height*offsets elif params['binaxis'] == 'y': width, height = size/factor, size xpos, ypos = data['x'] + width*offsets, data['y'] circles = [] for xy in zip(xpos, ypos): patch = mpatches.Ellipse(xy, width=width, height=height) circles.append(patch) coll = mcoll.PatchCollection(circles, edgecolors=color, facecolors=fill) ax.add_collection(coll)
Example #21
Source File: test_artist.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_collection_transform_of_none(): # tests the behaviour of collections added to an Axes with various # transform specifications ax = plt.axes() ax.set_xlim([1, 3]) ax.set_ylim([1, 3]) # draw an ellipse over data coord (2,2) by specifying device coords xy_data = (2, 2) xy_pix = ax.transData.transform_point(xy_data) # not providing a transform of None puts the ellipse in data coordinates e = mpatches.Ellipse(xy_data, width=1, height=1) c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5) ax.add_collection(c) # the collection should be in data coordinates assert c.get_offset_transform() + c.get_transform() == ax.transData # providing a transform of None puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=120, height=120) c = mcollections.PatchCollection([e], facecolor='coral', alpha=0.5) c.set_transform(None) ax.add_collection(c) assert isinstance(c.get_transform(), mtransforms.IdentityTransform) # providing an IdentityTransform puts the ellipse in device coordinates e = mpatches.Ellipse(xy_pix, width=100, height=100) c = mcollections.PatchCollection([e], transform=mtransforms.IdentityTransform(), alpha=0.5) ax.add_collection(c) assert isinstance(c._transOffset, mtransforms.IdentityTransform)
Example #22
Source File: heatmap.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_artists(self, ax, plot_args, plot_kwargs): # Draw edges color_opts = ['c', 'cmap', 'vmin', 'vmax', 'norm', 'array'] groups = [g for g in self._style_groups if g != 'annular'] edge_opts = filter_styles(plot_kwargs, 'annular', groups) annuli = plot_args['annular'] edge_opts.pop('interpolation', None) annuli = PatchCollection(annuli, transform=ax.transAxes, **edge_opts) ax.add_collection(annuli) artists = {'artist': annuli} paths = plot_args['xseparator'] if paths: groups = [g for g in self._style_groups if g != 'xmarks'] xmark_opts = filter_styles(plot_kwargs, 'xmarks', groups, color_opts) xmark_opts.pop('edgecolors', None) xseparators = LineCollection(paths, **xmark_opts) ax.add_collection(xseparators) artists['xseparator'] = xseparators paths = plot_args['yseparator'] if paths: groups = [g for g in self._style_groups if g != 'ymarks'] ymark_opts = filter_styles(plot_kwargs, 'ymarks', groups, color_opts) ymark_opts.pop('edgecolors', None) yseparators = PatchCollection(paths, facecolor='none', transform=ax.transAxes, **ymark_opts) ax.add_collection(yseparators) artists['yseparator'] = yseparators return artists
Example #23
Source File: path.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_artists(self, ax, plot_args, plot_kwargs): polys = PatchCollection(*plot_args, **plot_kwargs) ax.add_collection(polys) return {'artist': polys}
Example #24
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_mixed_collection(): from matplotlib import patches from matplotlib import collections x = list(range(10)) # First illustrate basic pyplot interface, using defaults where possible. fig = plt.figure() ax = fig.add_subplot(1, 1, 1) c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green') # PDF can optimize this one p1 = collections.PatchCollection([c], match_original=True) p1.set_offsets([[0, 0], [24, 24]]) p1.set_linewidths([1, 5]) # PDF can't optimize this one, because the alpha of the edge changes p2 = collections.PatchCollection([c], match_original=True) p2.set_offsets([[48, 0], [-32, -16]]) p2.set_linewidths([1, 5]) p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]]) ax.patch.set_color('0.5') ax.add_collection(p1) ax.add_collection(p2) ax.set_xlim(0, 16) ax.set_ylim(0, 16)
Example #25
Source File: errorbars_and_boxes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r', edgecolor='None', alpha=0.5): # Create list for all the error patches errorboxes = [] # Loop over data points; create box from errors at each point for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T): rect = Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum()) errorboxes.append(rect) # Create patch collection with specified colour/alpha pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha, edgecolor=edgecolor) # Add collection to axes ax.add_collection(pc) # Plot errorbars artists = ax.errorbar(xdata, ydata, xerr=xerror, yerr=yerror, fmt='None', ecolor='k') return artists # Create figure and axes
Example #26
Source File: axes3d.py From GraphicDesignPatternByPython 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) 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) super().add_collection(col)
Example #27
Source File: mesh.py From nusa with MIT License | 5 votes |
def plot_mesh(self): import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.ec): _x,_y,_ux,_uy = [],[],[],[] for nd in elm: _x.append(self.nc[nd,0]) _y.append(self.nc[nd,1]) polygon = Polygon(list(zip(_x,_y)), True) patches.append(polygon) pc = PatchCollection(patches, color="#25CDCD", edgecolor="#435959", alpha=0.8, lw=0.5) ax.add_collection(pc) x0,x1,y0,y1 = self._rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) #~ ax.set_title("Model %s"%(self.name)) ax.set_aspect("equal") plt.show()
Example #28
Source File: model.py From nusa with MIT License | 5 votes |
def plot_esol(self,var="ux"): import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.get_elements()): _x,_y,_ux,_uy = [],[],[],[] for nd in elm.nodes: _x.append(nd.x) _y.append(nd.y) polygon = Polygon(list(zip(_x,_y)), True) patches.append(polygon) pc = PatchCollection(patches, cmap="jet", alpha=1) solutions = { "sxx": [e.sx for e in self.get_elements()], "syy": [e.sy for e in self.get_elements()], "sxy": [e.sxy for e in self.get_elements()], "exx": [e.ex for e in self.get_elements()], "eyy": [e.ey for e in self.get_elements()], "exy": [e.exy for e in self.get_elements()] } fsol = np.array(solutions.get(var.lower())) pc.set_array(fsol) ax.add_collection(pc) plt.colorbar(pc) x0,x1,y0,y1 = self.rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) ax.set_aspect("equal") ax_title = "{0} (Max:{1}, Min:{2})".format(var,fsol.max(),fsol.min()) ax.set_title(ax_title)
Example #29
Source File: model.py From nusa with MIT License | 5 votes |
def plot_model(self): """ Plot the mesh model, including bcs """ import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection fig = plt.figure() ax = fig.add_subplot(111) _x,_y = [],[] patches = [] for k,elm in enumerate(self.get_elements()): _x,_y,_ux,_uy = [],[],[],[] for nd in elm.nodes: if nd.fx != 0: self._draw_xforce(ax,nd.x,nd.y) if nd.fy != 0: self._draw_yforce(ax,nd.x,nd.y) if nd.ux == 0 and nd.uy == 0: self._draw_xyconstraint(ax,nd.x,nd.y) _x.append(nd.x) _y.append(nd.y) polygon = Polygon(list(zip(_x,_y)), True) patches.append(polygon) pc = PatchCollection(patches, color="#7CE7FF", edgecolor="k", alpha=0.4) ax.add_collection(pc) x0,x1,y0,y1 = self.rect_region() ax.set_xlim(x0,x1) ax.set_ylim(y0,y1) ax.set_title("Model %s"%(self.name)) ax.set_aspect("equal")
Example #30
Source File: plotting.py From beat with GNU General Public License v3.0 | 5 votes |
def plot_quadtree(ax, data, target, cmap, colim, alpha=0.8): """ Plot UnwrappedIFG displacements on the respective quadtree rectangle. """ rectangles = [] for E, N, sE, sN in target.quadtree.iter_leaves(): rectangles.append( Rectangle( (E / km, N / km), width=sE / km, height=sN / km, edgecolor='black')) patch_col = PatchCollection( rectangles, match_original=True, alpha=alpha, linewidth=0.5) patch_col.set(array=data, cmap=cmap) patch_col.set_clim((-colim, colim)) E = target.quadtree.east_shifts N = target.quadtree.north_shifts xmin = E.min() / km xmax = (E + target.quadtree.sizeE).max() / km ymin = N.min() / km ymax = (N + target.quadtree.sizeN).max() / km ax.add_collection(patch_col) ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) return patch_col