def get_circles_for_scatter(x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0): cmap = plt.get_cmap(colormap) if colornorm is not None: colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True) # setup normalizing for radius scale factor (if used) if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: if radiusnorm is None: radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True) else: radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True) # make circles points = np.array([x, y]).T circles = [None for i in range(len(x))] for i, pt in enumerate(points): if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: r = radiusnorm(radius[i])*(maxradius-minradius) + minradius else: r = radius circles[i] = patches.Circle( pt, radius=r ) # make a collection of those circles cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True # set properties for collection cc.set_edgecolors(edgecolor) if type(color) is list or type(color) is np.array or type(color) is np.ndarray: cc.set_array(color) else: cc.set_facecolors(color) cc.set_alpha(alpha) return cc
def add_pmts(ax=None, color='b', linewidth=1): x0 = 27 # 9 times the inner radius y0 = 6 * 3 * 2 / np.sqrt(3) # 6 times the outer radius if ax is None: ax = plt.gca() per_row = [9, 10, 11, 10, 11, 10, 11, 10, 9] polys = [] for row, num_pmts in enumerate(per_row): y = row * 3 * np.sqrt(3) for pmt in range(num_pmts): x = 6 * pmt if row in (0, 8): x += 3 elif row % 2 == 0: x -= 3 polys.append(RegularPolygon((x - x0, y - y0), 6, radius=6 / np.sqrt(3))) col = PatchCollection(polys) col.set_facecolors('none') col.set_edgecolors(color) col.set_linewidths(linewidth) ax.add_artist(col) return col
def get_annotations(tiles_w, image_size, indices, coordinates): patches = [] colors = [] for index in range(canvas.shape[0]): x = index % tiles_w y = int(np.floor(index / tiles_w)) tile = int(indices[index]) if tile == -1: continue else: (lat, lon) = coordinates[tile] if np.isnan(lat) or np.isnan(lon): continue fc = lonlat2rgba(lon, lat) rect = mpatches.Rectangle((x * image_size, y * image_size), image_size, image_size) patches.append(rect) colors.append(fc) #image[((y + 1) * image_size, x * image_size):(x + 1) * image_size] = canvas[index] #colors = 100 * np.random.rand(len(patches)) collection = PatchCollection(patches, alpha=0.35) collection.set_facecolors(colors) collection.set_edgecolors(colors) collection.set_linewidth(0.1) #collection.set_array(np.array(colors)) return collection
def mark_pixel(pixels, color='g', ax=None, linewidth=None): ''' surrounds pixels given by pixels with a border ''' pixel_x, pixel_y = get_pixel_coords() if ax is None: ax = plt.gca() patches = [] for xy in zip(pixel_x[pixels], pixel_y[pixels]): patches.append( RegularPolygon( xy=xy, numVertices=6, radius=9.5 / np.sqrt(3), orientation=0., # in radians fill=False, )) if linewidth is None: linewidth = calc_linewidth(ax=ax) collection = PatchCollection(patches, picker=0) collection.set_linewidth(linewidth) collection.set_edgecolors(color) collection.set_facecolor('none') ax.add_collection(collection) plt.draw_if_interactive() return collection
def render(self,ax,alpha=.7,usePyLeaflet=False, minValueThreshold=-float('Inf'),logScale=True,colormapname='BlueRed'): if not usePyLeaflet or colormapname=='nothingRed': alpha=1.0 patches = [] values = [] colorvalues = [] for d in self.countPerGeohash.keys(): try: if (self.countPerGeohash[d]>minValueThreshold): bbox = geohash.bbox(d) rect = mpatches.Rectangle([ bbox['w'], bbox['s']], bbox['e'] - bbox['w'], bbox['n'] - bbox['s'], ec='none', lw=.1, fc='red', alpha=alpha) patches.append(rect) # values.append(self.countPerGeohash[d] \ # if self.countPerGeohash[d]<3 else self.countPerGeohash[d]+10) # colorvalues.append(self.countPerGeohash[d] \ # if self.countPerGeohash[d]<3 else self.countPerGeohash[d]+10) values.append(self.countPerGeohash[d]) colorvalues.append(self.countPerGeohash[d]) except KeyError: print("'"+d +"' is not a valid geohash.") try: maxval = max(values) minval = min(values) except ValueError: print('heatmap appears to be empty...') maxval = 1 minval = 0 p = PatchCollection(patches,cmap=plt.get_cmap(colormapname),alpha=alpha) # if usePyLeaflet: if (len(values)<100): p.set_edgecolors(np.array(['black' for x in values])) else: p.set_edgecolors(np.array(['#333333' if x<=2 \ else ('#666666' if x<=10 else 'black') for x in values])) # else: # p.set_edgecolors(np.array(['white' for x in values])) p.set_array(np.array(colorvalues)) if logScale: p.set_norm(colors.LogNorm(vmin=.01, vmax=maxval)) else: p.set_norm(colors.Normalize(vmin=0, vmax=maxval)) ax.add_collection(p) ax.set_xlim(self.bbox['w'], self.bbox['e']) ax.set_ylim(self.bbox['s'], self.bbox['n']) divider = make_axes_locatable(ax) cbar = plt.colorbar(p) cbar.set_clim(vmin=max(0,minval),vmax=maxval) cbar.update_normal(p) return
def display_ifu(x_coords, y_coords, xcen, ycen, scaling, values): bundle_patches = [] for x1, y1 in zip(x_coords, y_coords): circle = Circle((x1 * scaling + xcen, y1 * scaling + ycen), 52.5 * scaling) bundle_patches.append(circle) pcol = PatchCollection(bundle_patches, cmap=py.get_cmap('afmhot')) pcol.set_array(values) pcol.set_edgecolors('none') return pcol
def get_ellipses_for_scatter(ax, x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0): # get ellipse size to make it a circle given axes x0, y0 = ax.transAxes.transform((ax.get_ylim()[0],ax.get_xlim()[0])) x1, y1 = ax.transAxes.transform((ax.get_ylim()[1],ax.get_xlim()[1])) dx = x1-x0 dy = y1-y0 maxd = max(dx,dy) cmap = plt.get_cmap(colormap) if colornorm is not None: colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True) # setup normalizing for radius scale factor (if used) if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: if radiusnorm is None: radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True) else: radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True) # make circles points = np.array([x, y]).T ellipses = [None for i in range(len(x))] for i, pt in enumerate(points): if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: r = radiusnorm(radius[i])*(maxradius-minradius) + minradius else: r = radius width = r*2*maxd/dx height = r*2*maxd/dy ellipses[i] = patches.Ellipse( pt, width, height) # make a collection of those circles cc = PatchCollection(ellipses, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True # set properties for collection cc.set_edgecolors(edgecolor) if type(color) is list or type(color) is np.array or type(color) is np.ndarray: cc.set_array(color) else: cc.set_facecolors(color) cc.set_alpha(alpha) return cc
def scatter(ax, x, y, color='black', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0, edgecolors='none'): # color can be array-like, or a matplotlib color # I can't figure out how to control alpha through the individual circle patches.. it seems to get overwritten by the collection. low priority! cmap = plt.get_cmap(colormap) if colornorm is not None: colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True) # setup normalizing for radius scale factor (if used) if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: if radiusnorm is None: radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True) else: radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True) # make circles points = np.array([x, y]).T circles = [None for i in range(len(x))] for i, pt in enumerate(points): if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray: r = radiusnorm(radius[i])*(maxradius-minradius) + minradius else: r = radius circles[i] = patches.Circle( pt, radius=r ) # make a collection of those circles cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True # set properties for collection cc.set_edgecolors(edgecolors) if type(color) is list or type(color) is np.array or type(color) is np.ndarray: cc.set_array(color) else: cc.set_facecolors(color) cc.set_alpha(alpha) # add collection to axis ax.add_collection(cc)
def get_wedges_for_heading_plot(x, y, color, orientation, size_radius=0.1, size_angle=20, colormap='jet', colornorm=None, size_radius_range=(0.01,.1), size_radius_norm=None, edgecolor='none', alpha=1, flip=True, deg=True, nskip=0, center_offset_fraction=0.75): ''' Returns a Patch Collection of Wedges, with arbitrary color and orientation Outputs: Patch Collection Inputs: x, y - x and y positions (np.array or list, each of length N) color - values to color wedges by (np.array or list, length N), OR color string. colormap - specifies colormap to use (string, eg. 'jet') norm - specifies range you'd like to normalize to, if none, scales to min/max of color array (2-tuple, eg. (0,1) ) orientation - angles are in degrees, use deg=False to convert radians to degrees size_radius - radius of wedge, in same units as x, y. Can be list or np.array, length N, for changing sizes size_radius_norm - specifies range you'd like to normalize size_radius to, if size_radius is a list/array should be tuple, eg. (0.01, .1) size_angle - angular extent of wedge, degrees. Can be list or np.array, length N, for changing sizes edgecolor - color for lineedges, string or np.array of length N alpha - transparency (single value, between 0 and 1) flip - flip orientations by 180 degrees, default = True nskip - allows you to skip between points to make the points clearer, nskip=1 skips every other point center_offset_fraction - (float in range (0,1) ) - 0 means (x,y) is at the tip, 1 means (x,y) is at the edge ''' cmap = plt.get_cmap(colormap) # norms if colornorm is None and type(color) is not str: colornorm = plt.Normalize(np.min(color), np.max(color)) elif type(color) is not str: colornorm = plt.Normalize(colornorm[0], colornorm[1]) if size_radius_norm is None: size_radius_norm = plt.Normalize(np.min(size_radius), np.max(size_radius), clip=True) else: size_radius_norm = plt.Normalize(size_radius_norm[0], size_radius_norm[1], clip=True) indices_to_plot = np.arange(0, len(x), nskip+1) # fix orientations if type(orientation) is list: orientation = np.array(orientation) if deg is False: orientation = orientation*180./np.pi if flip: orientation += 180 flycons = [] n = 0 for i in indices_to_plot: # wedge parameters if type(size_radius) is list or type(size_radius) is np.array or type(size_radius) is np.ndarray: r = size_radius_norm(size_radius[i])*(size_radius_range[1]-size_radius_range[0]) + size_radius_range[0] else: r = size_radius if type(size_angle) is list or type(size_angle) is np.array or type(size_angle) is np.ndarray: angle_swept = size_radius[i] else: angle_swept = size_radius theta1 = orientation[i] - size_angle/2. theta2 = orientation[i] + size_angle/2. center = [x[i], y[i]] center[0] -= np.cos(orientation[i]*np.pi/180.)*r*center_offset_fraction center[1] -= np.sin(orientation[i]*np.pi/180.)*r*center_offset_fraction wedge = patches.Wedge(center, r, theta1, theta2) flycons.append(wedge) # add collection and color it pc = PatchCollection(flycons, cmap=cmap, norm=colornorm) # set properties for collection pc.set_edgecolors(edgecolor) if type(color) is list or type(color) is np.array or type(color) is np.ndarray: if type(color) is list: color = np.asarray(color) pc.set_array(color[indices_to_plot]) else: pc.set_facecolors(color) pc.set_alpha(alpha) return pc
def factcamera(self, data, pixelcoords=None, cmap='gray', vmin=None, vmax=None, pixelset=None, pixelsetcolour='g', linewidth=None, intersectcolour='b', picker=True, ): """ Attributes ---------- data : array like with shape 1440 the data you want to plot into the pixels pixelset : boolean array with shape 1440 the pixels where pixelset is True are marked with 'pixelsetcolour' [default: None] pixelsetcolour : a matplotlib conform colour representation the colour for the pixels in 'pixelset', [default: green] pixelcoords : the coordinates for the pixels in form [x-values, y-values] if None, the package resource is used [default: None] cmap : str or matplotlib colormap instance the colormap to use for plotting the 'dataset' [default: gray] vmin : float the minimum for the colorbar, if None min(dataset[event]) is used [default: None] vmax : float the maximum for the colorbar, if None max(dataset[event]) is used [default: None] picker: bool if True then the the pixel are made clickable to show information """ self.set_aspect('equal') if picker is True: fig = self.get_figure() fig.canvas.mpl_connect("pick_event", onpick) # if the axes limit is still (0,1) assume new axes if self.get_xlim() == (0, 1) and self.get_ylim() == (0, 1): self.set_xlim(-200, 200) self.set_ylim(-200, 200) if pixelcoords is None: pixel_x, pixel_y = get_pixel_coords() else: pixel_x, pixel_y = pixelcoords if vmin is None: vmin = np.min(data) if vmax is None: vmax = np.max(data) edgecolors = np.array(1440*["k"]) if pixelset is None: pixelset = np.zeros(1440, dtype=np.bool) _pixelset = np.array(pixelset) if _pixelset.ndim == 1: if _pixelset.shape != (1440,): pixelset = np.zeros(1440, dtype=np.bool) pixelset[_pixelset] = True else: pixelset = np.array(_pixelset, dtype=np.bool) edgecolors[pixelset] = pixelsetcolour elif _pixelset.ndim == 2: for pixelset, colour in zip(_pixelset, pixelsetcolour): edgecolors[pixelset] = colour intersect = np.logical_and(_pixelset[0], _pixelset[1]) edgecolors[intersect] = intersectcolour else: raise ValueError( """pixelset needs to be one of: 1. list of pixelids 2. 1d bool array with shape (1440,) 3. 2d bool array with shape (2, 1440) """ ) patches = [] for x, y, ec in zip(pixel_x, pixel_y, edgecolors): patches.append( RegularPolygon( xy=(x, y), numVertices=6, radius=0.95*9.5/np.sqrt(3), orientation=0., # in radians ) ) if linewidth is None: linewidth = calc_linewidth(self) collection = PatchCollection(patches, picker=0) collection.set_linewidth(linewidth) collection.set_edgecolors(edgecolors) collection.set_cmap(cmap) collection.set_array(data) collection.set_clim(vmin, vmax) self.add_collection(collection) return collection
def draw(self, ax, draw_polygons=True, colour='k', line_alpha=1., fill_alpha=1., linestyle='-', linewidth=1., markers=None, values=None, precompv=None, vmin=None, vmax=None, title=None, cmap=None, cblabel=None, logscale=False, allowed_cbticklabels=(None, ), extend='neither', zorder=0): """ Draw the diagram """ drawvalues = values is not None if drawvalues: patches = [] colours = np.zeros(self.nc) for i, pol in self.polygons.items(): # Colours and filled polygons if drawvalues: filled_pol = mp.Polygon(self.cellverts[i]) patches.append(filled_pol) if values == 'areas': colours[i] = pol.area if values == 'inv_areas': colours[i] = 1. / self.free_areas[i] if values == 'free_areas': colours[i] = self.free_areas[i] if values == 'precomputed': if logscale: colours[i] = np.abs(precompv[i]) else: colours[i] = precompv[i] # Colour for the polygon contours if colour == 'same_as_facecolors': pc_ = colours[i] else: pc_ = colour # Draw the polygon if draw_polygons: pol.draw(ax=ax, colour=pc_, alpha=line_alpha, linestyle=linestyle, linewidth=linewidth, markers=markers, zorder=zorder) # Line colours if drawvalues: if vmin is None: vmin = colours.min() if vmax is None: vmax = colours.max() if logscale: vmin = np.abs(vmin) vmax = np.abs(vmax) norm = LogNorm(vmin=vmin, vmax=vmax) else: norm = Normalize(vmin=vmin, vmax=vmax) m = plt.cm.ScalarMappable(norm=norm, cmap=cmap) line_colours = m.to_rgba(colours) print(line_colours) if drawvalues: collection = PatchCollection(patches, cmap=cmap, norm=norm) ax.add_collection(collection) collection.set_alpha(fill_alpha) collection.set_array(colours) if logscale: collection.set_clim(vmin=vmin, vmax=vmax) else: collection.set_clim(vmin=0., vmax=vmax) if colour == 'same_as_facecolors': collection.set_edgecolors(line_colours) else: collection.set_edgecolor(colour) collection.set_linewidth(linewidth) if values == 'precomputed': collection.set_clim(vmin=vmin, vmax=vmax) # Color bar if logscale: l_f = LogFormatter(10, labelOnlyBase=False) cb = plt.colorbar(collection, ax=ax, orientation='vertical', format=l_f, extend=extend) # Set minor ticks # We need to nomalize the tick locations so that they're in the range from 0-1... # minorticks = p.norm(np.arange(1, 10, 2)) # Minimum and maximum exponents min_exp = int(np.log10(min(vmin, vmax))) max_exp = int(np.log10(max(vmin, vmax))) + 1 # Ticks for the colorbar in case it's logscale minorticks = 10.**np.arange(min_exp, max_exp + 1, 1) minorticks_ = minorticks.tolist() for i in range(2, 10, 1): minorticks_ = minorticks_ + (float(i) * minorticks).tolist() minorticks_.sort() minorticks = np.array(minorticks_) minorticks = minorticks[np.where(minorticks >= vmin)] minorticks = minorticks[np.where(minorticks <= vmax)] print(minorticks) cb.set_ticks(minorticks) cb.set_ticklabels([ str(int(x)) if x in allowed_cbticklabels else '' for x in minorticks ]) else: cb = plt.colorbar(collection, ax=ax, orientation='vertical', extend=extend) cb.set_label(cblabel) if title is not None: ax.set_title(title) ax.set_xlabel(r'$\rm x$ ($\rm \mu m$)') ax.set_ylabel(r'$\rm y$ ($\rm \mu m$)')
def make_piechart(slices, colors, ecolors, outname, showtext=True, groups=[[0,1],[2,3]], radfraction=0.2, transparent=False): assert len(groups) == 2 plt.close('all') fig, ax = plt.subplots(figsize=(5,5)) wedgeprops = {'edgecolor':'k', 'linewidth':6} patches, texts, pcts = ax.pie(slices, labeldistance=1.15, colors=colors, autopct=lambda p: '{:1.1f}\%'.format(p), wedgeprops=wedgeprops) [pct.set_fontsize(20) for pct in pcts] ax.axis('equal') for patch, ecolor in zip(patches, ecolors): patch.set_edgecolor(ecolor) fig.savefig('{}'.format(outname), transparent=True) plt.close('all') fig, ax = plt.subplots(figsize=(5,5)) ax.axis('equal') ax.axis('off') #embed() i = groups[0] ang = np.deg2rad((patches[i[-1]].theta2 + patches[i[0]].theta1)/2.0) wedges = [] for j in i: patch = patches[j] center = (radfraction*patch.r*np.cos(ang), radfraction*patch.r*np.sin(ang)) wedges.append(mpatches.Wedge(center, patch.r, patch.theta1, patch.theta2, edgecolor=patch.get_edgecolor(), facecolor=patch.get_facecolor())) text_ang = np.deg2rad((patch.theta1 + patch.theta2)/2.0) pct = pcts[j].get_text() if slices[j] == 0: pct = '' fontsize = 10 elif slices[j] < 0.01: fontsize = 10 elif slices[j] < 0.1: fontsize = 15 else: fontsize = 20 if text_ang > np.pi and text_ang < (3*np.pi)/2.0: align='top' text_pos = np.array(((1.12)*patch.r*np.cos(text_ang), (1.12)*patch.r*np.sin(text_ang))) + np.array(center) else: align='baseline' text_pos = np.array(((1.08)*patch.r*np.cos(text_ang), (1.08)*patch.r*np.sin(text_ang))) + np.array(center) if showtext: ax.text(*text_pos, s=pct, fontsize=fontsize, verticalalignment=align) i = groups[1] for j in i: try: patch = patches[j] except: embed() center = patch.center wedges.append(mpatches.Wedge(center, patch.r, patch.theta1, patch.theta2, edgecolor=patch.get_edgecolor(), facecolor=patch.get_facecolor())) text_ang = np.deg2rad((patch.theta1 + patch.theta2)/2.0) pct = pcts[j].get_text() if slices[j] == 0: pct = '' fontsize = 10 elif slices[j] < 0.01: fontsize = 10 elif slices[j] < 0.1: fontsize = 15 else: fontsize = 20 if text_ang > np.pi and text_ang < (3*np.pi)/2.0: align='top' text_pos = np.array(((1.12)*patch.r*np.cos(text_ang), (1.12)*patch.r*np.sin(text_ang))) + np.array(center) else: align='baseline' text_pos = np.array(((1.08)*patch.r*np.cos(text_ang), (1.08)*patch.r*np.sin(text_ang))) + np.array(center) if showtext: ax.text(*text_pos, s=pct, fontsize=fontsize, verticalalignment=align) collection = PatchCollection(wedges) collection.set_facecolors(colors) collection.set_linewidths(6) collection.set_edgecolors(ecolors) #collection.set_array(np.array(colors)) ax.add_collection(collection) ax.autoscale(True) #ax.text(*pcts[0].get_position(), s=pcts[0].get_text()) fig.savefig('{}_nolabel'.format(outname), transparent=transparent) plt.close('all')
tmp = np.copy(-kyst2[:,0]) kyst2[:,0]=kyst2[:,1] kyst2[:,1]=tmp polygon = Polygon(kyst2, True) patches_flds.append(polygon) kyst2 = np.array([]) kll = np.array([]) klo = np.array([]) #---------------------------------------------------------- #-- p_blks = PatchCollection(patches_blks,alpha=0.2) p_blks.set_facecolors('none')#(1, 1, 0, 0.0)) p_blks.set_edgecolors((0, 0, 0, 1.0)) ax.add_collection(p_blks) #-- #-- p_flds = PatchCollection(patches_flds,alpha=0.4) p_flds.set_facecolors((.5, .5, .5, .5)) p_flds.set_edgecolors((0, 0, 0, 1.0)) ax.add_collection(p_flds) #-- colors = 100*np.random.rand(len(patches)) p = PatchCollection(patches, alpha=0.4) p.set_array(np.array(colors)) p.set_edgecolors((0, 0, 0, 1.0)) ax.add_collection(p)
def plot_counties( ax, counties, values=None, edgecolors=None, contourcolor="white", hatch_surround=None, xlim=None, ylim=None, background=True, xticks=True, yticks=True, grid=True, frame=True, xlabel="Longitude [in dec. degrees]", ylabel="Latitude [in dec. degrees]", lw=1): polygons = [r["shape"] for r in counties.values()] # extend german borders :S and then shrink them again after unifying # gets rid of many holes at the county boundaries contour = cascaded_union([pol.buffer(0.01) for pol in polygons]).buffer(-0.01) xmin, ymin, xmax, ymax = contour.bounds if xlim is None: xlim = [xmin, xmax] if ylim is None: ylim = [ymin, ymax] surround = PolygonPatch(Polygon([(xlim[0], ylim[0]), (xlim[0], ylim[1]), ( xlim[1], ylim[1]), (xlim[1], ylim[0])]).difference(contour)) contour = PolygonPatch(contour, lw=lw) pc = PatchCollection([PolygonPatch(p, lw=lw) for p in polygons], cmap=matplotlib.cm.magma, alpha=1.0) if values is not None: if isinstance(values, (dict, OrderedDict)): values = np.array([values.setdefault(r, np.nan) for r in counties.keys()]) elif isinstance(values, str): values = np.array([r.setdefault(values, np.nan) for r in counties.values()]) else: assert np.size(values) == len(counties), "Number of values ({}) doesn't match number of counties ({})!".format( np.size(values), len(counties)) pc.set_clim(0, 10) nans = np.isnan(values) values[nans] = 0 values = np.ma.MaskedArray(values, mask=nans) pc.set(array=values, cmap='magma') else: pc.set_facecolors("none") if edgecolors is not None: if isinstance(edgecolors, (dict, OrderedDict)): edgecolors = np.array([edgecolors.setdefault(r, "none") for r in counties.keys()]) elif isinstance(edgecolors, str): edgecolors = np.array([r.setdefault(edgecolors, "none") for r in counties.values()]) pc.set_edgecolors(edgecolors) else: pc.set_edgecolors("none") if hatch_surround is not None: surround.set_hatch(hatch_surround) surround.set_facecolor("none") ax.add_patch(surround) cb = plt.colorbar(pc, shrink=0.6) cb.set_ticks([0,5,10]) #cb.set_yticks([0.00004]) ax.add_collection(pc) if contourcolor is not None: contour.set_edgecolor(contourcolor) contour.set_facecolor("none") ax.add_patch(contour) if isinstance(background, bool): ax.patch.set_visible(background) else: ax.patch.set_color(background) ax.grid(grid) ax.set_frame_on(frame) ax.set_xlim(*xlim) ax.set_ylim(*ylim) ax.set_aspect(1.43) if xlabel: ax.set_xlabel(xlabel, fontsize=14) if ylabel: ax.set_ylabel(ylabel, fontsize=14) ax.tick_params(axis="x", which="both", bottom=xticks, labelbottom=xticks) ax.tick_params(axis="y", which="both", left=yticks, labelleft=yticks) #plt.colorbar() return pc, contour, surround
def plot_hextensor(tensor, image_range=(0, None), channel_range=(0, None), cmap=mymap, norm=None, linewidth=1, edgecolors='k', zorder=None, figname="figure", mask=[]): r"""Plot the hexagonal representation of a 4D tensor according to the addressing sheme used by HexagDLy. Args: tensor: torch tensor or numpy array containing the hexagonal data points image_range: tuple of ints, range defining the images to be plotted channel_range: tuple of ints, range defining the channels to be plotted cmap: colourmap figname: str, name of figure mask: list of ints that depict the pixels to skip in plots counting top to bottom left to right from the top left pixel """ try: tensor = tensor.data.numpy() except: pass if norm is None: norm = Normalize(tensor.min(), tensor.max()) if isinstance(edgecolors, np.ndarray) or isinstance(edgecolors, list): edgecolors[(edgecolors == '') | (edgecolors == '1')] = 'k' inshape = np.shape(tensor[image_range[0]:image_range[1], channel_range[0]:channel_range[1]]) inexamples = inshape[0] inchannels = inshape[1] if inexamples != 1 and inchannels != 1: print( "Choose one image and n channels or one channel an n images to display!" ) sys.exit() nimages = max(inexamples, inchannels) hexagons = [[] for i in range(nimages)] intensities = [[] for i in range(nimages)] fig = plt.figure(figname, (5, 5)) fig.clear() nrows = int(np.ceil(np.sqrt(nimages))) gs = gridspec.GridSpec(nrows, nrows) gs.update(wspace=0, hspace=0) for i in range(nimages): if inexamples >= inchannels: a = i b = 0 else: a = 0 b = i npixel = 0 for x in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1]): for y in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0]): if npixel not in mask: intensity = tensor[image_range[0] + a, channel_range[0] + b, y, x] hexagon = RegularPolygon( (x * np.sqrt(3) / 2, -(y + np.mod(x, 2) * 0.5)), 6, 0.577349, orientation=np.pi / 6, ) intensities[i].append(intensity) hexagons[i].append(hexagon) npixel += 1 ax = fig.add_subplot(gs[i]) ax.set_xlim([ -1, np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1] ]) #embed() ax.set_ylim([ -1.15 * np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0] - 1, 1, ]) ax.set_axis_off() p = PatchCollection(np.array(hexagons[i]), cmap=cmap, norm=norm, alpha=0.9, edgecolors="k", linewidth=linewidth) p.set_array(np.array(np.array(intensities[i]))) p.set_linewidth(linewidth) p.set_cmap(cmap) #p.set_norm(norm) p.set_edgecolors(edgecolors) p.set_zorder(zorder) ax.add_collection(p) ax.set_aspect("equal") plt.subplots_adjust(top=0.95, bottom=0.05) plt.tight_layout()
def camera( data, ax=None, cmap='gray', vmin=None, vmax=None, pixelcoords=None, edgecolor='k', linewidth=None, picker=False, ): ''' Parameters ---------- data : array like with shape 1440 the data you want to plot into the pixels ax : a matplotlib.axes.Axes instace or None The matplotlib axes in which to plot. If None, plt.gca() is used cmap : str or matplotlib colormap instance the colormap to use for plotting the 'dataset' [default: gray] vmin : float the minimum for the colorbar, if None min(data) is used [default: None] vmax : float the maximum for the colorbar, if None max(data) is used [default: None] pixelcoords : the coordinates for the pixels in form [x-values, y-values] if None, the package resource is used [default: None] edgecolor : any matplotlib color the color around the pixel picker: bool if True then the the pixel are made clickable to show information ''' if ax is None: ax = plt.gca() ax.set_aspect('equal') if picker is True: fig = ax.get_figure() fig.canvas.mpl_connect('pick_event', onpick) # if the axes limit is still (0,1) assume new axes if ax.get_xlim() == (0, 1) and ax.get_ylim() == (0, 1): ax.set_xlim(-200, 200) ax.set_ylim(-200, 200) if pixelcoords is None: pixel_x, pixel_y = get_pixel_coords() else: pixel_x, pixel_y = pixelcoords if vmin is None: vmin = np.min(data) if vmax is None: vmax = np.max(data) edgecolors = np.array(1440 * [edgecolor]) patches = [] for x, y, ec in zip(pixel_x, pixel_y, edgecolors): patches.append( RegularPolygon( xy=(x, y), numVertices=6, radius=9.51 / np.sqrt(3), orientation=0., # in radians )) if linewidth is None: linewidth = calc_linewidth(ax=ax) collection = PatchCollection(patches, picker=0) collection.set_linewidth(linewidth) collection.set_edgecolors(edgecolors) collection.set_cmap(cmap) collection.set_array(data) collection.set_clim(vmin, vmax) ax.add_collection(collection) plt.draw_if_interactive() return collection