def get_inference_from_file(lineProb_st): lineProb = [float(x) for x in lineProb_st] if FLAGS.Cmap == 'CancerType': NumberOfClasses = len(lineProb) class_all = [] sum_class = 0 for nC in range(1, NumberOfClasses): class_all.append(float(lineProb[nC])) sum_class = sum_class + float(lineProb[nC]) for nC in range(NumberOfClasses - 1): class_all[nC] = class_all[nC] / sum_class current_score = max(class_all) oClass = class_all.index(max(class_all)) + 1 if FLAGS.thresholds is not None: thresholds = FLAGS.thresholds thresholds = [float(x) for x in thresholds.split(',')] if len(thresholds) != len(class_all): print("Error: There must be one threshold per class:") probDiff = [] for nC in range(len(class_all)): probDiff.append(class_all[nC] - thresholds[nC]) oClass = probDiff.index(max(probDiff)) + 1 current_score = class_all[oClass - 1] score_correction = thresholds[oClass - 1] else: score_correction = 1.0 / len(class_all) if oClass == 1: if len(class_all) == 2: c = mcolors.ColorConverter().to_rgb cmap = make_colormap([c('white'), c('red')]) # cmap = plt.get_cmap('OrRd') else: cmap = plt.get_cmap('binary') elif oClass == 2: if len(class_all) == 2: c = mcolors.ColorConverter().to_rgb cmap = make_colormap([c('white'), c('blue')]) # cmap = plt.get_cmap('Blues') else: cmap = plt.get_cmap('OrRd') elif oClass == 3: cmap = plt.get_cmap('Blues') elif oClass == 4: cmap = plt.get_cmap('Oranges') elif oClass == 5: cmap = plt.get_cmap('Greens') else: cmap = plt.get_cmap('Purples') print(oClass, current_score, (current_score - score_correction) / (1.0 - score_correction)) return oClass, cmap, (current_score - score_correction) / (1.0 - score_correction), [ class_all[0], class_all[1] ]
def colour_plotter2(model, model1): c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('black'), c('red'), 0.05, c('red'), c('yellow'), 0.5, c('yellow'), c('white') , 0.9, c('white')]) agent_counts = np.zeros((model.grid.width, model.grid.height)) agent_counts1 = np.zeros((model1.grid.width, model1.grid.height)) for cell in model.grid.coord_iter(): cell_content, x, y = cell agent_count = len(cell_content) agent_counts[x][y] = agent_count for cell in model1.grid.coord_iter(): cell_content1, x1, y1 = cell agent_count1 = len(cell_content1) agent_counts1[x1][y1] = agent_count1 plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.imshow(agent_counts1.T, interpolation='nearest', cmap=rvb) plt.colorbar() plt.title('UK') plt.subplot(1, 2, 2) plt.imshow(agent_counts.T, interpolation='nearest', cmap=rvb) plt.colorbar() plt.title('New Zealand') plt.show()
def heatmap_with_labels(self, outfile, text_color='black', edgecolors='w', nrows=4, lengths=[2, 8], color_map='Pastel1', format='eps'): '''Modified from here: http://stackoverflow.com/questions/21024066/annotate-heatmap-with-value-from-pandas-dataframe Used for taking the aggregated "stats" node and creating a heatmap of all the sequences below it. ''' df = self.get_dataframe(nrows=nrows) # sequence, length, count, rank df = df[(df['LENGTH'] >= lengths[0]) & (df['LENGTH'] <= lengths[1])] # reshape s.t. index: rank; columns: length. # can select subsets with df['count'] and df['sequence'] df = df.pivot(index='RANK', columns='LENGTH') df = df.sort_index(ascending=False) width = len(df.columns)/7*10 height = len(df.index)/7*10 fig, ax = plt.subplots(figsize=(20,10)) # (figsize=(width,height)) # normalize count to [0, 1] count_df = df['COUNT'].copy().fillna(0.).astype(float) # make color map c = mcolors.ColorConverter().to_rgb # cmap = make_colormap(c('#0000FF'), c('#FFFF00')) # blue-yellow cmap = plt.get_cmap(color_map) # put white lines between squares in heatmap heatmap = ax.pcolor(count_df, cmap=cmap) for x_idx, x in enumerate(df['SEQUENCE'].index): for y_idx, y in enumerate(df['SEQUENCE'].columns): plt.text(y_idx + 0.5, x_idx + 0.5, '%s' % str(df['SEQUENCE'][y][x]), horizontalalignment='center', fontsize=20, verticalalignment='center', color=text_color) ax.autoscale(tight=True) # get rid of whitespace in margins of heatmap ax.set_aspect('equal') # ensure heatmap cells are square ax.xaxis.set_ticks_position('top') # put column labels at the top # turn off ticks ax.tick_params(bottom='off', top='off', left='off', right='off') ax.set_yticks(np.arange(len(count_df.index)) + 0.5) ax.set_yticklabels(count_df.index, size=20) ax.set_xticks(np.arange(len(count_df.columns)) + 0.5) ax.set_xticklabels(count_df.columns, size=24) plt.xlabel('Nucleotides Realigned', fontsize=36) ax.xaxis.set_label_position('top') plt.ylabel('Rank Within Group', fontsize=36) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", "3%", pad="1%") cbar = plt.colorbar(heatmap, cax=cax) cbar.set_label(r'Fraction realigned', fontsize=36) for t in cbar.ax.get_yticklabels(): t.set_fontsize(20) plt.savefig(outfile, format=format)
def make_colormap(colors, whiten=0): z = np.array(sorted(colors.keys())) n = len(z) z1 = min(z) zn = max(z) x0 = (z - z1) / (zn - z1) CC = mcolors.ColorConverter() R = [] G = [] B = [] for i in range(n): Ci = colors[z[i]] if type(Ci) == str: RGB = CC.to_rgb(Ci) else: RGB = Ci R.append(RGB[0] + (1 - RGB[0]) * whiten) G.append(RGB[1] + (1 - RGB[1]) * whiten) B.append(RGB[2] + (1 - RGB[2]) * whiten) cmap_dict = {} cmap_dict['red'] = [(x0[i], R[i], R[i]) for i in range(len(R))] cmap_dict['green'] = [(x0[i], G[i], G[i]) for i in range(len(G))] cmap_dict['blue'] = [(x0[i], B[i], B[i]) for i in range(len(B))] mymap = mcolors.LinearSegmentedColormap('mymap', cmap_dict) return mymap
def gbar(x, y, mapcolour, width=1, bottom=0): X = [[.6, .6], [.7, .7]] c = mcolors.ColorConverter().to_rgb cm = make_colormap([c('white'), c(mapcolour)]) for left, top in zip(x, y): if top != bottom: right = left + width plt.imshow(X, interpolation='bicubic', cmap=cm, extent=(left, right, bottom, top), alpha=1, zorder=10) plt.plot([left, left], [bottom, top], color='black', linestyle='-', zorder=20) plt.plot([right, right], [bottom, top], color='black', linestyle='-', zorder=20) plt.plot([right, left], [top, top], color='black', linestyle='-', zorder=20)
def DelTrminColour(self,colour): ''' To be used interactively, removes the trmin colour group "colour" ''' # If colour_in/colour_out is a string, convert them to RGB tuple if type(colour) == str: col = colors.ColorConverter() try: col_in = col.to_rgb(colour) print col_in except ValueError: print '"%s" not a recognised colour'%colour sys.exit() print '%s converted to: '%colour, col_in else: col_in = colour if not self.trmin_dict.has_key(col_in): print '%s not a key in trmin_dict'%col_in sys.exit() else: for m in self.trmin_dict[col_in]: for l, b in self.minima_index['Index'][m]['Basin']['Level'].items(): if b: self.basin_index['Level'][l]['Basin'][b]['RGB'] = (0,0,0)# black else: continue del self.trmin_dict[col_in]
def AddTrminColourBasin(self,colour,l,b): ''' To be used interactively, adds a new colour for the minima at level l in basin b. ''' # If colour_in/colour_out is a string, convert them to RGB tuple if type(colour) == str: col = colors.ColorConverter() try: col_in = col.to_rgb(colour) print col_in except ValueError: print '"%s" not a recognised colour'%colour sys.exit() print '%s converted to: '%colour, col_in # Check that col_in doesn't already exist if self.trmin_dict.has_key(col_in): print '%s:%s already exists'%(colour,col_in) sys.exit() # Add new colour self.trmin_dict[col_in] = self.basin_index['Level'][l]['Basin'][b]['Min'] # Update basin colours self.AssignColoursToBasin(col_in)
def make_colormap(low, high): """Generates your own colormap for heatmap. Args: low (str or tuple): Color for the lowest value, such as ``'red'`` or ``(1, 0, 0)``. high Returns: matplotlib.colors.LinearSegmentedColormap: Generated colormap. """ import matplotlib matplotlib.use('Agg') import matplotlib.colors as mcolors c = mcolors.ColorConverter().to_rgb if isinstance(low, str): low = c(low) if isinstance(high, str): high = c(high) seq = [(None, ) * 3, 0.0] + [low, high] + [1.0, (None, ) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, x in enumerate(seq): if isinstance(x, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([x, r1, r2]) cdict['green'].append([x, g1, g2]) cdict['blue'].append([x, b1, b2]) cmap = mcolors.LinearSegmentedColormap('CustomMap', cdict) return cmap
def _blend(cls, *color_specs): """ Blend different colors """ if len(color_specs) == 1: if isinstance(color_specs[0], list): return cls._blend(color_specs[0]) return color_specs[0][0].get(color_specs[0][1]) result_color = [0, 0, 0] for color in color_specs: new_rgb = colors.ColorConverter().to_rgb(color[0].get(color[1])) for i, channel in enumerate(new_rgb): result_color[i] = result_color[i] + (channel * float(color[2]) / 100.) result_color.append( colors.ColorConverter().to_rgba(color_specs[0][0].get(color_specs[0][1]))[3] ) return colors.to_hex(result_color, True)
def invert_color(cls, color): """ Compute the inverse of a given color """ rgba = colors.ColorConverter().to_rgba(color) inverted = list(rgba) for i, channel in enumerate(rgba): inverted[i] = ((255 - int(255 * channel)) % 256)/255 return colors.to_hex(inverted)
def heatmap(df, outfile, color_map='coolwarm', format='eps'): fig, ax = plt.subplots(figsize=(20, 10)) c = mcolors.ColorConverter().to_rgb cmap = plt.get_cmap(color_map) df_out = df.iloc[:, 1:-1] # grab everything but sequence and slope sys.stderr.write(str(df_out)) hmap = ax.pcolor(df_out, cmap=cmap) ax.autoscale(tight=True) # get rid of whitespace in margins of heatmap # ax.set_aspect('equal') # ensure heatmap cells are square ax.xaxis.set_ticks_position('top') # put column labels at the top ax.set_yticks(np.arange(len(df.index)) + 0.5) ax.set_yticklabels(df['SEQUENCE'], size=20) plt.xlabel('Time Course (minutes)', fontsize=36) ax.set_xticks(np.arange(len(df_out.columns)) + 0.5) ax.set_xticklabels(TIME_POINTS, size=24) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", "3%", pad="1%") cbar = plt.colorbar(hmap, cax=cax) cbar.set_label(r'Counts per million', fontsize=36) for t in cbar.ax.get_yticklabels(): t.set_fontsize(20) plt.savefig(outfile, format=format)
def visualize(self): c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('blue'), c('lightskyblue'), .20, c('lightsalmon'),c('salmon'), .30, c('salmon'),c('red')]) StrikeZonex = [1,2,3] StrikeZoney = [-1.5,0,1.5] row1 = [] row2 = [] row3 = [] for i in range(1,4): row1.append(self.strikezone.get(i)) for i in range(4,7): row2.append(self.strikezone.get(i)) for i in range(7,10): row3.append(self.strikezone.get(i)) z = np.array([row1, row2, row3]) fig, ax = plt.subplots() for i in range(len(StrikeZoney)): for j in range(len(StrikeZonex)): text = ax.text(j, i, z[i, j], ha="center", va="center", color="black") im = ax.imshow(z,cmap = rvb) fig.tight_layout() plt.show()
def AddTrminColourList(self,colour,minima): ''' To be used interactively, adds a new colour and list of minima to trmin_dict. ''' # If colour_in/colour_out is a string, convert them to RGB tuple if type(colour) == str: col = colors.ColorConverter() try: col_in = col.to_rgb(colour) print col_in except ValueError: print '"%s" not a recognised colour'%colour sys.exit() print '%s converted to: '%colour, col_in # Check that col_in doesn't already exist if self.trmin_dict.has_key(col_in): print '%s:%s already exists'%(colour,col_in) sys.exit() # Add new colour self.trmin_dict[col_in] = minima # Update basin colours self.AssignColoursToBasin(col_in)
def _color2hex(color): """Convert arbitrary color input to hex string""" from matplotlib import colors cc = colors.ColorConverter() rgba = cc.to_rgba(color) hexcol = colors.rgb2hex(rgba) return hexcol
def makeColorMap(colors): """ Creates a colormap for a given array with colors (can be used for e.g. imshow() plots) """ c = mcolors.ColorConverter().to_rgb rgb_list = np.zeros((len(colors), 3)) for i in range(len(colors)): rgb_list[i, :] = c(colors[i]) rgb_list += 0.1 bins = np.linspace(0, 1, len(colors)) cdict_array = np.zeros((3, len(bins), 3)) for i in range(3): cdict_array[i, :, 0] = bins cdict_array[i, :, 1] = rgb_list[:, i] cdict_array[i, :, 2] = rgb_list[:, i] cdict = {} cdict['red'] = tuple([tuple(x) for x in cdict_array[0]]) cdict['green'] = tuple([tuple(x) for x in cdict_array[1]]) cdict['blue'] = tuple([tuple(x) for x in cdict_array[2]]) return mcolors.LinearSegmentedColormap('CustomMap', cdict)
def color(s): """ Convert hex color to space-separated RGB in the range [0-1], as needed by the `dot` graph layout program. """ rgb = colors.ColorConverter().to_rgb(s) return '"{0} {1} {2}"'.format(*rgb)
def plot(*args, **kwargs): # NOTE: this are admin_level.level list not pk or admin_levels objects admin_levels = kwargs.get('admin_levels') # NOTE: this are region pks/objects regions = kwargs.get('regions') df = kwargs.get('data').rename(columns={'value': 'geoarea_id'}) shapes = [] geoareas = get_geoareas( df['geoarea_id'].values.tolist(), admin_levels, regions, ) if len(geoareas) == 0: logger.warning('Empty geoareas found') return for geoarea in geoareas: s = shape(json.loads(geoarea.polygons.geojson)) shapes.append({'geoarea_id': geoarea.id, 'geometry': s}) shapes_frame = gpd.GeoDataFrame(shapes, geometry='geometry') data = shapes_frame.merge(df, on='geoarea_id', how='outer').fillna(0) c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('white'), c('teal')]) data.plot( column='count', cmap=rvb, legend=True, linewidth=0.4, edgecolor='0.5', ) plt.axis('off')
def diverge_map(low=qual_color(0), high=qual_color(1)): c = mcolors.ColorConverter().to_rgb if isinstance(low, basestring): low = c(low) if isinstance(high, basestring): high = c(high) return make_colormap([low, c('white'), 0.5, c('white'), high])
def getInterpolatedColorValues(error_values, A=None, B=None, *, normalize=True): step_colors = [[1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 1, 1], [0, 0, 1]] norm = clrs.Normalize(vmin=A, vmax=B) # cmap = get_cmap('jet'); # cmap = ListedColormap(step_colors); # cmap = get_cmap('Spectral'); c = clrs.ColorConverter().to_rgb cmap = make_colormap([ c('red'), c('yellow'), 0.25, c('yellow'), c('green'), 0.5, c('green'), c('cyan'), 0.75, c('cyan'), c('blue'), 1.0, c('blue') ]) c = error_values final_weights = norm(c) final_colors = cmap(final_weights)[:, 0:3] if (normalize): return final_colors, final_weights return final_colors, error_values
def plot1020(values, electrodes, axis, head=True): ''' Interpolate and plot a color array of the scalp values: values to plot, excepts values between 0 and 1 (e.g. p values) electrodes: same size as values, the observed scalp electrodes axis: axis where the plot will be done head: plot the head reference returns a plot object that may be used for plt.colorbar the colormap used is a diverging map that changes around 0.1 in order to mark statistical significance ''' values = np.asarray(values) electrodes = np.asarray(electrodes) assert (values.size == electrodes.size) all_coords = get_1020coords() Xe = [] Ye = [] Ze = [] for ei in electrodes: x, y, z = all_coords[ei] Xe.append(x) Ye.append(y) Ze.append(z) Xe = np.asarray(Xe) Ye = np.asarray(Ye) Ze = np.asarray(Ze) gridpoints = np.linspace(-1, 1, 250) Xi, Yi = np.meshgrid(gridpoints, gridpoints) rbf = spi.Rbf(Xe, Ye, values, epsilon=0.25) # RBF ignoring Z coordinates Vi = np.ma.masked_array(rbf(Xi, Yi)) # Mask out of head values Vi[Xi**2 + Yi**2 > 1] = np.ma.masked #cmap = cm.bwr c = mcolors.ColorConverter().to_rgb cmap = make_colormap([c('red'), c('white'), 0.1, c('white'), c('blue')]) cres = axis.pcolor(Xi, Yi, Vi, cmap=cmap, vmin=0, vmax=1) if head: # plot fake head circle = np.linspace(0, 2 * np.pi, 1e3) xhead = np.sin(circle) yhead = np.cos(circle) axis.plot(xhead, yhead, color='k', linewidth=3) # plot projection of electrodes on Z=0 axis.plot(Ye, Xe, 'go') for i, elec in enumerate(electrodes): axis.text(Ye[i] + .05 * np.sign(Ye[i]), Xe[i] + .08 * np.sign(Xe[i]), elec) axis.set_xlim((-1.1, 1.1)) axis.set_ylim((-1.1, 1.1)) return cres
def __init__(self): self.clf = None converter = mcolors.ColorConverter().to_rgb cmap = self.make_colormap( [converter('#98FB98'), converter('green'), 0.33, converter('#ffffe0'), converter('yellow'), 0.66, converter('#ffcccc'), converter('red')] ) self.cmap = cmap
def __setattr__(self, name, val): '''set color of sites.''' self.__dict__[name] = val if name == 'color': c = colors.ColorConverter().to_rgb if isinstance(val, str): val = c(val) self._cm = make_colormap([val, c('white')])
def get_color(color_name): """ color can be any name from this page: http://matplotlib.org/mpl_examples/color/named_colors.hires.png """ converter = colors.ColorConverter() c = converter.to_rgba(colors.cnames[color_name]) return ColorRGBA(*c)
def monthly_returns(self, name = "monthly-returns.png",width = 3.5*2, height = 2.5*2): if not self.is_drawable: return str() # Prepare the dataset to be used for drawing charts df_this = self.df.copy() df_this.drop("Benchmark",1,inplace = True) df_this1 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.head(1)) df_this2 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.tail(1)) df_this1.index = df_this1.index.droplevel(2) df_this2.index = df_this2.index.droplevel(2) df_this = pd.concat([df_this1,df_this2],axis = 1) df_this["Return"] = (df_this.iloc[:,1] / df_this.iloc[:,0] - 1) * 100 df_this = df_this.iloc[:,2] for i in range(1,df_this.index[0][1]): df_this.loc[df_this.index[0][0],i] = float("nan") df_this.sort_index(0,0,inplace = True) df_this = df_this.unstack() df_this = df_this.iloc[::-1] # Define the rules of color change def make_colormap(seq): seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict) c = mcolors.ColorConverter().to_rgb c_map = make_colormap([c('#CC0000'),0.1,c('#FF0000'),0.2,c('#FF3333'), 0.3,c('#FF9933'),0.4,c('#FFFF66'),0.5,c('#FFFF99'), 0.6,c('#B2FF66'),0.7,c('#99FF33'),0.8, c('#00FF00'),0.9, c('#00CC00')]) # Drawing charts plt.figure() ax = plt.imshow(df_this, aspect='auto',cmap=c_map, interpolation='none',vmin = -10, vmax = 10) fig = ax.get_figure() fig.set_size_inches(3.5*2,2.5*2) plt.xlabel('') plt.ylabel('') plt.yticks(range(len(df_this.index.values)),df_this.index.values, fontsize = 8) plt.xticks(range(12),["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]) for (j,i),label in np.ndenumerate(df_this): if j == 0: plt.text(i,j+0.1,round(label,1),ha='center',va='top', fontsize = 7) elif j == (df_this.shape[0] - 1): plt.text(i,j-0.1,round(label,1),ha='center',va='bottom', fontsize = 7) else: plt.text(i,j,round(label,1),ha='center',va='center', fontsize = 7) fig.set_size_inches(width, height) base64 = self.fig_to_base64(name, fig) plt.cla() plt.clf() plt.close('all') return base64
def contour_plot_ladung(info, tables, plots, u_h): """ plots """ # x = np.arange(0, plots.x_max, plots.step) # y = np.arange(0, plots.x_max, plots.step) # xx,yy = np.meshgrid(x, y) # zz = np.zeros(xx.shape) plt.figure() for r in range(0, info.number_of_elements): i1 = tables.local_to_global[r, 0] i2 = tables.local_to_global[r, 1] i3 = tables.local_to_global[r, 2] i4 = tables.local_to_global[r, 3] x1 = tables.nodes_to_coordinates[i1, 0] x2 = tables.nodes_to_coordinates[i2, 0] x4 = tables.nodes_to_coordinates[i4, 0] y1 = tables.nodes_to_coordinates[i1, 1] y2 = tables.nodes_to_coordinates[i2, 1] y4 = tables.nodes_to_coordinates[i4, 1] x = np.arange(0, 1.2, 0.2) #plots.step) y = np.arange(0, 1.2, 0.2) #plots.step) xx, yy = np.meshgrid(x, y) #local functions phi1 = (1 - xx) * (1 - yy) phi2 = xx * (1 - yy) phi3 = xx * yy phi4 = (1 - xx) * yy #add weights phi = u_h[i1] * phi1 + u_h[i2] * phi2 + u_h[i3] * phi3 + u_h[i4] * phi4 xx2 = (x2 - x1) * xx + x1 yy2 = (y4 - y1) * yy + y1 #print(phi.max()) #levels = np.arange(u_h.min(), u_h.max()+0.01, (u_h.max()-u_h.min())/10.) levels = np.arange(-5.0, 5.5, 0.5) #maybe outside of loop c = mcolors.ColorConverter().to_rgb rvb = helper.make_colormap([(1.0, 0.6, 0.4), (0.5, 0.5, 0.5), 0.5, (0.5, 0.5, 0.5), (0.0, 0.4, 0.6)]) plt.contour(xx2, yy2, phi, cmap=plt.get_cmap('cool'), levels=levels) # , linewith=0.2) plt.get_cmap('cool') plt.xlabel('$\mathbf{x}_1$') plt.ylabel('$\mathbf{x}_2$') plt.colorbar() plt.savefig('images/contour_ladung.pdf', dpi=500, bbox_inches='tight')
def ChangeBasinColour(self, colour_in, colour_out): ''' Changes the colour of a collection of minima defined using the trmin keyword ''' # If colour_in/colour_out is a string, convert them to RGB tuple if type(colour_in) == str: col = colors.ColorConverter() try: col_in = col.to_rgb(colour_in) except ValueError: print '"%s" not a recognised colour'%colour_in sys.exit() print '%s converted to: '%colour_in, col_in if type(colour_out) == str: col = colors.ColorConverter() try: col_out = col.to_rgb(colour_out) except ValueError: print '"%s" not a recognised colour'%colour_out sys.exit() print '%s converted to: '%colour_out, col_out # Check that colour_in is a valid key, and that there isn't an extant # colour_out if not self.trmin_dict.has_key(col_in): print '%s:%s trmin group not found'%(colour_in,col_in) sys.exit() if self.trmin_dict.has_key(col_out): print '%s:%s already exists'%(colour_out,col_out) sys.exit() # Change colour here! # First copy trmin_dict[col_in] to trmin_dict[col_out] self.trmin_dict[col_out] = self.trmin_dict[col_in][:] # Then delete trmin_dict[col_in] del self.trmin_dict[col_in] # Update basin colours self.AssignColoursToBasin(col_out)
def make_colormap(color_list): #------------------------- """ Define a new color map based on values specified in the dictionary colors, where colors[z] is the color that value z should be mapped to, with linear interpolation between the given values of z. The z values (dictionary keys) are real numbers and the values colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an html hex string, e.g. "#ff0000" for red. Optionally, an alpha channel can be added to indicate levels of transparency. In this case, colors should have a fourth argument, a value between 0 and 1, where zero is transparent and 1 is opaque. Ex. blue_semi_transparent = [0.0, 0.0, 1.0, 0.5] """ z = numpy.sort(list(color_list.keys())) n = len(z) z1 = min(z) zn = max(z) x0 = (z - z1) / (zn - z1) CC = colors.ColorConverter() R = [] G = [] B = [] A = [] for i in range(n): #i'th color at level z[i]: Ci = color_list[z[i]] if type(Ci) == str: # a hex string of form '#ff0000' for example (for red) RGBA = CC.to_rgba(Ci,1.0) else: # assume it's an RGB (or RGBA) tuple already: if (len(Ci) == 3): Ci = numpy.concatenate((Ci,[1.0])) # Add alpha channel RGBA = Ci R.append(RGBA[0]) G.append(RGBA[1]) B.append(RGBA[2]) A.append(RGBA[3]) cmap_dict = {} cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))] cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))] cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))] cmap_dict['alpha'] = [(x0[i],A[i],A[i]) for i in range(len(A))] mymap = colors.LinearSegmentedColormap('mymap',cmap_dict) return mymap
def main(nepochs, model, metric): if type(nepochs) == str: nepochs = int(nepochs) pdf = pd.read_csv('./Code/Performance/Simulation/%s_%s_perf.txt' % (model, metric) , sep=';') md = {"f1": "rougeF1", "recall": "rougeRecall", "precision": "rougePrecision"} emetric = md[metric] c = mcolors.ColorConverter().to_rgb grn = 'limegreen' rvb = make_colormap([c(grn), c('white'), 0.1, c(grn), c('white'), 0.9, c('white')]) # Pulling in the images that were exported ofile_names = [('./Code/plotdata/%s/1/%i_epoch.txt' % (model, x) ) for x in range(nepochs) ] for (ofile, epoch) in zip(ofile_names, range(nepochs)): # Loading data sets and concatenating them odf = pd.read_csv(ofile, sep=';') if epoch == 0: llow = min(odf['actual'].min(), odf['predSelect'].min(), odf['predSkip'].min()) lhigh = max(odf['actual'].max(), odf['predSelect'].max(), odf['predSkip'].max()) llow = min(llow, odf['actual'].min(), odf['predSelect'].min(), odf['predSkip'].min()) lhigh = max(lhigh, odf['actual'].max(), odf['predSelect'].max(), odf['predSkip'].max()) for (ofile, epoch) in zip(ofile_names, range(nepochs)): # Loading data sets and concatenating them # Two subplots, the axes array is 1-d rouge = pdf[pdf['epoch']==epoch][emetric].tolist()[0] odf = pd.read_csv(ofile, sep=';') odf['predOptimal'] = odf[['predSelect','predSkip']].max(axis=1) nsel = odf['Select'].sum() nskip = odf['Skip'].sum() den = float(nsel+nskip) cdfp = buildCDF(odf, 'predOptimal') cdfa = buildCDF(odf, 'actual') f, axarr = plt.subplots(1, 2, figsize=(16,8)) axarr[0].imshow(odf[['Skip', 'Select']], cmap=rvb, interpolation='nearest', aspect='auto') axarr[0].set_title('Select = {%i, %.3f} and Skip = {%i, %.3f}' % (nsel, nsel/den, nskip, nskip/den)) axarr[0].set_xlabel('Estimated Optimal Actions') axarr[0].set_xticks([]) axarr[1].plot(cdfp['predOptimal'], cdfp['cumpercent'], label='Predicted', c='blue') axarr[1].plot(cdfa['actual'], cdfa['cumpercent'], label='Actual', c='red') axarr[1].set_ylim([0,1]) axarr[1].set_xlim([llow, lhigh]) axarr[1].set_xlabel('CDF of Actual and Predicted Rouge') axarr[1].legend(loc ='upper left') axarr[1].grid() axarr[1].set_title('%s %s model performance at epoch %i = %.3f' % (metric, model, epoch, rouge)) f.tight_layout() f.savefig('./Code/plotdata/%s/plotfiles/perfplot_%i.png' % (model, epoch) ) # Exporting the images to a gif file_names = [ ('./Code/plotdata/%s/plotfiles/perfplot_%i.png' % (model, epoch)) for epoch in range(nepochs)] images = [] for filename in file_names: images.append(imageio.imread(filename)) # Actual v Predicted gif imageio.mimsave('./Code/Performance/Simulation/%s_perf.gif' % model, images, duration=0.75)
def diverge_map(high=('blue'), low=('green')): ''' low and high are colors that will be used for the two ends of the spectrum. they can be either color strings or rgb color tuples ''' c = mcolors.ColorConverter().to_rgb if isinstance(low, basestring): low = c(low) if isinstance(high, basestring): high = c(high) return make_colormap([low, c('white'), 0.5, c('white'), high])
def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)): ''' low and high are colors that will be used for the two ends of the spectrum. they can be either color strings or rgb color tuples ''' c = mcolors.ColorConverter().to_rgb if isinstance(low, str): low = c(low) if isinstance(high, str): high = c(high) return make_colormap([low, c('white'), 0.5, c('white'), high])