def cmapFromName(cmapname, ncols=256, bad=None): """ Do we need this? """ if not bad: bad = [1.0, 1.0, 1.0, 0.0] cmap = mpl.cm.get_cmap('jet', ncols) if cmapname is not None: if cmapname == 'b2r': cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, ncols) elif cmapname == 'viridis' and StrictVersion(mpl.__version__) < StrictVersion('1.5.0'): print("Mpl:", mpl.__version__, " using HB viridis") cmap = LinearSegmentedColormap.from_list('viridis', viridis_data[::-1]) elif cmapname == 'viridis_r': print("Using HB viridis_r") cmap = LinearSegmentedColormap.from_list('viridis', viridis_data) else: try: cmap = mpl.cm.get_cmap(cmapname, ncols) except Exception as e: print("Could not retrieve colormap ", cmapname, e) cmap.set_bad(bad) return cmap
def demo_compositing(im_r, im_g, im_b, im_rgb): fig = plt.figure(3) grid = ImageGrid(fig, 222, nrows_ncols = (2, 2), axes_pad = 0.1, ) cm_red = LinearSegmentedColormap.from_list('cm_black_red', [cm.colors.cnames['black'], cm.colors.cnames['red']]) cm_green = LinearSegmentedColormap.from_list('cm_black_green', [cm.colors.cnames['black'], cm.colors.cnames['green']]) cm_blue= LinearSegmentedColormap.from_list('cm_black_blue', [cm.colors.cnames['black'], cm.colors.cnames['blue']]) im_grid = [im_r, im_g, im_b, im_rgb] color_maps = [cm_red, cm_green, cm_blue, None] for i in range(4): cmap = color_maps[i] grid[i].imshow(im_grid[i], cmap = cmap, interpolation = 'nearest') # The AxesGrid object work as a list of axes. plt.show()
def _make_STMView_colormap(fileName, name='my_cmap'): if fileName.endswith('.mat'): matFile = _loadmat(_path + fileName) for key in matFile: if key not in ['__version__', '__header__', '__globals__']: return _LSC.from_list(name, matFile[key]) elif fileName.endswith('.txt'): txtFile = _np.loadtxt(_path + fileName) return _LSC.from_list(name, txtFile)
def __init__(self): aggr1=0.2 aggr2 = 0.2 #fitnessCmap=LinearSegmentedColormap.from_list('fitness_map',[(aggr1,1,aggr1),(1,1,aggr1),(1,aggr1,aggr1)]) fitnessCmap = LinearSegmentedColormap.from_list('fitness_map',[(0, 1-aggr1, 0), (1-aggr1, 1-aggr1, 0), (1-aggr1, 0, 0)]) #complexityCmap = LinearSegmentedColormap.from_list('complexity_map', [(1,1,1),(aggr2, 1, 1), (aggr2,aggr2,1),(aggr2, aggr2, aggr2)]) complexityCmap = LinearSegmentedColormap.from_list('complexity_map',[(0.6, 0.6, 0.9),(0, 0, 0.3)]) self.complexity = complexityCmap#plt.get_cmap("cool") self.globalm = fitnessCmap self.localm = fitnessCmap#plt.get_cmap("RdYlGn")
def newgray(): """ Modified version of Oranges.""" oranges = cm.get_cmap("gray", 100) array = oranges(np.arange(100)) array = array[40:] cmap = LinearSegmentedColormap.from_list("newgray", array) cm.register_cmap(name='newgray', cmap=cmap) array = array[::-1] cmap = LinearSegmentedColormap.from_list("newgray_r", array) cm.register_cmap(name='newgray_r', cmap=cmap) return
def pl_hess_diag( gs, gs_y1, gs_y2, x_min_cmd, x_max_cmd, y_min_cmd, y_max_cmd, x_ax, y_ax, lkl_method, hess_xedges, hess_yedges, hess_x, hess_y, HD): """ Hess diagram of observed minus best match synthetic cluster. """ ax = plt.subplot(gs[gs_y1:gs_y2, 2:4]) # Set plot limits plt.xlim(x_min_cmd, x_max_cmd) plt.ylim(y_min_cmd, y_max_cmd) # Set axis labels plt.xlabel('$' + x_ax + '$', fontsize=18) # Set minor ticks ax.minorticks_on() ax.xaxis.set_major_locator(MultipleLocator(1.0)) if gs_y1 == 0: ax.set_title("Hess diagram (observed - synthetic)", fontsize=10) for x_ed in hess_xedges: # vertical lines ax.axvline(x_ed, linestyle=':', lw=.8, color='k', zorder=1) for y_ed in hess_yedges: # horizontal lines ax.axhline(y_ed, linestyle=':', lw=.8, color='k', zorder=1) if HD.any(): # Add text box. if HD.min() < 0: plt.scatter(-100., -100., marker='s', lw=0., s=60, c='#0B02F8', label='{}'.format(int(HD.min()))) if HD.max() > 0: plt.scatter(-100., -100., marker='s', lw=0., s=60, c='#FB0605', label='{}'.format(int(HD.max()))) # Define custom colorbar. if HD.min() == 0: cmap = LinearSegmentedColormap.from_list( 'mycmap', [(0, 'white'), (1, 'red')]) else: # Zero point for empty bins which should be colored in white. zero_pt = (0. - HD.min()) / float(HD.max() - HD.min()) N = 256. zero_pt0 = np.floor(zero_pt * (N - 1)) / (N - 1) zero_pt1 = np.ceil(zero_pt * (N - 1)) / (N - 1) cmap = LinearSegmentedColormap.from_list( 'mycmap', [(0, 'blue'), (zero_pt0, 'white'), (zero_pt1, 'white'), (1, 'red')], N=N) ax.pcolormesh(hess_x, hess_y, HD, cmap=cmap, vmin=HD.min(), vmax=HD.max(), zorder=1) # Legend. handles, labels = ax.get_legend_handles_labels() leg = ax.legend( handles, labels, loc='lower right', scatterpoints=1, ncol=2, columnspacing=.2, handletextpad=-.3, fontsize=10) leg.get_frame().set_alpha(0.7)
def temp_style_file(name): """ A context manager for creating an empty style file in the expected path. """ stylelib_path = USER_LIBRARY_PATHS[0] if not os.path.exists(stylelib_path): os.makedirs(stylelib_path) srcname = os.path.abspath(os.path.join(os.path.dirname(__file__),name)) dstname = os.path.join(stylelib_path, os.path.basename(name)) if not os.path.exists(srcname): raise RuntimeError('Cannot use file at "' + srcname + '". This file does not exist.') if os.path.exists(dstname): #raise RuntimeError('Cannot create a temporary file at "' + dstname + '". This file exists already.') warnings.warn('Overwriting the temporary file at "' + dstname + '".') #with open(filename, 'w'): # pass shutil.copy2(srcname, dstname) rgb = [ ( 0./255. , 0./255. , 0./255.), ( 0./255. , 102./255. , 51./255.), #(114./255. , 121./255. , 126./255.), ( 91./255. , 172./255. , 38./255.), (217./255. , 220./255. , 222./255.), (255./255. , 255./255. , 255./255.) ] # create map and register it together with reversed colours maps = [] maps.append(LinearSegmentedColormap.from_list('IPU' , rgb)) maps.append(LinearSegmentedColormap.from_list('IPU_r', rgb[::-1])) for cmap in maps: mplcm.register_cmap(cmap=cmap) #self._color_maps[cmap.name] = cmap yield os.remove(dstname) #print('# styles available:', len(plt.style.available)) # #with temp_style_file('dummy.mplstyle'): # print('# before reload:', len(plt.style.available)) # # plt.style.reload_library() # print('# after reload:', len(plt.style.available))
def custom_div_cmap(numcolors=11, name='custom_div_cmap', mincol='r', midcol='white', maxcol='g'): from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list(name=name, colors =[mincol, midcol, maxcol], N=numcolors) return cmap
def get_colors(N=256, N_discrete=9): """Return colorbrewer's Set1 colors and a colormap similar to MATLAB's 'parula' colormap. Returns: -------- colors: list parula: list parula_discrete: list """ colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors rgb = [[0.20784314, 0.16470588, 0.52941176], [0.01176471, 0.38823529, 0.88235294], [0.07843137, 0.52156863, 0.83137255], [0.02352941, 0.65490196, 0.77647059], [0.21960784, 0.72549020, 0.61960784], [0.57254902, 0.74901961, 0.45098039], [0.85098039, 0.72941176, 0.33725490], [0.98823529, 0.80784314, 0.18039216], [0.97647059, 0.98431373, 0.05490196]] parula = LinearSegmentedColormap.from_list('parula', rgb, N=N) parula_discrete = ListedColormap(rgb, name='parula_discrete', N=N_discrete) for cmap in (parula, parula_discrete): matplotlib.cm.register_cmap(cmap=cmap) return colors, parula, parula_discrete
def make_thresholded_slices(regions, colors, display_mode='z', overplot=True, binarize=True, **kwargs): """ Plots on axial slices numerous images regions: Nibabel images colors: List of colors (rgb tuples) overplot: Overlay images? binarize: Binarize images or plot full stat maps """ from matplotlib.colors import LinearSegmentedColormap from nilearn import plotting as niplt if binarize: for reg in regions: reg.get_data()[reg.get_data().nonzero()] = 1 for i, reg in enumerate(regions): reg_color = LinearSegmentedColormap.from_list('reg1', [colors[i], colors[i]]) if i == 0: plot = niplt.plot_stat_map(reg, draw_cross=False, display_mode=display_mode, cmap = reg_color, alpha=0.9, colorbar=False, **kwargs) else: if overplot: plot.add_overlay(reg, cmap = reg_color, alpha=.72) else: plt.plot_stat_map(reg, draw_cross=False, display_mode=display_mode, cmap = reg_color, colorbar=False, **kwargs) return plot
def get_color_map(num_states): colours = plt.cm.viridis(np.linspace(0, 1, num_states)) colormap = {i: colours[i] for i in range(num_states)} cmap = LinearSegmentedColormap.from_list('name', list(colormap.values()), num_states) return colormap, cmap
def generate_cmap(colors): values = range(len(colors)) vmax = np.ceil(np.max(values)) color_list = [] for v, c in zip(values, colors): color_list.append( ( v/ vmax, c) ) return LinearSegmentedColormap.from_list('custom_cmap', color_list)
def plot_confusion_matrix(model_name, conf_matrix, labels, save, cmap, graph_fn='cfm.png'): startcolor = '#cccccc' midcolor = '#08519c' endcolor = '#08306b' b_g2 = LinearSegmentedColormap.from_list('B_G2', [startcolor, midcolor, endcolor]) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(conf_matrix, cmap=b_g2) fig.colorbar(cax) plt.title('Jeeves Confusion Matrix \n', fontsize=16) ax.set_xticklabels([''] + labels, fontsize=13) ax.set_yticklabels([''] + labels, fontsize=13) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') spines_to_remove = ['top', 'right', 'left', 'bottom'] # for spine in spines_to_remove: # ax.spines[spine].set_visible(False) plt.xlabel('Predicted', fontsize=14) plt.ylabel('Actual', fontsize=14) if save: plt.savefig(os.path.join(graph_dir, graph_fn)) plt.show()
def swap_colors(json_file_path): ''' Switches out color ramp in meta.json files. Uses custom color ramp if provided and valid; otherwise falls back to nextstrain default colors. N.B.: Modifies json in place and writes to original file path. ''' j = json.load(open(json_file_path, 'r')) color_options = j['color_options'] for k,v in color_options.items(): if 'color_map' in v: categories, colors = zip(*v['color_map']) ## Use custom colors if provided AND present for all categories in the dataset if custom_colors and all([category in custom_colors for category in categories]): colors = [ custom_colors[category] for category in categories ] ## Expand the color palette if we have too many categories elif len(categories) > len(default_colors): from matplotlib.colors import LinearSegmentedColormap, to_hex from numpy import linspace expanded_cmap = LinearSegmentedColormap.from_list('expanded_cmap', default_colors[-1], N=len(categories)) discrete_colors = [expanded_cmap(i) for i in linspace(0,1,len(categories))] colors = [to_hex(c).upper() for c in discrete_colors] else: ## Falls back to default nextstrain colors colors = default_colors[len(categories)] # based on how many categories are present; keeps original ordering j['color_options'][k]['color_map'] = map(list, zip(categories, colors)) json.dump(j, open(json_file_path, 'w'), indent=1)
def _init_mutable_colormap(): """Create a matplotlib colormap that will be updated by the widgets.""" greys = color_palette("Greys", 256) cmap = LinearSegmentedColormap.from_list("interactive", greys) cmap._init() cmap._set_extremes() return cmap
def heatmap(cea, synchronous=True): data = cea.grid.get_heat_data() fig, ax = plt.subplots() cmap = LinearSegmentedColormap.from_list('my cmap', ['black', 'white']) heatmap_plot = ax.imshow(data, interpolation='nearest', cmap=cmap, vmin=0, vmax=1.0) def init(): heatmap_plot.set_data(cea.grid.get_heat_data()) return heatmap_plot def animate(i): if i > 2: cea.iterate_population() if synchronous else cea.iterate_individual() heatmap_plot.set_data(cea.grid.get_heat_data()) return heatmap anim = animation.FuncAnimation(fig, animate, init_func=init, frames=150) plt.axis('off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) anim.save('gifs/slash_final.gif', writer='imagemagick') plt.show()
def heat_map(self, cmap="RdYlGn", vmin=None, vmax=None, font_cmap=None): if cmap is None: carr = ["#d7191c", "#fdae61", "#ffffff", "#a6d96a", "#1a9641"] cmap = LinearSegmentedColormap.from_list("default-heatmap", carr) if isinstance(cmap, str): cmap = get_cmap(cmap) if isinstance(font_cmap, str): font_cmap = get_cmap(font_cmap) vals = self.actual_values.astype(float) if vmin is None: vmin = vals.min().min() if vmax is None: vmax = vals.max().max() norm = (vals - vmin) / (vmax - vmin) for ridx in range(self.nrows): for cidx in range(self.ncols): v = norm.iloc[ridx, cidx] if np.isnan(v): continue color = cmap(v) hex = rgb2hex(color) styles = {"BACKGROUND": HexColor(hex)} if font_cmap is not None: styles["TEXTCOLOR"] = HexColor(rgb2hex(font_cmap(v))) self.iloc[ridx, cidx].apply_styles(styles) return self
def green_lightblue_blue(levels=10): """ Generate a colormap from green to light blue then dark blue. """ colors =[(0., 1., 0.), (0., 1., 1.), (0., 0., 1.)] return LinearSegmentedColormap.from_list(colors=colors, name='green_lightblue_blue', N=levels)
def plot_confusion_matrix(conf_matrix, cm_labels): startcolor = "#cccccc" midcolor = "#08519c" endcolor = "#08306b" b_g2 = LinearSegmentedColormap.from_list("B_G2", [startcolor, midcolor, endcolor]) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(conf_matrix, cmap=b_g2) fig.colorbar(cax) plt.title("Neural Net Confusion Matrix \n", fontsize=16) ax.set_xticklabels([""] + cm_labels, fontsize=13) ax.set_yticklabels([""] + cm_labels, fontsize=13) ax.xaxis.set_ticks_position("none") ax.yaxis.set_ticks_position("none") spines_to_remove = ["top", "right", "left", "bottom"] plt.xlabel("Predicted", fontsize=14) plt.ylabel("Actual", fontsize=14) # plt.savefig(os.path.join(graph_dir, graph_fn)) plt.show()
def like2d(datx,daty,weights=None, nbins=15, which=[.68,.95], range=None, filled=True, color=None, cmap=None, smooth=None, ax=None, **kwargs): from matplotlib.pyplot import gca, get_cmap from matplotlib.mlab import movavg from matplotlib.colors import LinearSegmentedColormap from scipy.ndimage import gaussian_filter if ax is None: ax = gca() if weights is None: weights=ones(len(datx)) if color is None: color = kwargs.pop('c') if 'c' in kwargs else 'b' H,xe,ye = histogram2d(datx,daty,nbins,weights=weights, range=range) xem, yem = movavg(xe,2), movavg(ye,2) kwargs = dict(levels=confint2d(H, sorted(which)[::-1]+[0]),**kwargs) if smooth: H = gaussian_filter(H,smooth) args = (xem,yem,transpose(H)) if cmap is None: cmap = {'b':'Blues', 'g':'Greens', 'r':'Reds', 'orange':'Oranges', 'grey':'Greys'}.get(color) if cmap is None: cmap = LinearSegmentedColormap.from_list(None,['w',color]) else: cmap = get_cmap(cmap) if filled: ax.contourf(*args,cmap=cmap,**kwargs) ax.contour(*args,colors=color,**kwargs)
def get_with_white_added(cm_name_default, white_start=0.0, white_end=0.1, ncolors_out=100): cmap = cm.get_cmap(cm_name_default) ncolors = cmap.N clist = [] lower = [] if white_start > 0: lower = cmap(np.linspace(0, white_start, int(white_start * ncolors))) clist.append(lower) white = np.ones((int((white_end - white_start) * ncolors), 4)) clist.append(white) upper = [] if white_end < 1: upper = cmap(np.linspace(white_end, 1, int((1 - white_end) * ncolors))) clist.append(upper) colors = np.vstack(tuple([p for p in clist if len(p) > 0])) return LinearSegmentedColormap.from_list("mycmap", colors, N=ncolors_out)
def heat_map(self, cmap='RdYlGn', vmin=None, vmax=None, font_cmap=None): if cmap is None: carr = ['#d7191c', '#fdae61', '#ffffff', '#a6d96a', '#1a9641'] cmap = LinearSegmentedColormap.from_list('default-heatmap', carr) if isinstance(cmap, basestring): cmap = get_cmap(cmap) if isinstance(font_cmap, basestring): font_cmap = get_cmap(font_cmap) vals = self.actual_values.astype(float) if vmin is None: vmin = vals.min().min() if vmax is None: vmax = vals.max().max() norm = (vals - vmin) / (vmax - vmin) for ridx in range(self.nrows): for cidx in range(self.ncols): v = norm.iloc[ridx, cidx] if np.isnan(v): continue color = cmap(v) hex = rgb2hex(color) styles = {'BACKGROUND': HexColor(hex)} if font_cmap is not None: styles['TEXTCOLOR'] = HexColor(rgb2hex(font_cmap(v))) self.iloc[ridx, cidx].apply_styles(styles) return self
def plotBackground(areaPoly=None, ax=None, globalOrigin=None): """ plots the background from the tiff-file given. In the future, maybe data is taken from google maps or something similar? #local coordinates in areaPoly, with origin in origin origin is given in sweref99 coordinates, not local. """ if not areaPoly: raise Exception('need area polygon in order to plot background') if not ax: fig=plt.figure() ax=fig.add_subplot(111, aspect='equal') figCorner=(595000, 6725000) #for this specific area, not general if not globalOrigin: globalOrigin=figCorner #now, let our global origin be in the origin.. w=5000 #for this specific image.. h=5000 figorigin=np.array(figCorner)-np.array(globalOrigin) limits=[figorigin[0], figorigin[0]+w, figorigin[1], figorigin[1]+h] folder=os.path.dirname(os.path.abspath(__file__)) folder=os.path.join(folder, 'GIS') map=LinearSegmentedColormap.from_list('lightgray', ['#666666', '#C5C5C5']) #our own cmap bg=mpimg.imread(os.path.join(folder,'672_59_11.tif')) im = plt.imshow(bg, cmap=map,origin='lower', extent=limits) #now, adjust to our polygon.. limits=list(fun.polygonLim(areaPoly)) w=max(10, max(limits)/10.) limits[0]-=w #to get some space to polygon limits[1]+=w limits[2]-=w limits[3]+=w ax.axis(limits) return ax
def plot_colorblock(values, vmin=0, vmax=1, nColors=12, colors=[(0.75, 0.15, 0.15), (1, 0.75, 0.15), (0.15, 0.75, 0.15)]): """ Create a colorblock figure. Default color scheme is red to yellow to green with 12 colors. This function can be used to generate dashboards with simple color indicators in each cell. Parameters ----------- values : 2D np.array Values to plot in the colorblock vmin : float (optional) Colomap minimum, default = 0 vmax : float (optional) Colomap maximum, default = 1 num_colors : int (optional) Number of colors in the colormap colors : list (optional) List of colors, colors can be specified in any way understandable by matplotlib.colors.ColorConverter.to_rgb(). Default is red to yellow to green. """ from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list(name='custom', colors = colors, N=nColors) fig = plt.imshow(values, cmap=cmap, aspect='equal', vmin=vmin, vmax=vmax) plt.axis('off') fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False)
def green_white(levels=10): """ Generate a colormap from green to white. """ colors =[(0., 0.5, 0.), (1., 1., 1.)] return LinearSegmentedColormap.from_list(colors=colors, name='green_white', N=levels)
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): """ Truncates a colourmap. Parameters ---------- cmap : `matplotlib.colors.LinearSegmentedColormap` Input colourmap. minval, maxval : float Interval to sample (minval >= 0, maxval <= 1) n : int Sampling density. Returns ------- new_cmap : `matplotlib.colors.LinearSegmentedColormap` Truncated colourmap. """ new_cmap = LinearSegmentedColormap.from_list( "trunc({n},{a:.2f},{b:.2f})".format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n)) ) return new_cmap
def set_binary_lut(mayavi_obj, color1, color2, use_vector_lut=False): ''' sets the lookup table to of the mayavi object provided to a 2 color color map ranging between color1 and color2. Also sets the appropriate attributes of the LUT so that the scalars are immediately displayed Parameters ---------- mayavi_obj : Instance(mlab.pipeline) A mayavi object with a module_manager instance color1 : 3-tuple An RGB color represented as a 3-tuple with values [0,1], and corresponding to the scalar value 0 color2 : 3-tuple An RGB color represented as a 3-tuple with values [0,1], and corresponding to the scalar value 1 use_vector_lut : Bool If true, uses the vector_lut_manager. Otherwise, uses the scalar_lut_manager. Defaults to False. ''' mayavi_obj.actor.mapper.scalar_visibility = True if use_vector_lut: lut_mgr=mayavi_obj.module_manager.vector_lut_manager else: lut_mgr=mayavi_obj.module_manager.scalar_lut_manager lut_mgr.lut.table = map_to_table( LinearSegmentedColormap.from_list('ign', [color1, color2])) #map(mayavi2vtk_color, [color1, color2]))) #lut_mgr.use_default_range = False lut_mgr.data_range = [0,1]
def blank_topo(in_ax, info): ''' create a blank headplot ''' topo = np.empty(61) cmap = LinearSegmentedColormap.from_list('mycmap', ['white', 'white']) ax, im, cn, pos_x, pos_y = plot_topomap(topo, info, cmap=cmap, contours=0, axes=in_ax, show=False) return ax, im, cn, pos_x, pos_y
def green_yellow_red(levels=10): """ Generate a colormap from green to yellow then red. """ colors =[(0., 0.5, 0.), (1., 1., 0.), (1, 0., 0.)] return LinearSegmentedColormap.from_list(name='green_yellow_red', colors=colors, N=levels)
def purple_grey_green(N=256, reverse=False): cols = ['#46005f', '#ba00ff', '#ff64d0', '#f0b3cb', '#ececec', '#aee28f', '#0bb337', '#004d0d', '#001e0f'] if reverse: cols = cols[::-1] return LinearSegmentedColormap.from_list('custom', cols, N)
# Read in original d files in order to plot pressure isobars dfileloc=(dir_dfile_op+'/d01_'+dttf.strftime("%Y%m%d%H")+'00_psl') data2=xr.open_dataset(dfileloc) # plot rainrate print ('plotting RAIN and pressure') out_path=(pngjson_out_dir+'/'+pngfilename) conv_out_path=(pngjson_out_dir+'/'+convfilename) fig=plt.figure(figsize=(tilesize/dpi, tilesize/dpi), dpi=dpi) ax=fig.add_subplot(111, projection=ccrs.Mercator()) bounds=[0, 0.1, 0.3, 0.5, 0.7, 1.0, 2.0, 3.0, 6.0, 12.0] lev_range=np.array(bounds) levels=lev_range palette=['w', 'lightcyan', 'paleturquoise', 'turquoise', 'lightskyblue', 'royalblue', 'orange', 'orangered', 'firebrick', 'darkmagenta'] cm=LinearSegmentedColormap.from_list('palette', palette, N=len(palette)) cm.set_over('purple') norm = mc.BoundaryNorm(bounds, cm.N) rainfall=rainrate[i] cs=ax.contourf(LON, LAT, rainfall[0,:,:], levels, cmap=cm, norm=norm, transform=ccrs.PlateCarree()) plt.box(on=None) plt.subplots_adjust(bottom=0, left=0, right=1, top=1, hspace = 0, wspace = 0) #ax.coastlines('10m', linewidth=0.15) plt.axis('off') ax.figsize=(tilesize/dpi, tilesize/dpi) ax.dpi=dpi ax.outline_patch.set_visible(False) ax.background_patch.set_visible(False) ax.patch.set_alpha(0) #ax.add_feature(cfeature.BORDERS,linewidth=0.25) ax.axes.get_xaxis().set_visible(False)
[0.36271, 0.31986, 0.53684], [0.36617, 0.31411, 0.52917], [0.36961, 0.30852, 0.52148], [0.37306, 0.30306, 0.51382], [0.37652, 0.2978, 0.50615], [0.37994, 0.29269, 0.49854], [0.38336, 0.28775, 0.49094], [0.38674, 0.28301, 0.48337], [0.39011, 0.27842, 0.47586], [0.39346, 0.27401, 0.4684], [0.39677, 0.26978, 0.461], [0.40006, 0.26573, 0.45366], [0.40333, 0.26185, 0.4464], [0.40655, 0.25815, 0.43921], [0.40974, 0.25466, 0.43212], [0.4129, 0.25132, 0.42509], [0.41602, 0.24817, 0.41813], [0.41912, 0.24515, 0.41128], [0.42218, 0.24235, 0.40451], [0.42522, 0.23972, 0.39784], [0.42823, 0.23728, 0.39126], [0.43121, 0.23498, 0.38475], [0.43415, 0.23282, 0.37836], [0.43708, 0.23086, 0.37204], [0.43998, 0.22907, 0.36583], [0.44286, 0.22743, 0.3597], [0.44571, 0.22596, 0.35366], [0.44855, 0.2246, 0.34773]] romaO_map = LinearSegmentedColormap.from_list('romaO', cm_data) # For use of "viscm view" test_cm = romaO_map if __name__ == "__main__": import matplotlib.pyplot as plt import numpy as np try: from viscm import viscm viscm(romaO_map) except ImportError: print("viscm not found, falling back on simple display") plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=romaO_map)
from sklearn import datasets iris = datasets.load_iris() X_train = iris.data[:, 2:4] y_train = iris.target ### COVARIANVE TYPE = full, spherical,diag,tied mix = mixture.GMM(n_components=3, covariance_type='spherical') mix.fit(X_train) print(mix.means_) cc = mix.predict(X_train) from matplotlib.colors import LinearSegmentedColormap colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] cm = LinearSegmentedColormap.from_list(cc, colors, N=3) colors2 = [(1, 0, 0), (0, 0, 1), (0, 1, 0)] cm2 = LinearSegmentedColormap.from_list(y_train, colors2, N=3) cc2 = y_train fig = plt.figure(figsize=(10, 5)) plt.subplot2grid((1, 2), (0, 0)) plt.title('CLASSES') plt.scatter(X_train[:, 0], X_train[:, 1], c=cc, cmap=cm, alpha=0.8) plt.xlabel('Petal Length') plt.ylabel('Petal Width') plt.subplot2grid((1, 2), (0, 1), rowspan=1, colspan=2) plt.title('PREDICTED CLASSES MIXTURE MODEL') plt.scatter(X_train[:, 0], X_train[:, 1], c=cc2, cmap=cm2, alpha=0.8) plt.xlabel('Petal Length')
L_impact_N1_l1[j, i] = gmax blue_div = np.array([61 / 255, 139 / 255, 240 / 255]) blue = np.array([67 / 255, 114 / 255, 189 / 255]) red = np.array([146 / 255, 64 / 255, 79 / 255]) red = np.array([159 / 255, 58 / 255, 65 / 255]) n = 11 L = [] for i in range(n): if i < n / gmax: a = int(n / gmax) c = (a - i) / a * red + i / a * blue L.append(c) else: a = int(n / gmax) b = int(n) c = (b - i) / (b - a) * blue + (i - a) / (b - a) * blue_div L.append(c) cm = LinearSegmentedColormap.from_list( 'cmap', L, N=n) plt.figure() plt.imshow(L_impact_N1_l1, extent=[0, 25, 0, 1], aspect=25, origin='lower', cmap=cm, vmin=0, vmax=2) plt.colorbar(label=r"$|\overline{t}^*-\overline{t}'|$") plt.xlabel(r'density ($N$)') plt.ylabel(r"defence ($\lambda$)") plt.title(r'$c_{RI} = $' + str(cri)) plt.tight_layout()
def plot(self): '''Method for generating a graphic of the grid structure of the BIM. Returns: (`matplotlib.figure.Figure`): object with the matplotlib structure\ of the plot. You might use it to save the figure for example. Examples: >>> from numpy import array >>> from pybimstab.bim import BlocksInMatrix >>> slopeCoords = array([[0, 1, 1, 0, 0], [0, 0, 1, 1, 0]]) >>> bim = BlocksInMatrix(slopeCoords=slopeCoords, blockProp=0.5, >>> tileSize=0.1, seed=123) >>> fig = bim.plot() .. figure:: https://rawgit.com/eamontoyaa/pybimstab/master/examples/figures/bim_example1.svg :alt: bim_example1 .. only:: html :download:`example script<../examples/figuresScripts/bim_example1.py>`. >>> from pybimstab.slope import AnthropicSlope >>> from pybimstab.bim import BlocksInMatrix >>> slope = AnthropicSlope(slopeHeight=12, slopeDip=[1, 1.5], >>> crownDist=10, toeDist=10) >>> bim = BlocksInMatrix(slopeCoords=slope.coords, blockProp=0.2, >>> tileSize=0.25, seed=123) >>> fig = bim.plot() .. figure:: https://rawgit.com/eamontoyaa/pybimstab/master/examples/figures/bim_example2.svg :alt: bim_example2 .. only:: html :download:`example script<../examples/figuresScripts/bim_example2.py>`. fig = bim.plot() >>> from numpy import array >>> from pybimstab.slope import NaturalSlope >>> from pybimstab.bim import BlocksInMatrix >>> terrainCoords = array( >>> [[-2.49, 0.1 , 1.7 , 3.89, 5.9 , 8.12, 9.87, 13.29, 20.29, >>> 21.43, 22.28, 23.48, 24.65, 25.17], >>> [18.16, 17.88, 17.28, 15.73, 14.31, 13.58, 13, 3.61, 3.61, >>> 3.32, 2.71, 2.23, 1.21, 0.25]]) >>> slope = NaturalSlope(terrainCoords) >>> bim = BlocksInMatrix(slopeCoords=slope.coords, blockProp=0.25, >>> tileSize=0.4, seed=123) >>> fig = bim.plot() .. figure:: https://rawgit.com/eamontoyaa/pybimstab/master/examples/figures/bim_example3.svg :alt: bim_example3 .. only:: html :download:`example script<../examples/figuresScripts/bim_example3.py>`. ''' import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import LinearSegmentedColormap as newcmap # Variables to control the color map and its legend if np.any(self.grid == -1): cmap = newcmap.from_list('BIMcmap', ['white', 'lightgray', 'black'], 3) ticks = [-1 + 0.333, 0, 1 - 0.333] ticksLabels = ['None', 'Matrix', 'Blocks'] else: cmap = newcmap.from_list('BIMcmap', ['lightgray', 'black'], 2) ticks = [0.25, 0.75] ticksLabels = ['Matrix', 'Blocks'] # Plot body fig = plt.figure() ax = fig.add_subplot(111) bar = ax.pcolormesh(self.xCells, self.yCells, self.grid, cmap=cmap) ax.plot(self.slopeCoords[0], self.slopeCoords[1], '-k') # Configuring the colorbar bar = plt.colorbar(bar, ax=ax, ticks=ticks, pad=0.005, shrink=0.15, aspect=3) bar.ax.set_yticklabels(ticksLabels, fontsize='small') # Plot settings ax.set_aspect(1) ax.grid(True, ls='--', lw=0.5) ax.grid(True, ls='--', lw=0.5) ax.set_xlim( (self.slopeCoords[0].min() - 0.02 * self.slopeCoords[0].max(), 1.02 * self.slopeCoords[0].max())) ax.set_ylim( (self.slopeCoords[1].min() - 0.02 * self.slopeCoords[1].max(), 1.02 * self.slopeCoords[1].max())) fig.tight_layout() return fig
Guest = Palette() Guest.purple = Color('purple', (162, 128, 185)) Guest.blue = Color('blue', (96, 193, 207)) Guest.green = Color('green', (121, 191, 130)) Guest.yellow = Color('yellow', (243, 195, 84)) Guest.orange = Color('orange', (249, 143, 96)) Guest.red = Color('red', (237, 88, 111)) Guest.gray = Color('gray', (144, 145, 142)) RGBn['Guest'] = [ Guest.red.RGBn, Guest.purple.RGBn, Guest.blue.RGBn, Guest.green.RGBn, Guest.yellow.RGBn ] palettes['Guest'] = Guest colormaps['Guest'] = LSC.from_list('Guest', RGBn['Guest']) # # If want to anchor color at a specific point # colormaps['Guest'] = LSC.from_list('Guest', list(zip([0, 0.2, 0.4, 0.6, 1], RGBn['Guest']))) # CABBI colors CABBI = Palette() CABBI.feedstock = Color('feedstock', (45, 130, 63)) CABBI.conversion = Color('conversion', (243, 195, 84)) CABBI.sustainability = Color('sustainability', (21, 145, 118)) CABBI.green_light = Color('green_light', fg=(142, 173, 62)) CABBI.green_dark = Color('green_dark', fg=(0, 127, 61), bg=(59, 164, 89)) CABBI.yellow = Color('yellow', fg=(252, 184, 19), bg=(255, 221, 80)) CABBI.blue_light = Color('blue_light', fg=(0, 169, 150), bg=(178, 224, 229))
def plot_surf(surf_mesh, surf_map=None, bg_map=None, hemi='left', view='lateral', cmap=None, colorbar=False, avg_method='mean', threshold=None, alpha='auto', bg_on_data=False, darkness=1, vmin=None, vmax=None, cbar_vmin=None, cbar_vmax=None, title=None, output_file=None, axes=None, figure=None, midpoint=None, dist=6.5, **kwargs): """ Plotting of surfaces with optional background and data .. versionadded:: 0.3 Parameters ---------- surf_mesh: str or list of two numpy.ndarray Surface mesh geometry, can be a file (valid formats are .gii or Freesurfer specific files such as .orig, .pial, .sphere, .white, .inflated) or a list of two Numpy arrays, the first containing the x-y-z coordinates of the mesh vertices, the second containing the indices (into coords) of the mesh faces. surf_map: str or numpy.ndarray, optional. Data to be displayed on the surface mesh. Can be a file (valid formats are .gii, .mgz, .nii, .nii.gz, or Freesurfer specific files such as .thickness, .curv, .sulc, .annot, .label) or a Numpy array with a value for each vertex of the surf_mesh. bg_map: Surface data object (to be defined), optional, Background image to be plotted on the mesh underneath the surf_data in greyscale, most likely a sulcal depth map for realistic shading. hemi : {'left', 'right'}, default is 'left' Hemisphere to display. view: {'lateral', 'medial', 'dorsal', 'ventral', 'anterior', 'posterior'}, default is 'lateral' View of the surface that is rendered. cmap: matplotlib colormap, str or colormap object, default is None To use for plotting of the stat_map. Either a string which is a name of a matplotlib colormap, or a matplotlib colormap object. If None, matplotlib default will be chosen colorbar : bool, optional, default is False If True, a colorbar of surf_map is displayed. avg_method: {'mean', 'median'}, default is 'mean' How to average vertex values to derive the face value, mean results in smooth, median in sharp boundaries. threshold : a number or None, default is None. If None is given, the image is not thresholded. If a number is given, it is used to threshold the image, values below the threshold (in absolute value) are plotted as transparent. alpha: float, alpha level of the mesh (not surf_data), default 'auto' If 'auto' is chosen, alpha will default to .5 when no bg_map is passed and to 1 if a bg_map is passed. bg_on_data: bool, default is False If True, and a bg_map is specified, the surf_data data is multiplied by the background image, so that e.g. sulcal depth is visible beneath the surf_data. NOTE: that this non-uniformly changes the surf_data values according to e.g the sulcal depth. darkness: float, between 0 and 1, default is 1 Specifying the darkness of the background image. 1 indicates that the original values of the background are used. .5 indicates the background values are reduced by half before being applied. vmin, vmax: lower / upper bound to plot surf_data values If None , the values will be set to min/max of the data title : str, optional Figure title. output_file: str, or None, optional The name of an image file to export plot to. Valid extensions are .png, .pdf, .svg. If output_file is not None, the plot is saved to a file, and the display is closed. axes: instance of matplotlib axes, None, optional The axes instance to plot to. The projection must be '3d' (e.g., `figure, axes = plt.subplots(subplot_kw={'projection': '3d'})`, where axes should be passed.). If None, a new axes is created. figure: instance of matplotlib figure, None, optional The figure instance to plot to. If None, a new figure is created. See Also -------- nilearn.datasets.fetch_surf_fsaverage : For surface data object to be used as background map for this plotting function. nilearn.plotting.plot_surf_roi : For plotting statistical maps on brain surfaces. nilearn.plotting.plot_surf_stat_map : for plotting statistical maps on brain surfaces. """ # load mesh and derive axes limits mesh = load_surf_mesh(surf_mesh) coords, faces = mesh[0], mesh[1] limits = [coords.min(), coords.max()] # set view if hemi == 'right': if view == 'lateral': elev, azim = 0, 0 elif view == 'medial': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 elif len(view) == 2: elev, azim = view else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') elif hemi == 'left': if view == 'medial': elev, azim = 0, 0 elif view == 'lateral': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 elif len(view) == 2: elev, azim = view else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') else: raise ValueError('hemi must be one of right or left') # set alpha if in auto mode if alpha == 'auto': if bg_map is None: alpha = .5 else: alpha = 1 # if no cmap is given, set to matplotlib default if cmap is None: cmap = plt.cm.get_cmap(plt.rcParamsDefault['image.cmap']) else: # if cmap is given as string, translate to matplotlib cmap if isinstance(cmap, str): cmap = plt.cm.get_cmap(cmap) # initiate figure and 3d axes if axes is None: if figure is None: figure = plt.figure() axes = Axes3D(figure, rect=[0, 0, 1, 1], xlim=limits, ylim=limits) else: if figure is None: figure = axes.get_figure() axes.set_xlim(*limits) axes.set_ylim(*limits) axes.view_init(elev=elev, azim=azim) axes.set_axis_off() # plot mesh without data p3dcollec = axes.plot_trisurf(coords[:, 0], coords[:, 1], coords[:, 2], triangles=faces, linewidth=0., antialiased=False, color='white') # reduce viewing distance to remove space around mesh axes.dist = dist # set_facecolors function of Poly3DCollection is used as passing the # facecolors argument to plot_trisurf does not seem to work face_colors = np.ones((faces.shape[0], 4)) if bg_map is None: bg_data = np.ones(coords.shape[0]) * 0.5 else: bg_data = load_surf_data(bg_map) if bg_data.shape[0] != coords.shape[0]: raise ValueError('The bg_map does not have the same number ' 'of vertices as the mesh.') bg_faces = np.mean(bg_data[faces], axis=1) if bg_faces.min() != bg_faces.max(): bg_faces = bg_faces - bg_faces.min() bg_faces = bg_faces / bg_faces.max() # control background darkness bg_faces *= darkness face_colors = plt.cm.gray_r(bg_faces) # modify alpha values of background face_colors[:, 3] = alpha * face_colors[:, 3] # should it be possible to modify alpha of surf data as well? if surf_map is not None: surf_map_data = load_surf_data(surf_map) if len(surf_map_data.shape) is not 1: raise ValueError('surf_map can only have one dimension but has' '%i dimensions' % len(surf_map_data.shape)) if surf_map_data.shape[0] != coords.shape[0]: raise ValueError('The surf_map does not have the same number ' 'of vertices as the mesh.') # create face values from vertex values by selected avg methods if avg_method == 'mean': surf_map_faces = np.mean(surf_map_data[faces], axis=1) elif avg_method == 'median': surf_map_faces = np.median(surf_map_data[faces], axis=1) # if no vmin/vmax are passed figure them out from data if vmin is None: vmin = np.nanmin(surf_map_faces) if vmax is None: vmax = np.nanmax(surf_map_faces) # treshold if indicated if threshold is None: kept_indices = np.arange(surf_map_faces.shape[0]) else: kept_indices = np.where(np.abs(surf_map_faces) >= threshold)[0] if midpoint is None: surf_map_faces = surf_map_faces - vmin surf_map_faces = surf_map_faces / (vmax - vmin) norm_object = None else: norm_object = MidpointNormalize(midpoint=midpoint, vmin=vmin, vmax=vmax) surf_map_faces = norm_object.__call__(surf_map_faces).data # multiply data with background if indicated if bg_on_data: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices])\ * face_colors[kept_indices] else: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices]) if colorbar: our_cmap = get_cmap(cmap) if midpoint is None: norm = Normalize(vmin=vmin, vmax=vmax) else: norm = norm_object nb_ticks = 5 ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, our_cmap.N) if threshold is not None: cmaplist = [our_cmap(i) for i in range(our_cmap.N)] # set colors to grey for absolute values < threshold istart = int(norm(-threshold, clip=True) * (our_cmap.N - 1)) istop = int(norm(threshold, clip=True) * (our_cmap.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.) our_cmap = LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, our_cmap.N) # we need to create a proxy mappable proxy_mappable = ScalarMappable(cmap=our_cmap, norm=norm) proxy_mappable.set_array(surf_map_faces) cax, kw = make_axes(axes, location='right', fraction=.1, shrink=.6, pad=.0) cbar = figure.colorbar(proxy_mappable, cax=cax, ticks=ticks, boundaries=bounds, spacing='proportional', format='%.2g', orientation='vertical') _crop_colorbar(cbar, cbar_vmin, cbar_vmax) p3dcollec.set_facecolors(face_colors) axes.patch.set_alpha(0) if title is not None: axes.set_title(title, position=(.5, .95)) # save figure if output file is given if output_file is not None: figure.savefig(output_file) plt.close(figure) else: return figure, axes, surf_map_faces
def main(inference_type: str = "K", batch_size: int = 1, test_path: str = None, weights: str = None, merge: bool = False, stage: str = "test", limit: int = 20, confidence: float = 0.1, visualize: bool = True): keras_model = MobileDetectNetModel.complete_model() if weights is not None: keras_model.load_weights(weights, by_name=True) images_done = 0 if test_path is not None: import cv2 if stage != 'test': from generator import MobileDetectNetSequence seq = MobileDetectNetSequence.create_augmenter(stage) else: seq = None images_full = [] images_input = [] images_scale = [] for r, d, f in os.walk(test_path): for file in f: image_full = cv2.imread(os.path.join(r, file)) image_input = cv2.resize(image_full, (224, 224)) scale_width = image_full.shape[1] / 224 scale_height = image_full.shape[0] / 224 images_scale.append((scale_width, scale_height)) if stage != 'test': seq_det = seq.to_deterministic() image_aug = (seq_det.augment_image(image_input).astype( np.float32) / 127.5) - 1. else: image_aug = image_input.astype(np.float32) / 127.5 - 1. images_full.append(image_full) images_input.append(image_aug) images_done += 1 if images_done == limit: break if images_done == limit: break x_test = np.array(images_input) else: x_test = np.random.random((limit, 224, 224, 3)) x_cold = np.random.random((batch_size, 224, 224, 3)) if inference_type == 'K': keras_model.predict(x_cold) t0 = time.time() model_outputs = keras_model.predict(x_test) t1 = time.time() elif inference_type == 'TF': tf_engine = keras_model.tf_engine() tf_engine.infer(x_cold) t0 = time.time() model_outputs = tf_engine.infer(x_test) t1 = time.time() elif inference_type == 'FP32': tftrt_engine = keras_model.tftrt_engine(precision='FP32', batch_size=batch_size) tftrt_engine.infer(x_cold) t0 = time.time() model_outputs = tftrt_engine.infer(x_test) t1 = time.time() elif inference_type == 'FP16': tftrt_engine = keras_model.tftrt_engine(precision='FP16', batch_size=batch_size) tftrt_engine.infer(x_cold) t0 = time.time() model_outputs = tftrt_engine.infer(x_test) t1 = time.time() elif inference_type == 'INT8': tftrt_engine = keras_model.tftrt_engine(precision='INT8', batch_size=batch_size) tftrt_engine.infer(x_cold) t0 = time.time() model_outputs = tftrt_engine.infer(x_test) t1 = time.time() else: raise ValueError("Invalid inference type") # MÓDOSÍTOTT txt_file = open("frametimes.txt", "w") print('Time: ', t1 - t0) print('FPS: ', x_test.shape[0] / (t1 - t0)) print('Time*FPS: ', x_test.shape[0]) # MÓDOSÍTOTT txt_file.write("Time: %lf\t" % (t1 - t0)) txt_file.write("\n") txt_file.write("FPS: %lf\t" % (x_test.shape[0] / (t1 - t0))) txt_file.write("\n") txt_file.write("Time*FPS: %lf\t" % x_test.shape[0]) if not visualize: return if len(model_outputs) == 2: classes, bboxes = model_outputs # TF / TensorRT models won't output regions (not useful for production) elif len(model_outputs) == 3: regions, bboxes, classes = model_outputs else: raise ValueError("Invalid model length output") if test_path is not None: import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # get colormap ncolors = 256 color_array = plt.get_cmap('viridis')(range(ncolors)) # change alpha values color_array[:, -1] = np.linspace(0.0, 1.0, ncolors) # create a colormap object map_object = LinearSegmentedColormap.from_list(name='viridis_alpha', colors=color_array) # register this new colormap with matplotlib plt.register_cmap(cmap=map_object) for idx in range(0, len(images_full)): rectangles = [] #MÓDOSÍTOTT confidences = [] print("Valoszinusegek:") for y in range(0, 7): for x in range(0, 7): if classes[idx, y, x, 0] >= confidence: rect = [ int(bboxes[idx, int(y), int(x), 0] * 224), int(bboxes[idx, int(y), int(x), 1] * 224), int(bboxes[idx, int(y), int(x), 2] * 224), int(bboxes[idx, int(y), int(x), 3] * 224) ] rectangles.append(rect) #MÓDOSÍTOTT conf = classes[idx, y, x, 0] confidences.append(conf) print(conf) if merge: rectangles, merges = cv2.groupRectangles(rectangles, 1, eps=0.75) scale_width, scale_height = images_scale[idx] i = 0 for rect in rectangles: cv2.rectangle( images_full[idx], (int(rect[0] * scale_width), int(rect[1] * scale_height)), (int(rect[2] * scale_width), int(rect[3] * scale_height)), (40, 127, 255), 3) #MÓDOSÍTOTT cv2.putText(images_full[idx], str(confidences[i]), (int(((rect[0] + rect[2]) / 2) * scale_width), int(rect[1] * scale_height)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) i = i + 1 plt.imshow(cv2.cvtColor(images_full[idx], cv2.COLOR_BGR2RGB), alpha=1.0, aspect='auto') plt.imshow(cv2.resize(classes[idx].reshape( (7, 7)), (images_full[idx].shape[1], images_full[idx].shape[0])), interpolation='nearest', alpha=0.5, cmap='viridis_alpha', aspect='auto') plt.show() #MÓDOSÍTOTT print(f[idx], 'feldolgozva.\n') #MÓDOSÍTOTT print('Sikeres lefutas.') # MÓDOSÍTOTT txt_file.close()
# these settings enable LaTeX in matplotlib and make the figures pretty import matplotlib.pyplot as plt from matplotlib import rcParams from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator from matplotlib.colors import LinearSegmentedColormap from mpl_toolkits.axes_grid1 import make_axes_locatable colors = [(1, 0, 0), (1, 1, 1), (0, 0, 1)] cm = LinearSegmentedColormap.from_list("my_list", colors) rcParams["figure.dpi"] = 100 rcParams["figure.figsize"] = [6.0, 4.0] rcParams["axes.linewidth"] = 0.5 rcParams["font.size"] = 15.0 axisFace = "#323A48" figureFace = "#323A48" textColor = "#DBE1EA" edgeColor = "#92A2BD" gridColor = "#3F495A" notebook_bg = "#1A2028" yellow = "#FFEC8E" orange = "#ff7f0e" red = "#e17e85" magenta = "#e07a7a" violet = "#be86e3" blue = "#1f77b4" cyan = "#4cb2ff" green = "#61ba86" rcParams["lines.linewidth"] = 1.25
[0.76237342, 0.87642392, 0.13706449], [0.77285183, 0.87786808, 0.13110864], [0.78331535, 0.87928545, 0.12540538], [0.79375994, 0.88067763, 0.12000532], [0.80418159, 0.88204632, 0.11496505], [0.81457634, 0.88339329, 0.11034678], [0.82494028, 0.88472036, 0.10621724], [0.83526959, 0.88602943, 0.10264590], [0.84556056, 0.88732243, 0.09970219], [0.85580960, 0.88860134, 0.09745186], [0.86601325, 0.88986815, 0.09595277], [0.87616824, 0.89112487, 0.09525046], [0.88627146, 0.89237353, 0.09537439], [0.89632002, 0.89361614, 0.09633538], [0.90631121, 0.89485467, 0.09812496], [0.91624212, 0.89609127, 0.10071680], [0.92610579, 0.89732977, 0.10407067], [0.93590444, 0.89857040, 0.10813094], [0.94563626, 0.89981500, 0.11283773], [0.95529972, 0.90106534, 0.11812832], [0.96489353, 0.90232311, 0.12394051], [0.97441665, 0.90358991, 0.13021494], [0.98386829, 0.90486726, 0.13689671], [0.99324789, 0.90615657, 0.14393620]] viridis = LinearSegmentedColormap.from_list('viridis', viridis_data) mpl.cm.register_cmap('viridis', viridis) viridis_data.reverse() viridis_r = LinearSegmentedColormap.from_list('viridis', viridis_data) mpl.cm.register_cmap('viridis', viridis)
from skbio.stats.ordination import pcoa from skbio.stats.distance import anosim ''' depth_colormap = LinearSegmentedColormap.from_list('colorbar', ['#990000','Green','#0A47C2','#420561'],N=4) #p colormap_1 = LinearSegmentedColormap.from_list('colorbar', ['#FFFF99','#efe350ff','#f7cb44ff','#f9b641ff','#f9a242ff',\ '#f68f46ff','#eb8055ff','#de7065ff','#cc6a70ff','#b8627dff','#a65c85ff','#90548bff','#7e4e90ff','#6b4596ff','#593d9cff',\ '#403891ff','#253582ff','#13306dff','#0c2a50ff','#042333ff'], N=10000000) #v colormap_1 = LinearSegmentedColormap.from_list('colorbar', ['#FFFF99','#DCE319FF','#B8DE29FF','#95D840FF','#73D055FF',\ '#55C667FF','#3CBB75FF','#29AF7FFF','#20A387FF','#1F968BFF','#238A8DFF','#287D8EFF','#2D708EFF','#33638DFF','#39568CFF',\ '#404788FF','#453781FF','#482677FF','#481567FF','#440154FF'], N=10000000) ''' region_colormap = LinearSegmentedColormap.from_list('colorbar', [ '#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#e5c494', '#b3b3b3', '#777777' ], N=9) tree = read('om252.nw', format="newick", into=TreeNode) print(tree.ascii_art()) #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*# # all region # #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*# #adiv_faith_pd = alpha_diversity('alpha', data, ids=ids, otu_ids=otu_ids, tree=tree) df = pd.read_csv("tpm.tsv", sep="\t", header=0, index_col=0) #df.to_csv("test1.tsv", sep="\t", header=1) print(df)
from matplotlib.colors import LinearSegmentedColormap as LSC __description__ = 'Gentoo emerge Heatmap Generator' DEFAULT_CSV = 'emerge.csv' DEFAULT_WIDTH = 1280 DEFAULT_HEIGHT = 720 FIGURE_PARAMS = None DEFAULT_RECT = [0.05, 0.1, 0.925, 0.825] # L, B, W, H # from webpage, #62548f = rgb(98, 84, 143) GENTOO_PURPLE1 = '#62548f' GENTOO_PURPLE2 = '#dddaec' GENTOO_PURPLES = np.array([98, 84, 143]) / 255 GENTOO_PURPLES = [[1.0] * 3, GENTOO_PURPLES] GENTOO_PURPLES = LSC.from_list('Gentoo-Purples', GENTOO_PURPLES) LOG_FORMAT = ('%(asctime)s.%(msecs)03d %(levelname)8s ' '%(funcName)s:%(lineno)d: %(message)s') LOG_DATEFMT = '%H:%M:%S' log.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATEFMT, level='DEBUG') # patch and insight for ax.xaxis and footer from: # https://stackoverflow.com/a/17562747/242583 by tacaswell # https://stackoverflow.com/a/30860027/242583 by eric def _blit_draw(self, artists, bg_cache): # Handles blitted drawing, which renders only the artists given instead # of the entire figure. updated_ax = [] for a in artists:
def _set_col_map(col_map_colors): return LinearSegmentedColormap.from_list('color_map', col_map_colors, N=256)
[0.99555225, 0.88285068, 0.2418514], [0.99513763, 0.8884501, 0.23588062], [0.99471252, 0.89405076, 0.2296837], [0.99421873, 0.89968246, 0.2230963], [0.99370185, 0.90532165, 0.21619768], [0.99313786, 0.91098038, 0.2088926], [0.99250707, 0.91666811, 0.20108214], [0.99187888, 0.92235023, 0.19290417], [0.99110991, 0.92809686, 0.18387963], [0.99042108, 0.93379995, 0.17458127], [0.98958484, 0.93956962, 0.16420166], [0.98873988, 0.94533859, 0.15303117], [0.98784836, 0.95112482, 0.14074826], [0.98680727, 0.95697596, 0.12661626]] test_cm = LinearSegmentedColormap.from_list(__file__, cm_data) if __name__ == "__main__": import matplotlib.pyplot as plt import numpy as np try: from viscm import viscm viscm(test_cm) except ImportError: print("viscm not found, falling back on simple display") plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=test_cm) plt.show()
def __init__(self,**args): ### initialize global containers and variables # initialize containers for grid, hazard locations, agent and goal locations, etc., self.grid = [] self.hazards = [] self.agent = [] self.goal = [] self.training_episodes_history_v1 = [] self.training_episodes_history_v2 = [] self.training_start_schedule = [] # container for holding starting positions for traininig self.validation_start_schedule = [] # container for holding starting psoitions for validation self.training_reward_v1 = [] self.training_reward_v2 = [] self.validation_reward_v1 = [] self.validation_reward_v2 = [] # initialize global variables e.g., height and width of gridworld, hazard penalty value self.width = 0 self.height = 0 self.hazard_reward = 0 self.goal_reward = 0 self.standard_reward = -1 self.num_episodes = 0 self.training_episodes = 0 self.validation_epislodes = 0 self.world_size = '' self.world_type = '' # setup world world_name = '' if "world_size" not in args: print 'world_size parameter required, choose either small or large' return if "world_type" not in args: print 'world_type parameter required, choose maze, random, or moat' ### set world size ### if args["world_size"] == 'small': self.world_size = 'small' self.width = 13 self.height = 11 if args["world_size"] == 'large': self.world_size = 'large' self.width = 41 self.height = 15 ### initialize grid based on world_size ### self.grid = np.zeros((self.height,self.width)) # index states for Q matrix self.states = [] for i in range(self.height): for j in range(self.width): block = [i,j] self.states.append(str(i) + ',' + str(j)) ### with world type load in hazards ### if args["world_type"] == 'maze': self.world_type = 'maze' self.agent = [self.height-2, 0] # initial location agent self.goal = [self.height-2, self.width-1] # goal block if args["world_type"] == 'maze_v2': self.world_type = 'maze_v2' self.agent = [self.height-2, 0] # initial location agent self.goal = [self.height-2, self.width-1] # goal block if args["world_type"] == 'random': self.world_type = 'random' self.agent = [0,0] # initial location agent self.goal = [0,self.width-1] # goal block if args["world_type"] == 'moat': self.world_type = 'moat' self.agent = [0,0] # initial location agent self.goal = [0,self.width-1] # goal block ### load in hazards for given world size and type ### hazard_csvname = 'demo_datasets/RL_datasets/' + args["world_size"] + '_' + args["world_type"] + '_hazards.csv' # load in preset hazard locations from csv self.hazards = pd.read_csv(hazard_csvname,header = None) # setup hazard reward value self.hazard_reward = -200 if 'hazard_reward' in args: self.hazard_reward = args['hazard_reward'] # initialize hazards locations temp = [] for i in range(len(self.hazards)): block = list(self.hazards.iloc[i]) self.grid[block[0]][block[1]] = 1 temp.append(block) # initialize hazards location self.hazards = temp ### initialize state index, Q matrix, and action choices ### # initialize action choices self.action_choices = [[-1,0],[1,0],[0,-1],[0,1]] ### create custom colormap for gridworld plotting ### # color ordering: background, hazard, goal, agent, lights off colors = [(0.9,0.9,0.9),(255/float(255), 119/float(255), 119/float(255)), (66/float(255),244/float(255),131/float(255)), (1/float(255),100/float(255),200/float(255)),(0,0,0)] self.my_cmap = LinearSegmentedColormap.from_list('colormapX', colors, N=100) # create training episodes self.training_episodes = 500 if 'training_episodes' in args: # define num of training episodes self.training_episodes = args['training_episodes'] # make new training start schedule self.training_start_schedule = self.make_start_schedule(episodes = self.training_episodes) # preset number of training episodes value self.validation_episodes = 100 if 'validation_episodes' in args: # define num of testing episodes self.validation_episodes = args['validation_episodes'] # make new testing start schedule self.validation_start_schedule = self.make_start_schedule(episodes = self.validation_episodes) self.max_steps = 5*self.width*self.height # maximum number of steps per episode
plt.rcParams["font.sans-serif"] = [ "Fira Sans", "PT Sans", "Open Sans", "Roboto", "DejaVu Sans", "Liberation Sans", "sans-serif" ] plt.rcParams["xtick.major.width"] = 2 plt.rcParams["xtick.major.size"] = 8 plt.rcParams["ytick.major.width"] = 2 plt.rcParams["ytick.major.size"] = 8 #Make Figures Great Again color scheme... why am I still using this? colors = [(11 / 255, 26 / 255, 69 / 255), (85 / 255, 114 / 255, 194 / 255), (195 / 255, 177 / 255, 137 / 255), (216 / 255, 157 / 255, 125 / 255), (175 / 255, 90 / 255, 59 / 255)] n_bins = [3, 6, 10, 100] # Discretizes the interpolation into bins cmap_name = 'my_list' cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=7) #Load simulation results. data = np.loadtxt('./validation_sims/ResultsBA2_f2.dat') # Creates the figure and axis objects. fig, ax = plt.subplots(1, 1, figsize=(6, 5.5), sharey=False) fig.subplots_adjust(bottom=0.15) #ax.set_xscale('log') ax.set_xlim(0.000, 0.5) #ax.set_yscale('log') ax.set_ylim(0.001, 1) # Parameter sets F = np.linspace(0.00, 0.5, 50) T = 0.3
from matplotlib import cm from matplotlib.colors import LinearSegmentedColormap, ListedColormap class Colors: bright_blue = (13 / 255, 0 / 255, 107 / 255) # blue HSV(244, 255, 207) bright_red = (207 / 255, 0 / 255, 0 / 255) # red HSV(0, 255, 207) _bwr_data = [ (13 / 255, 0 / 255, 107 / 255), # blue negative HSV(244, 255, 207) (1.0, 1.0, 1.0), # white center (207 / 255, 0 / 255, 0 / 255), # red positive HSV(0, 255, 207) ] _cmap_bwr = LinearSegmentedColormap.from_list("crownet_bwr", _bwr_data) def _register_cmap(): cm.register_cmap("crownet_bwr", _cmap_bwr)
'#03A9F4', '#009688', '#8BC34A', '#FFEB3B', '#FF9800', '#795548', '#607D8B', ), 'map': LinearSegmentedColormap.from_list( 'colour', ( '#F44336', '#9C27B0', '#3F51B5', '#03A9F4', '#009688', '#8BC34A', '#FFEB3B', '#FF9800', '#795548', '#607D8B', )), 'colourspace': RGB_COLOURSPACES['sRGB'] }), 'opacity': Structure(**{ 'high': 0.75, 'low': 0.25 }), 'hatch':
def showWriting(dictfilenames): #################################################################################### # Displays a set of writing exercises (x-y position and pressure variation). # #################################################################################### # Fancy display assets --------------------------------------------------------- colorsfair = [(1, 219 / 255, 163 / 255), (1, 196 / 255, 102 / 255), (244 / 255, 189 / 255, 96 / 255), (244 / 255, 164 / 255, 96 / 255)] colorsdark = [(120 / 255, 120 / 255, 120 / 255), (80 / 255, 80 / 255, 80 / 255), (40 / 255, 40 / 255, 40 / 255), (0, 0, 0)] spectrefair = LinearSegmentedColormap.from_list('spectre', colorsfair, N=100) spectredark = LinearSegmentedColormap.from_list('spectre', colorsdark, N=100) # Going through the CSV collection and extracting the data. -------------------- allWritings = {} # The "easy" tasks come first. Click to enlarge the display. ------------------- glyphs = plt.figure(figsize=(40, 20)) for i in range(6): filename = list(dictfilenames.keys())[i] qualify = dictfilenames[filename] posd = readWriting(filename) allWritings[qualify] = posd ax = glyphs.add_subplot(6, 6, i + 1) # The pressure variation is shown using the colormap. ---------------------- # Notice how increasing the speed loosens the pen's pressure. -------------- ax.scatter(posd['x'], posd['y'], c=posd['pressure'], cmap=spectrefair, marker='.', s=0.05) ax.set_title("Writing task - " + qualify, fontsize=20, pad=12) ax.invert_yaxis() # to compensate for the mirroring effect # The children tend to use various areas from the tablet : ----------------- ax.set_ylim(200, 1000) if i > 2: ax.set_ylim(-900, -400) ax.set_xlim(200, 1800) plt.xticks([]), plt.yticks([]) plt.tight_layout() plt.show() # We turn to harder tasks where the child has to trace full letters and words. - glyphs = plt.figure(figsize=(27, 31)) for i in range(6, 10): filename = list(dictfilenames.keys())[i] qualify = dictfilenames[filename] posd = readWriting(filename) ax = glyphs.add_subplot(4, 2, i - 5) # Some of these exercises are never recorded for younger children, ---------- # we take that fact into account -------------------------------------------- if len( posd ) > 5: # 5 instead of 0, just in case the DF is not totally empty ax.scatter(posd['x'], posd['y'], c=posd['pressure'], cmap=spectredark, marker='.', s=0.05) ax.set_title("Writing task - " + qualify, fontsize=14, pad=7) ax.set_ylim(0, 1000) ax.invert_yaxis() ax.set_xlim(0, 2000) allWritings[qualify] = posd else: ax.fill_between([0, 1], [1, 1], hatch='\\', linewidth=0, facecolor='white', edgecolor='lightgrey') plt.xticks([]), plt.yticks([]) plt.subplots_adjust(wspace=7, hspace=50) plt.tight_layout() plt.show() return allWritings
from mpl_toolkits import mplot3d # Handling the drift import quat, vector, rotmat from scipy import constants g = constants.g # Signal correlation from scipy.ndimage import interpolation as ip from scipy import integrate, interpolate as ipd from scipy.signal import correlate # Fourier Transforms import numpy.fft as fft colors = [(126 / 255, 154 / 255, 11 / 255), (127 / 255, 155 / 255, 12 / 255), (128 / 255, 156 / 255, 13 / 255), (129 / 255, 157 / 255, 14 / 255), (1, 200 / 255, 207 / 255), (1, 162 / 255, 0), (120 / 255, 0, 29 / 255)] spectre = LinearSegmentedColormap.from_list('spectre', colors, N=100) # ////////////////////////////////////////////////////////////////////////////////// '''1. Common tools for signal processing''' # ////////////////////////////////////////////////////////////////////////////////// def kalmanFilter(data, att, eps, disp=False, afflim=None): #################################################################################### # # # Using Kalman's approach to filter a fixed column in a DataFrame. This should # # rule out any kind of noise that would be brought in by the measuring devices. # # Parameters # # ------------------------------------------------------------------------------ #
mint = np.vstack((white, palettable.cartocolors.sequential.Mint_7.mpl_colors)) PBW = np.vstack((white, palettable.colorbrewer.sequential.PuBu_9.mpl_colors)) BYW = palettable.cartocolors.sequential.BrwnYl_7_r.mpl_colors #[1:] mint = palettable.cartocolors.sequential.Mint_7_r.mpl_colors #[1:] PBW = palettable.colorbrewer.sequential.PuBu_9_r.mpl_colors #[1:] cmap_list = [ 'magma', #LinearSegmentedColormap.from_list('mytempo', tempo), palettable.scientific.sequential.LaJolla_20_r.mpl_colormap, # palettable.cartocolors.diverging.Geyser_7.mpl_colormap, # palettable.scientific.sequential.Turku_20.mpl_colormap, pt.get_cmap('radial_velocity'), # LinearSegmentedColormap.from_list('Tokyo', tokyo), # palettable.scientific.sequential.Oslo_20.mpl_colormap, LinearSegmentedColormap.from_list('ovi', BYW), LinearSegmentedColormap.from_list('si', mint), LinearSegmentedColormap.from_list('hi', PBW), #palettable.scientific.sequential.LaPaz_20_r.mpl_colormap, # palettable.scientific.sequential.Davos_20_r.mpl_colormap, ] #zlim_list = [(1e-30, 1e-25), (1e5, 1e8), (5e-3, 5), (1e-21, 1e-15), (1e13, 1e15), (3e12, 1e17)] zlim_list = [ (1e-28, 5e-25), (3e4, 1.5e6), (-100, 100), #(1e-2, 1), (1e13, 3.2e16), (3.2e12, 1e16), (1e13, 1e20) ]
def visualize_image_attr( attr: ndarray, original_image: Union[None, ndarray] = None, method: str = "heat_map", sign: str = "absolute_value", plt_fig_axis: Union[None, Tuple[figure, axis]] = None, outlier_perc: Union[int, float] = 2, cmap: Union[None, str] = None, alpha_overlay: float = 0.5, show_colorbar: bool = False, title: Union[None, str] = None, fig_size: Tuple[int, int] = (6, 6), use_pyplot: bool = True, ): r""" Visualizes attribution for a given image by normalizing attribution values of the desired sign (positive, negative, absolute value, or all) and displaying them using the desired mode in a matplotlib figure. Args: attr (numpy.array): Numpy array corresponding to attributions to be visualized. Shape must be in the form (H, W, C), with channels as last dimension. Shape must also match that of the original image if provided. original_image (numpy.array, optional): Numpy array corresponding to original image. Shape must be in the form (H, W, C), with channels as the last dimension. Image can be provided either with float values in range 0-1 or int values between 0-255. This is a necessary argument for any visualization method which utilizes the original image. Default: None method (string, optional): Chosen method for visualizing attribution. Supported options are: 1. `heat_map` - Display heat map of chosen attributions 2. `blended_heat_map` - Overlay heat map over greyscale version of original image. Parameter alpha_overlay corresponds to alpha of heat map. 3. `original_image` - Only display original image. 4. `masked_image` - Mask image (pixel-wise multiply) by normalized attribution values. 5. `alpha_scaling` - Sets alpha channel of each pixel to be equal to normalized attribution value. Default: `heat_map` sign (string, optional): Chosen sign of attributions to visualize. Supported options are: 1. `positive` - Displays only positive pixel attributions. 2. `absolute_value` - Displays absolute value of attributions. 3. `negative` - Displays only negative pixel attributions. 4. `all` - Displays both positive and negative attribution values. This is not supported for `masked_image` or `alpha_scaling` modes, since signed information cannot be represented in these modes. Default: `absolute_value` plt_fig_axis (tuple, optional): Tuple of matplotlib.pyplot.figure and axis on which to visualize. If None is provided, then a new figure and axis are created. Default: None outlier_perc (float or int, optional): Top attribution values which correspond to a total of outlier_perc percentage of the total attribution are set to 1 and scaling is performed using the minimum of these values. For sign=`all`, outliers a nd scale value are computed using absolute value of attributions. Default: 2 cmap (string, optional): String corresponding to desired colormap for heatmap visualization. This defaults to "Reds" for negative sign, "Blues" for absolute value, "Greens" for positive sign, and a spectrum from red to green for all. Note that this argument is only used for visualizations displaying heatmaps. Default: None alpha_overlay (float, optional): Alpha to set for heatmap when using `blended_heat_map` visualization mode, which overlays the heat map over the greyscaled original image. Default: 0.5 show_colorbar (boolean, optional): Displays colorbar for heatmap below the visualization. If given method does not use a heatmap, then a colormap axis is created and hidden. This is necessary for appropriate alignment when visualizing multiple plots, some with colorbars and some without. Default: False title (string, optional): Title string for plot. If None, no title is set. Default: None fig_size (tuple, optional): Size of figure created. Default: (6,6) use_pyplot (boolean, optional): If true, uses pyplot to create and show figure and displays the figure after creating. If False, uses Matplotlib object oriented API and simply returns a figure object without showing. Default: True. Returns: 2-element tuple of **figure**, **axis**: - **figure** (*matplotlib.pyplot.figure*): Figure object on which visualization is created. If plt_fig_axis argument is given, this is the same figure provided. - **axis** (*matplotlib.pyplot.axis*): Axis object on which visualization is created. If plt_fig_axis argument is given, this is the same axis provided. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> ig = IntegratedGradients(net) >>> # Computes integrated gradients for class 3 for a given image . >>> attribution, delta = ig.attribute(orig_image, target=3) >>> # Displays blended heat map visualization of computed attributions. >>> _ = visualize_image_attr(attribution, orig_image, "blended_heat_map") """ # Create plot if figure, axis not provided if plt_fig_axis is not None: plt_fig, plt_axis = plt_fig_axis else: if use_pyplot: plt_fig, plt_axis = plt.subplots(figsize=fig_size) else: plt_fig = Figure(figsize=fig_size) plt_axis = plt_fig.subplots() if original_image is not None: if np.max(original_image) <= 1.0: original_image = _prepare_image(original_image * 255) else: assert ( ImageVisualizationMethod[method] == ImageVisualizationMethod.heat_map ), "Original Image must be provided for any visualization other than heatmap." # Remove ticks and tick labels from plot. plt_axis.xaxis.set_ticks_position("none") plt_axis.yaxis.set_ticks_position("none") plt_axis.set_yticklabels([]) plt_axis.set_xticklabels([]) plt_axis.grid(b=False) heat_map = None # Show original image if ImageVisualizationMethod[ method] == ImageVisualizationMethod.original_image: plt_axis.imshow(original_image) else: # Choose appropriate signed attributions and normalize. norm_attr = _normalize_image_attr(attr, sign, outlier_perc) # Set default colormap and bounds based on sign. if VisualizeSign[sign] == VisualizeSign.all: default_cmap = LinearSegmentedColormap.from_list( "RdWhGn", ["red", "white", "green"]) vmin, vmax = -1, 1 elif VisualizeSign[sign] == VisualizeSign.positive: default_cmap = "Greens" vmin, vmax = 0, 1 elif VisualizeSign[sign] == VisualizeSign.negative: default_cmap = "Reds" vmin, vmax = 0, 1 elif VisualizeSign[sign] == VisualizeSign.absolute_value: default_cmap = "Blues" vmin, vmax = 0, 1 else: raise AssertionError("Visualize Sign type is not valid.") cmap = cmap if cmap is not None else default_cmap # Show appropriate image visualization. if ImageVisualizationMethod[ method] == ImageVisualizationMethod.heat_map: heat_map = plt_axis.imshow(norm_attr, cmap=cmap, vmin=vmin, vmax=vmax) elif (ImageVisualizationMethod[method] == ImageVisualizationMethod.blended_heat_map): plt_axis.imshow(np.mean(original_image, axis=2), cmap="gray") heat_map = plt_axis.imshow(norm_attr, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha_overlay) elif ImageVisualizationMethod[ method] == ImageVisualizationMethod.masked_image: assert VisualizeSign[sign] != VisualizeSign.all, ( "Cannot display masked image with both positive and negative " "attributions, choose a different sign option.") plt_axis.imshow( _prepare_image(original_image * np.expand_dims(norm_attr, 2))) elif ImageVisualizationMethod[ method] == ImageVisualizationMethod.alpha_scaling: assert VisualizeSign[sign] != VisualizeSign.all, ( "Cannot display alpha scaling with both positive and negative " "attributions, choose a different sign option.") plt_axis.imshow( np.concatenate( [ original_image, _prepare_image(np.expand_dims(norm_attr, 2) * 255), ], axis=2, )) else: raise AssertionError("Visualize Method type is not valid.") # Add colorbar. If given method is not a heatmap and no colormap is relevant, # then a colormap axis is created and hidden. This is necessary for appropriate # alignment when visualizing multiple plots, some with heatmaps and some # without. if show_colorbar: axis_separator = make_axes_locatable(plt_axis) colorbar_axis = axis_separator.append_axes("bottom", size="5%", pad=0.1) if heat_map: plt_fig.colorbar(heat_map, orientation="horizontal", cax=colorbar_axis) else: colorbar_axis.axis("off") if title: plt_axis.set_title(title) if use_pyplot: plt.show() return plt_fig, plt_axis
def add_collage_colorbar(figure, ax, smfs, vmin, vmax, cbar_vmin=None, cbar_vmax=None, midpoint=None, multicollage=False, colorbar_params={}, **kwargs): if 'fraction' in colorbar_params: fraction = colorbar_params['fraction'] else: fraction = .5 if 'shrink' in colorbar_params: shrink = colorbar_params['shrink'] else: shrink = .5 if 'aspect' in colorbar_params: aspect = colorbar_params['aspect'] else: aspect = 20 if 'pad' in colorbar_params: pad = colorbar_params['pad'] else: pad = .5 if 'anchor' in colorbar_params: anchor = colorbar_params['anchor'] else: anchor = 'C' if 'format' in colorbar_params: c_format = colorbar_params['format'] else: c_format = '%.2g' if 'cmap' not in kwargs: cmap = None else: cmap = kwargs.pop('cmap') if cmap is None: cmap = get_cmap(plt.rcParamsDefault['image.cmap']) else: if isinstance(cmap, str): cmap = get_cmap(cmap) if 'threshold' in kwargs: threshold = kwargs['threshold'] else: threshold = None # Color bar our_cmap = get_cmap(cmap) if midpoint is None: norm = Normalize(vmin=vmin, vmax=vmax) else: norm = MidpointNormalize(midpoint=midpoint, vmin=vmin, vmax=vmax) nb_ticks = 5 ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, our_cmap.N) if threshold is not None: cmaplist = [our_cmap(i) for i in range(our_cmap.N)] # set colors to grey for absolute values < threshold istart = int(norm(-threshold, clip=True) * (our_cmap.N - 1)) istop = int(norm(threshold, clip=True) * (our_cmap.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.) our_cmap = LinearSegmentedColormap.from_list('Custom cmap', cmaplist, our_cmap.N) # we need to create a proxy mappable proxy_mappable = ScalarMappable(cmap=our_cmap, norm=norm) proxy_mappable.set_array(np.concatenate(smfs)) if multicollage: cbar = plt.colorbar(proxy_mappable, ax=ax, ticks=ticks, spacing='proportional', format=c_format, orientation='vertical', anchor=anchor, fraction=fraction, shrink=shrink, aspect=aspect, pad=pad) else: left = (ax[0][0].get_position().x0 + ax[0][0].get_position().x1) / 2 right = (ax[0][1].get_position().x0 + ax[0][1].get_position().x1) / 2 bot = ax[1][0].get_position().y1 width = right - left # [left, bottom, width, height] cbaxes = figure.add_axes([left, bot - (.05 / 3), width, .05]) cbar = plt.colorbar(proxy_mappable, cax=cbaxes, ticks=ticks, spacing='proportional', format=c_format, orientation='horizontal', shrink=1, anchor='C') _crop_colorbar(cbar, cbar_vmin, cbar_vmax) return figure, ax
col for col in barcamoves.columns if 'bin' not in col ]] ##remove the bins/indices since they're useless now xT_Players = barcamoves.groupby('name')[[ 'xT_value', 'end_zone_value', 'start_zone_value' ]].sum().sort_values('xT_value', ascending=False).round(4) pitch = Pitch(pitch_type='uefa', figsize=(6.8, 10.5), line_zorder=2, line_color='white', orientation='vertical') # draw fig, ax = pitch.draw() from matplotlib.colors import ListedColormap, LinearSegmentedColormap cmaplist = ['#082630', '#0682fe', "#eff3ff"] cmap = LinearSegmentedColormap.from_list("", cmaplist) bin_statistic = pitch.bin_statistic(barcamoves.x, barcamoves.y, values=barcamoves.xT_value, statistic='sum', bins=(38, 25)) bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1) vm = bin_statistic['statistic'].min() vma = bin_statistic['statistic'].max() pitch.heatmap(bin_statistic, ax=ax, cmap='inferno', edgecolors=None, vmin=bin_statistic['statistic'].min(), vmax=bin_statistic['statistic'].max()) ax.set_title('Barcelona' + '\n' + 'Open-play Threat-generation hotspots',
from pysqlite2 import dbapi2 as sql import geopandas as gpd from geopandas.plotting import plot_dataframe from custom_geopandas_plotting import plot_dataframe_custom import pandas as pd import csv import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import numpy as np np.seterr(invalid='ignore') plt.style.use('diss_style_small.mplstyle') cmap = LinearSegmentedColormap.from_list( 'mycmap', list( reversed( ['#d73027', '#fc8d59', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4']))) db = "/home/eric/Documents/franklin/narsc2018/generated_data/narsc18.sqlite" con = sql.connect(db) con.enable_load_extension(True) con.execute("SELECT load_extension('mod_spatialite');") cur = con.cursor() qry = ''' SELECT A.GISJOIN, B.diversity_4grp_10, B.diversity_4grp_00, B.diversity_4grp_90, D.Sus_10, D.Sus_00, D.Sus_90, E.gini_10, E.gini_00, E.gini_90, Hex(ST_AsBinary(C.geometry)) AS geom FROM us_county_2010 AS A JOIN county_diversity AS B
def __init__(self, mainframe, path): """Initialize the main frame""" ttk.Frame.__init__(self, master=mainframe) self.filename = path.split('/')[-1] self.master.title(self.filename) # The main frame onto which we draw the app's elements frame = tk.Frame(self.master) frame.grid(row=0) # Add a button to clear the grid b_clear = tk.Button(frame, text='Clear', command=self.clear_grid) b_clear.grid(row=0, column=1, padx=5, pady=5) # Add a button to save b_save = tk.Button(frame, text='Export Tiles', command=self.save_curation) b_save.grid(row=0, column=2, padx=5, pady=5) # The palette for selecting colours. self.num_colors = 10 self.palette_canvas = tk.Canvas(self.master, height=75, width=60 * (self.num_colors + 1)) self.palette_canvas.grid(row=1, column=0) colors = [(1, 0.5, 0.5), (0.6, 0.25, 0.7), (0.05, 0.05, 1)] color_map = LinearSegmentedColormap.from_list('Yeet', colors, N=10) self.colors = [''] for i in range(self.num_colors): color = rgb2hex(color_map(i)[:3]) self.colors.append(color) # Add the color selection rectangles to the palette canvas self.palette_rects = [] self.p_pad = 5 self.labels = [""] + [i for i in range(10)] self.p_width = self.p_height = 65 - 2 * self.p_pad for i in range(self.num_colors + 1): x, y = self.p_pad * (i + 1) + i * self.p_width, self.p_pad rect = self.palette_canvas.create_rectangle(x, y, x + self.p_width, y + self.p_height, fill=self.colors[i]) self.palette_rects.append(rect) self.palette_canvas.create_text((2 * x + self.p_width) / 2, (2 * y + self.p_height) / 2, font=("Purisa", 16), fill="black", text="{}".format(self.labels[i])) self.palette_canvas.create_polygon([ self.p_pad, self.p_pad, self.p_width + self.p_pad, self.p_height + self.p_pad ], outline="black", fill="black", width=1) self.palette_canvas.create_polygon([ self.p_pad, self.p_height + self.p_pad, self.p_width + self.p_pad, self.p_pad ], outline="black", fill="black", width=1) self.current_color = 0 # Vertical and horizontal scrollbars for canvas vbar = AutoScrollbar(self.master, orient='vertical') hbar = AutoScrollbar(self.master, orient='horizontal') vbar.grid(row=2, column=1, sticky='ns') hbar.grid(row=4, column=0, sticky='we') self.orig_image = np.array(Image.open(path)) # open image self.image = Image.open(path) # open image self.width, self.height = self.image.size self.im_scale = 1.0 # scale for the canvas image self.delta = 1.1 # zoom magnitude # Scale image to the window when it first pops up if self.width > 1024 or self.height > (768 - 200): ratio_scale = max(self.width / 1024, self.height / (768 - 200)) resized_width = self.width / ratio_scale resized_height = self.height / ratio_scale # Create canvas and put image on it self.canvas = tk.Canvas(self.master, highlightthickness=0, width=resized_width, height=resized_height, xscrollcommand=hbar.set, yscrollcommand=vbar.set) self.canvas.grid(row=2, column=0, sticky='nswe') self.canvas.update() # wait till canvas is created vbar.configure(command=self.scroll_y) # bind scrollbars to the canvas hbar.configure(command=self.scroll_x) # Make the canvas expandable self.master.rowconfigure(2, weight=1) self.master.columnconfigure(0, weight=1) # Put image into container rectangle and use it to set proper coordinates to the image self.container = self.canvas.create_rectangle(0, 0, self.width, self.height, width=0, tags="image") # Add the cell rectangles to the grid canvas. self.orig_x_tile, self.x_tile = 128, 128 self.orig_y_tile, self.y_tile = 128, 128 self.cells = [] self.num_x_tiles = int(self.width / self.x_tile) self.num_y_tiles = int(self.height / self.y_tile) for iy in range(self.num_y_tiles): for ix in range(self.num_x_tiles): x, y = ix * self.x_tile, iy * self.y_tile rect = self.canvas.create_rectangle(x, y, x + self.x_tile, y + self.y_tile, fill="", tags=str(x) + ' ' + str(y)) self.cells.append(rect) self.tile_colors = np.zeros((self.num_x_tiles, self.num_y_tiles)) # Bind events to the Canvas self.hovering_tile = None imagetk = ImageTk.PhotoImage(self.image) self.canvas.create_image(0, 0, anchor='nw', image=imagetk) # Scale image to the window when it first pops up if self.width > 1024 or self.height > (768 - 200): ratio_scale = max(self.width / 1024, self.height / (768 - 200)) scale = 1.0 self.im_scale /= ratio_scale self.x_tile /= ratio_scale self.y_tile /= ratio_scale scale /= ratio_scale self.canvas.scale('all', 0, 0, scale, scale) # rescale all canvas objects self.canvas.config(width=self.width / ratio_scale, height=self.height / ratio_scale) self.canvas.bind('<Configure>', self.show_image) # canvas is resized self.canvas.bind('<ButtonPress-1>', self.move_from) self.canvas.bind('<B1-Motion>', self.move_to) self.canvas.bind('<MouseWheel>', self.wheel) # with Windows and MacOS, but not Linux self.canvas.bind('<Button-5>', self.wheel) # only with Linux, wheel scroll down self.canvas.bind('<Button-4>', self.wheel) # only with Linux, wheel scroll up self.palette_canvas.bind('<ButtonPress-1>', self.palette_click_callback) # palette canvas self.canvas.bind('<Double-Button-1>', self.w_click_callback) # grid canvas self.canvas.bind('<Motion>', self.hover_tile) self.canvas.bind('<Enter>', self.hover_tile) self.canvas.bind('<Leave>', self.left_grid) self.reference_image = self.image self.show_image()
""" # Add the sample code in the path mypath = "../ingestion_program" from sys import argv, path from os.path import abspath import os path.append(abspath(mypath)) # Graphic routines import seaborn as sns sns.set() import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # Red, lime, blue cm = LinearSegmentedColormap.from_list('rgb', colors, N=3) # Data types import pandas as pd import numpy as np import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) # Converter class import data_converter # Mother class import data_manager # Typical score from sklearn.metrics import accuracy_score
def alertheat(): """ Creates a state of health table with every station and parameter combination. Timespan selection available for time interval anaysis. """ from polyfemos.front import forms importlib.reload(forms) form = forms.AlertHeatForm() enddate = UTCDateTime().now() startdate = enddate - 86400 * 20 if not form.validate_on_submit(): form.startdate.data = startdate.date form.enddate.data = enddate.date form.log_color.data = False form.points_per_thbb.data = 1 form.points_per_tib.data = 2 startdate = parse_date(form.startdate.data) enddate = parse_date(form.enddate.data) log_color = form.log_color.data points = { "0": 0, "1": form.points_per_thbb.data, "2": form.points_per_tib.data, } sohpar_names = userdef.sohpars(visibilities={1, 2}) station_ids = userdef.station_ids() fpf = userdef.filepathformats("alert") results = {} while startdate <= enddate: julday, year = get_jY(startdate) sohdict = get_sohdict(station_ids, year, julday, fpf) for k, v in sohdict['alerts'].items(): if k not in results: results[k] = {'count': 0, 'max': 0} if v in points: results[k]['count'] += points[v] results[k]['max'] += 2. startdate += 86400 cmap = LinearSegmentedColormap.from_list("", [ colors.ALERT_GREEN, colors.ALERT_YELLOW, colors.ALERT_RED, ]) for k, v in results.items(): if v['max'] <= 0.: v['color'] = colors.GREY_3 v['tooltip'] = "0 / 0\n0.0%" continue else: percentage = v['count'] / v['max'] percents = round(100. * percentage, 2) if log_color: color = 255. * np.log(max(1, percents)) / np.log(100) else: color = 255. * percentage color = int(round(color)) v['color'] = rgb2hex(cmap(color)[:3]) v['tooltip'] = "{} / {:.0f}\n{:.1f}%" \ .format(v['count'], v['max'], percents) return render_base(render_template)('alertheat.htm', alertdict=results, station_ids=station_ids, sohpar_names=sohpar_names, form=form)
def getParulaMap(): """A convienance method for getting a matplotlib friendly version of MATLAB's parula colormap. """ from matplotlib.colors import LinearSegmentedColormap # This is so we can use the Parula Colormap in matplotlib cm_data = [[0.2081, 0.1663, 0.5292], [0.2116238095, 0.1897809524, 0.5776761905], [0.212252381, 0.2137714286, 0.6269714286], [0.2081, 0.2386, 0.6770857143], [0.1959047619, 0.2644571429, 0.7279], [0.1707285714, 0.2919380952, 0.779247619], [0.1252714286, 0.3242428571, 0.8302714286], [0.0591333333, 0.3598333333, 0.8683333333], [0.0116952381, 0.3875095238, 0.8819571429], [0.0059571429, 0.4086142857, 0.8828428571], [0.0165142857, 0.4266, 0.8786333333], [0.032852381, 0.4430428571, 0.8719571429], [0.0498142857, 0.4585714286, 0.8640571429], [0.0629333333, 0.4736904762, 0.8554380952], [0.0722666667, 0.4886666667, 0.8467], [0.0779428571, 0.5039857143, 0.8383714286], [0.079347619, 0.5200238095, 0.8311809524], [0.0749428571, 0.5375428571, 0.8262714286], [0.0640571429, 0.5569857143, 0.8239571429], [0.0487714286, 0.5772238095, 0.8228285714], [0.0343428571, 0.5965809524, 0.819852381], [0.0265, 0.6137, 0.8135], [0.0238904762, 0.6286619048, 0.8037619048], [0.0230904762, 0.6417857143, 0.7912666667], [0.0227714286, 0.6534857143, 0.7767571429], [0.0266619048, 0.6641952381, 0.7607190476], [0.0383714286, 0.6742714286, 0.743552381], [0.0589714286, 0.6837571429, 0.7253857143], [0.0843, 0.6928333333, 0.7061666667], [0.1132952381, 0.7015, 0.6858571429], [0.1452714286, 0.7097571429, 0.6646285714], [0.1801333333, 0.7176571429, 0.6424333333], [0.2178285714, 0.7250428571, 0.6192619048], [0.2586428571, 0.7317142857, 0.5954285714], [0.3021714286, 0.7376047619, 0.5711857143], [0.3481666667, 0.7424333333, 0.5472666667], [0.3952571429, 0.7459, 0.5244428571], [0.4420095238, 0.7480809524, 0.5033142857], [0.4871238095, 0.7490619048, 0.4839761905], [0.5300285714, 0.7491142857, 0.4661142857], [0.5708571429, 0.7485190476, 0.4493904762], [0.609852381, 0.7473142857, 0.4336857143], [0.6473, 0.7456, 0.4188], [0.6834190476, 0.7434761905, 0.4044333333], [0.7184095238, 0.7411333333, 0.3904761905], [0.7524857143, 0.7384, 0.3768142857], [0.7858428571, 0.7355666667, 0.3632714286], [0.8185047619, 0.7327333333, 0.3497904762], [0.8506571429, 0.7299, 0.3360285714], [0.8824333333, 0.7274333333, 0.3217], [0.9139333333, 0.7257857143, 0.3062761905], [0.9449571429, 0.7261142857, 0.2886428571], [0.9738952381, 0.7313952381, 0.266647619], [0.9937714286, 0.7454571429, 0.240347619], [0.9990428571, 0.7653142857, 0.2164142857], [0.9955333333, 0.7860571429, 0.196652381], [0.988, 0.8066, 0.1793666667], [0.9788571429, 0.8271428571, 0.1633142857], [0.9697, 0.8481380952, 0.147452381], [0.9625857143, 0.8705142857, 0.1309], [0.9588714286, 0.8949, 0.1132428571], [0.9598238095, 0.9218333333, 0.0948380952], [0.9661, 0.9514428571, 0.0755333333], [0.9763, 0.9831, 0.0538]] return LinearSegmentedColormap.from_list('parula', cm_data)
blues.append((pos, rgb[2], rgb[2])) alphas.append((pos, 1.0, 1.0)) red_blue_circle = LinearSegmentedColormap('red_blue_circle', { "red": reds, "green": greens, "blue": blues, "alpha": alphas }) colors = [] for l in np.linspace(1, 0, 100): colors.append((30./255, 136./255, 229./255,l)) for l in np.linspace(0, 1, 100): colors.append((255./255, 13./255, 87./255,l)) red_transparent_blue = LinearSegmentedColormap.from_list("red_transparent_blue", colors) colors = [] for l in np.linspace(0, 1, 100): colors.append((30./255, 136./255, 229./255,l)) transparent_blue = LinearSegmentedColormap.from_list("transparent_blue", colors) colors = [] for l in np.linspace(0, 1, 100): colors.append((255./255, 13./255, 87./255,l)) transparent_red = LinearSegmentedColormap.from_list("transparent_red", colors) old_blue_rgb = np.array([30, 136, 229]) / 255 old_red_rgb = np.array([255, 13, 87]) / 255