def test_patch_alpha_override(): #: Test checks that specifying an alpha attribute for a patch or #: collection will override any alpha component of the facecolor #: or edgecolor. star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle='dashdot', alpha=0.25, facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles='dashdot', alpha=0.25, facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2])
def test_clipping(): exterior = mpath.Path.unit_rectangle().deepcopy() exterior.vertices *= 4 exterior.vertices -= 2 interior = mpath.Path.unit_circle().deepcopy() interior.vertices = interior.vertices[::-1] clip_path = mpath.Path.make_compound_path(exterior, interior) star = mpath.Path.unit_regular_star(6).deepcopy() star.vertices *= 2.6 fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) col = mcollections.PathCollection([star], lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') col.set_clip_path(clip_path, ax1.transData) ax1.add_collection(col) patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') patch.set_clip_path(clip_path, ax2.transData) ax2.add_patch(patch) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3])
def mark_roi(self, alpha=0.4, **kwargs): """ Marks the ROI by a circle ans shades cosmic rays outside the ROI. :param kwargs: Passed to Basemaps tissot() function """ from matplotlib import path, collections kwargs.setdefault('lw', 2) kwargs.setdefault('zorder', 3) try: t = self.tissot(np.deg2rad(self.lon_0), np.deg2rad(self.lat_0), self.r_roi, **kwargs) xyb = np.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.], [0., 0.] ]) * self.scale p = path.Path(np.concatenate([xyb, t.get_xy()[::-1]])) p.codes = np.ones(len(p.vertices), dtype=p.code_type) * p.LINETO p.codes[0] = path.Path.MOVETO p.codes[4] = path.Path.CLOSEPOLY p.codes[5] = path.Path.MOVETO p.codes[-1] = path.Path.CLOSEPOLY col = collections.PathCollection([p], facecolor='white', alpha=alpha, zorder=1) self.ax.add_collection(col) except ValueError: print( "Warning: Could not plot ROI circle due to undefined inverse geodesic!" ) self.mark_roi_center()
def test_patch_custom_linestyle(): #: A test to check that patches and collections accept custom dash #: patterns as linestyle and that they display correctly. star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle=(0.0, (5.0, 7.0, 10.0, 7.0)), facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles=[(0.0, (5.0, 7.0, 10.0, 7.0)) ], facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2])
def test_clipping(): exterior = mpath.Path.unit_rectangle().deepcopy() exterior.vertices *= 4 exterior.vertices -= 2 interior = mpath.Path.unit_circle().deepcopy() interior.vertices = interior.vertices[::-1] clip_path = mpath.Path( vertices=np.concatenate([exterior.vertices, interior.vertices]), codes=np.concatenate([exterior.codes, interior.codes])) star = mpath.Path.unit_regular_star(6).deepcopy() star.vertices *= 2.6 ax1 = plt.subplot(121) col = mcollections.PathCollection([star], lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') col.set_clip_path(clip_path, ax1.transData) ax1.add_collection(col) ax2 = plt.subplot(122, sharex=ax1, sharey=ax1) patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red', alpha=0.7, hatch='*') patch.set_clip_path(clip_path, ax2.transData) ax2.add_patch(patch) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3])
def test_patch_alpha_coloring(): """ Test checks that the patch and collection are rendered with the specified alpha values in their facecolor and edgecolor. """ star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the star with an internal cutout of the circle verts = np.concatenate([circle.vertices, star.vertices[::-1]]) codes = np.concatenate([circle.codes, star.codes]) cut_star1 = mpath.Path(verts, codes) cut_star2 = mpath.Path(verts + 1, codes) ax = plt.axes() patch = mpatches.PathPatch(cut_star1, linewidth=5, linestyle='dashdot', facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_patch(patch) col = mcollections.PathCollection([cut_star2], linewidth=5, linestyles='dashdot', facecolor=(1, 0, 0, 0.5), edgecolor=(0, 0, 1, 0.75)) ax.add_collection(col) ax.set_xlim([-1, 2]) ax.set_ylim([-1, 2])
def plot_regions(self, axes, best_regions, plane): """ Function to plot the best efficiency regions, once they've been calculated. """ axes.autoscale(True) # colors = itertools.cycle(["r", "b", "g", "y", "c","m"]) idx = np.linspace(0, 1, len(best_regions)) cmap = cm.get_cmap('Accent') colors = itertools.cycle(cmap(idx)) legend_handles = [] axes.clear() axes.axis([ self.optimisation['Umin'], self.optimisation['Umax'], self.optimisation['Tmin'], self.optimisation['Tmax'] ]) battery = self.battery atmosphere = self.atmosphere # fig, ax = plt.subplots() # axes.set_color_cycle(jet(idx)) for patch in best_regions: zone = patch['region'] combo_colour = next(colors) area = 0 for i, p in enumerate(zone): axes.add_collection( collections.PathCollection(zone, color=combo_colour)) bbx = p.get_extents() length = bbx.x1 - bbx.x0 height = bbx.y1 - bbx.y0 area = area + length * height if area > 0.1: combo_patch = mpatches.Patch(color=combo_colour, label=patch['combo_name']) legend_handles.append(combo_patch) # plt.scatter(points[:,0], points[:,1]) axes.set_title(r"Most efficient combination") axes.set_ylabel(r"Thrust produced [N]") axes.set_xlabel(r"Air speed (in steady flight) [m/s]") axes.autoscale(False) Uplot = np.linspace(self.optimisation['Umin'] + 0.1, self.optimisation['Umax'], 100) dragP = optimised_consumption.dragFunc(Uplot, plane, atmosphere) self.plane_curve = [Uplot, dragP] axes.plot(Uplot, dragP, color='k', label='Plane') plane_line = mlines.Line2D([], [], color='k', label='Plane drag') legend_handles.append(plane_line) axes.legend(handles=legend_handles) self.canvas.draw()
def test_no_offsets_datalim(): # A collection with no offsets and a non transData # transform should return a null bbox ax = plt.axes() coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])]) ax.add_collection(coll) coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform()) assert_array_equal(coll_data_lim.get_points(), mtransforms.Bbox.null().get_points())
def mpl_axes_plot(axes, geometries, **kwargs): """Plot lines on the given axes, given the geometries.""" # TODO: This interface should be exposed nicely on the geoaxes itself. import matplotlib.collections as mcollections import cartopy.mpl_integration.patch as patch paths = [] for geom in geometries: paths.extend(patch.geos_to_path(axes.projection.project_geometry(geom))) axes.add_collection(mcollections.PathCollection(paths, facecolor='none', **kwargs), autolim=False)
def test_lslw_bcast(): col = mcollections.PathCollection([]) col.set_linestyles(['-', '-']) col.set_linewidths([1, 2, 3]) assert col.get_linestyles() == [(0, None)] * 6 assert col.get_linewidths() == [1, 2, 3] * 2 col.set_linestyles(['-', '-', '-']) assert col.get_linestyles() == [(0, None)] * 3 assert (col.get_linewidths() == [1, 2, 3]).all()
def test_lslw_bcast(): col = mcollections.PathCollection([]) col.set_linestyles(['-', '-']) col.set_linewidths([1, 2, 3]) assert_equal(col.get_linestyles(), [(None, None)] * 6) assert_equal(col.get_linewidths(), [1, 2, 3] * 2) col.set_linestyles(['-', '-', '-']) assert_equal(col.get_linestyles(), [(None, None)] * 3) assert_equal(col.get_linewidths(), [1, 2, 3])
def test_large_single_path_collection(): buff = io.BytesIO() # Generates a too-large single path in a path collection that # would cause a segfault if the draw_markers optimization is # applied. f, ax = plt.subplots() collection = collections.PathCollection( [path.Path([[-10, 5], [10, 5], [10, -5], [-10, -5], [-10, 5]])]) ax.add_artist(collection) ax.set_xlim(10**-3, 1) plt.savefig(buff)
def coastlines_land(self, facecolor=colors['land'], **kwargs): import cartopy.io.shapereader as shapereader land_path = shapereader.natural_earth(resolution='110m', category='physical', name='land') paths = [] for geom in shapereader.Reader(land_path).geometries(): paths.extend(patch.geos_to_path(self.projection.project_geometry(geom))) self.add_collection(mcollections.PathCollection(paths, facecolor=facecolor, **kwargs), autolim=False)
def plot_rects(anc, chrom, start, stop, pop_order, colors, ax, chrX=False, conf=1): conf *= 0.7 verts = [ (float(start), chrom), # left, bottom (float(start), chrom + conf), # left, top (float(stop), chrom + conf), # right, top (float(stop), chrom), # right, bottom (0, 0), # ignored ] codes = [ path.Path.MOVETO, path.Path.LINETO, path.Path.LINETO, path.Path.LINETO, path.Path.CLOSEPOLY, ] clip_path = path.Path(verts, codes) if anc in pop_order: col = mcol.PathCollection([clip_path], facecolor=colors[pop_order.index(anc)], linewidths=0) else: col = mcol.PathCollection([clip_path], facecolor=colors[-1], linewidths=0) return col
def add_fish(ax, offset=(0, 0), scale=1): """Plot the siluhette of a fish.""" path_fish = "m0 0c-13.119 71.131-12.078 130.72-12.078 138.78-5.372 8.506-3.932 18.626-3.264 23.963-6.671 1.112-2.891 4.002-2.891 5.114s-2.224 8.005.445 9.116c-.223 3.113.222 0 0 1.557-.223 1.556-3.558 3.558-2.891 8.227.667 4.67 3.558 10.228 6.226 9.784 2.224 4.892 5.559 4.669 7.56 4.447 2.001-.223 8.672-.445 10.228-6.004 5.115-1.556 5.562-4.002 5.559-6.67-.003-3.341.223-8.45-3.113-12.008 3.336-4.224.667-13.786-3.335-13.786 1.59-8.161-2.446-13.786-3.558-20.679-2.223-34.909-.298-102.74 1.112-141.84" path = parse_path(path_fish) min_p = np.min(path.vertices, 0) path.vertices -= min_p f = np.abs(path.vertices[:, 1]).max() * scale path.vertices[:, 0] = path.vertices[:, 0] / f path.vertices[:, 1] = path.vertices[:, 1] / f path.vertices += np.array(offset) collection = collections.PathCollection([path], linewidths=0, facecolors=["#909090"]) ax.add_artist(collection)
def plot_rects(bottom, left, top, right, color): codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] verts = [ (left, bottom), #left, bottom (left, top), #left, top (right, top), #right, top (right, bottom), #right, bottom (0, 0), #ignored ] clip_path = Path(verts, codes) col = mcol.PathCollection([clip_path], facecolor=color, linewidths=0) ax.add_collection(col)
def draw(self, data, panel_params, coord, ax, zorder, constant=True): """ Draw arrows at the end(s) of the lines Parameters ---------- data : dict plot information as required by geom.draw scales : dict x scale, y scale ax : axes On which to draw constant: bool If the path attributes vary along the way. If false, the arrows are per segment of the path """ first = self.ends in ('first', 'both') last = self.ends in ('last', 'both') data = data.sort_values('group', kind='mergesort') data['color'] = to_rgba(data['color'], data['alpha']) if self.type == 'open': data['facecolor'] = 'none' else: data['facecolor'] = data['color'] if not constant: # Get segments/points (x1, y1) -> (x2, y2) # for which to calculate the arrow heads idx1, idx2 = [], [] for _, df in data.groupby('group'): idx1.extend(df.index[:-1]) idx2.extend(df.index[1:]) d = dict(zorder=zorder, edgecolor=data.loc[idx1, 'color'], facecolor=data.loc[idx1, 'facecolor'], linewidth=data.loc[idx1, 'size'], linestyle=data.loc[idx1, 'linetype']) x1 = data.loc[idx1, 'x'].values y1 = data.loc[idx1, 'y'].values x2 = data.loc[idx2, 'x'].values y2 = data.loc[idx2, 'y'].values if first: paths = self.get_paths(x1, y1, x2, y2, panel_params, coord, ax) coll = mcoll.PathCollection(paths, **d) ax.add_collection(coll) if last: x1, y1, x2, y2 = x2, y2, x1, y1 paths = self.get_paths(x1, y1, x2, y2, panel_params, coord, ax) coll = mcoll.PathCollection(paths, **d) ax.add_collection(coll) else: d = dict(zorder=zorder, edgecolor=data['color'].iloc[0], facecolor=data['facecolor'].iloc[0], linewidth=data['size'].iloc[0], linestyle=data['linetype'].iloc[0], joinstyle='round', capstyle='butt') if first: x1, x2 = data['x'].iloc[0:2] y1, y2 = data['y'].iloc[0:2] x1, y1, x2, y2 = [np.array([i]) for i in (x1, y1, x2, y2)] paths = self.get_paths(x1, y1, x2, y2, panel_params, coord, ax) patch = mpatches.PathPatch(paths[0], **d) ax.add_artist(patch) if last: x1, x2 = data['x'].iloc[-2:] y1, y2 = data['y'].iloc[-2:] x1, y1, x2, y2 = x2, y2, x1, y1 x1, y1, x2, y2 = [np.array([i]) for i in (x1, y1, x2, y2)] paths = self.get_paths(x1, y1, x2, y2, panel_params, coord, ax) patch = mpatches.PathPatch(paths[0], **d) ax.add_artist(patch)
def test_joinstyle(): col = mcollections.PathCollection([], joinstyle='round') assert col.get_joinstyle() == 'round' col.set_joinstyle('miter') assert col.get_joinstyle() == 'miter'
def test_capstyle(): col = mcollections.PathCollection([], capstyle='round') assert col.get_capstyle() == 'round' col.set_capstyle('butt') assert col.get_capstyle() == 'butt'
def test_null_collection_datalim(): col = mcollections.PathCollection([]) col_data_lim = col.get_datalim(mtransforms.IdentityTransform()) assert_array_equal(col_data_lim.get_points(), mtransforms.Bbox.null().get_points())
def plot_rects(anc, chr, start, stop, hap, pop_order, colors, chrX): centro_coords = map(float, centromeres[str(chr)]) if len(centro_coords) == 3: #acrocentric chromosome mask = [ (centro_coords[1] + 2, chr - 0.4), #add +/- 2 at the end of either end (centro_coords[2] - 2, chr - 0.4), (centro_coords[2] + 2, chr), (centro_coords[2] - 2, chr + 0.4), (centro_coords[1] + 2, chr + 0.4), (centro_coords[1] - 2, chr), (centro_coords[1] + 2, chr - 0.4) ] mask_codes = [ Path.MOVETO, Path.LINETO, Path.CURVE3, Path.LINETO, Path.LINETO, Path.CURVE3, Path.LINETO, ] clip_mask = Path(vertices=mask, codes=mask_codes) else: #need to write more complicated clipping mask with centromere masked out mask = [ (centro_coords[1] + 2, chr - 0.4), #add +/- 2 at the end of either end (centro_coords[2] - 2, chr - 0.4), (centro_coords[2] + 2, chr + 0.4), (centro_coords[3] - 2, chr + 0.4), (centro_coords[3] + 2, chr), (centro_coords[3] - 2, chr - 0.4), (centro_coords[2] + 2, chr - 0.4), (centro_coords[2] - 2, chr + 0.4), (centro_coords[1] + 2, chr + 0.4), (centro_coords[1] - 2, chr), (centro_coords[1] + 2, chr - 0.4) ] mask_codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CURVE3, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CURVE3, Path.LINETO, ] clip_mask = Path(vertices=mask, codes=mask_codes) if hap == 'A': #bed_a ancestry goes on top verts = [ (float(start), chr), #left, bottom (float(start), chr + 0.4), #left, top (float(stop), chr + 0.4), #right, top (float(stop), chr), #right, bottom (0, 0), #ignored ] else: #bed_b ancestry goes on bottom verts = [ (float(start), chr - 0.4), #left, bottom (float(start), chr), #left, top (float(stop), chr), #right, top (float(stop), chr - 0.4), #right, bottom (0, 0), #ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] clip_path = Path(verts, codes) if anc in pop_order: col = mcol.PathCollection([clip_path], facecolor=colors[pop_order.index(anc)], linewidths=0) else: col = mcol.PathCollection([clip_path], facecolor=colors[-1], linewidths=0) if 'clip_mask' in locals(): col.set_clip_path(clip_mask, ax.transData) ax.add_collection(col)
def __init__(self, ax, *args, **kwargs): """ Draw contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc. """ self.ax = ax self.levels = kwargs.get('levels', None) self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.linestyles = kwargs.get('linestyles', None) self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) norm = kwargs.get('norm', None) self.extend = kwargs.get('extend', 'neither') self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) self.locator = kwargs.get('locator', None) if (isinstance(norm, colors.LogNorm) or isinstance(self.locator, ticker.LogLocator)): self.logscale = True if norm is None: norm = colors.LogNorm() if self.extend is not 'neither': raise ValueError( 'extend kwarg does not work yet with log scale') else: self.logscale = False if self.origin is not None: assert (self.origin in ['lower', 'upper', 'image']) if self.extent is not None: assert (len(self.extent) == 4) if cmap is not None: assert (isinstance(cmap, colors.Colormap)) if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = mpl.rcParams['image.origin'] if isinstance(args[0], ContourSet): C = args[0].Cntr if self.levels is None: self.levels = args[0].levels else: x, y, z = self._contour_args(*args) x0 = ma.minimum(x) x1 = ma.maximum(x) y0 = ma.minimum(y) y1 = ma.maximum(y) self.ax.update_datalim([(x0, y0), (x1, y1)]) self.ax.autoscale_view() _mask = ma.getmask(z) if _mask is ma.nomask: _mask = None C = _cntr.Cntr(x, y, z.filled(), _mask) self.Cntr = C self._process_levels() if self.colors is not None: cmap = colors.ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = cbook.silent_list('collections.PathCollection') else: self.collections = cbook.silent_list('collections.LineCollection') # label lists must be initialized here self.labelTexts = [] self.labelCValues = [] kw = {'cmap': cmap} if norm is not None: kw['norm'] = norm cm.ScalarMappable.__init__(self, **kw) # sets self.cmap; self._process_colors() if self.filled: if self.linewidths is not None: warnings.warn('linewidths is ignored by contourf') lowers = self._levels[:-1] uppers = self._levels[1:] for level, level_upper in zip(lowers, uppers): nlist = C.trace(level, level_upper, nchunk=self.nchunk) nseg = len(nlist) // 2 segs = nlist[:nseg] kinds = nlist[nseg:] paths = self._make_paths(segs, kinds) col = collections.PathCollection( paths, antialiaseds=(self.antialiased, ), edgecolors='none', alpha=self.alpha) self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths tlinestyles = self._process_linestyles() for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles): nlist = C.trace(level) nseg = len(nlist) // 2 segs = nlist[:nseg] #kinds = nlist[nseg:] col = collections.LineCollection(segs, linewidths=width, linestyle=lstyle, alpha=self.alpha) col.set_label('_nolegend_') self.ax.add_collection(col, False) self.collections.append(col) self.changed() # set the colors
def test_joinstyle(): col = mcollections.PathCollection([], joinstyle='round') assert_equal(col.get_joinstyle(), 'round') col.set_joinstyle('miter') assert_equal(col.get_joinstyle(), 'miter')
def test_capstyle(): col = mcollections.PathCollection([], capstyle='round') assert_equal(col.get_capstyle(), 'round') col.set_capstyle('butt') assert_equal(col.get_capstyle(), 'butt')