def ColLegManager(colours=None, legend=None, N=None): # If no dict of colours_map or legend or N has been entered if not colours: colours = None if not legend: legend = None if not N: N = len(legend) + 1 # Constructing list of indexes for alphabetically ordered molecule names in 'legend' if legend is not None: order = np.argsort(legend) print("Order_of_mol_names: ", list(order)) def ColMatcher(*names): for name in names: if mol.find(name) != -1: cols.append(key) return cols cols = [] if colours is not None: # Sorting molecules by colours: for mol in legend: for key in list(colours.keys()): cmap = colours[key] if isinstance(cmap, (list, tuple)): ColMatcher(*cmap) else: ColMatcher(cmap) print("Input_legend: ", legend) print("Matched_col_maps: ", cols) # Creating list of different colour shades from selected colour map for each molecule: paintings = [0] * len(cols) # Matching different shades from selected colour map for each molecule, the gradient respects the alphabetical # order of the molecules' names (first molecule is always the darkest, the shade gets lighter with each next) q = 0 num_of_col = len(Counter(cols).keys()) for num in range(0, num_of_col): clr = cols[order[q]] numocc = cols.count(clr) gradient = np.linspace(0.2, 1, 2 * numocc + 1) for i in range(0, numocc): loc = order[i + q] paintings[loc] = plt.get_cmap(clr)(1 - gradient[i]) q = q + numocc # Default setting - gradient of colours of preset colour map if colours is None: paintings = [0] * N gradient = np.linspace(0.2, 1, N) j = 0 for o in order: paintings[o] = plt.get_cmap('inferno_r')(1 - gradient[j]) j = j + 1 return [order, paintings]
def multiplot_hexbin(b, s): f1 = 'DER_mass_transverse_met_lep' f2 = 'DER_mass_MMC' f3 = 'DER_mass_jet_jet' f4 = 'DER_pt_h' feature_pairs = list(itertools.combinations([f1, f2, f3, f4], 2)) feature_pairs_ = list(itertools.chain(*zip(feature_pairs, feature_pairs))) b_clean = b[(b[f1] != -999.0) & (b[f2] != -999.0) & (b[f3] != -999.0) & (b[f4] != -999.0)] s_clean = s[(s[f1] != -999.0) & (s[f2] != -999.0) & (s[f3] != -999.0) & (s[f4] != -999.0)] plt.figure(figsize=(15, 15)) multiplot_range = xrange(6) for i, k in zip(multiplot_range, feature_pairs_[0:6]): plt.subplot(str(32) + str(i + 1)) if i % 2: plot_hexbin(s_clean, s_clean['Weight'], plt.get_cmap('Reds'), k) else: plot_hexbin(b_clean, b_clean['Weight'], plt.get_cmap('Blues'), k) plt.tight_layout() filename = '../Graphs/scatter1.png' print 'Saving plot in ' + filename plt.savefig(filename) plt.figure(figsize=(15, 15)) multiplot_range = xrange(6) for i, k in zip(multiplot_range, feature_pairs_[6:12]): plt.subplot(str(32) + str(i + 1)) if i % 2: plot_hexbin(s_clean, s_clean['Weight'], plt.get_cmap('Reds'), k) else: plot_hexbin(b_clean, b_clean['Weight'], plt.get_cmap('Blues'), k) plt.tight_layout() filename = '../Graphs/scatter2.png' print 'Saving plot in ' + filename plt.savefig(filename)
def get_cmap(cmap=None): """Get the color map. Parameters ---------- cmap: str, mpl.colors.Colormap The colormap can be provided as the name (should be in matplotlib or cmocean colormaps), or as matplotlib colormap object. Returns ------- colormap:mpl.colors.Colormap Matplotlib colormap object. """ if cmap: if isinstance(cmap, (mpl.colors.Colormap)): colormap = cmap elif cmap in cmo.cmapnames: colormap = cmo.cmap_d[cmap] elif cmap in plt.colormaps(): colormap = plt.get_cmap(cmap) else: raise ValueError( "Get unrecognised name for the colormap `{}`. Colormaps should be from standard matplotlib set of from cmocean package." .format(cmap)) else: colormap = plt.get_cmap("Spectral_r") return colormap
def plot_spectrogram_to_numpy2(spectrogram1, spectrogram2, save_name): fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(3, 3), sharex=True, sharey=True) im = ax1.imshow(spectrogram1, vmin=-11.53, vmax=-0.5, aspect="auto", origin="lower", cmap=plt.get_cmap('magma'), interpolation='none') plt.colorbar(im, ax=ax1) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() ax2 = plt.subplot(2, 1, 2) im2 = ax2.imshow(spectrogram2, vmin=-11.53, vmax=-0.5, aspect="auto", origin="lower", cmap=plt.get_cmap('magma'), interpolation='none') plt.colorbar(im2, ax=ax2) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() plt.savefig(save_name)
def plot_sun_image(img, filename, wavelength, title = '', vmin=0.0, vmax = 1.0): if wavelength == 'hmi': cmap = plt.get_cmap('hmimag') else: cmap = plt.get_cmap('sdoaia{}'.format(wavelength)) plt.title(title) plt.imshow(img,cmap=cmap,origin='lower',vmin=vmin, vmax=vmax) plt.savefig(filename) plt.close("all")
def draw_mask(img, mask, blend=.5, cmap=None, interp='cubic'): if not cmap: import matplotlib.pylab as plt cmap = plt.get_cmap('jet') if isinstance(cmap, str): import matplotlib.pylab as plt cmap = plt.get_cmap(cmap) if mask.shape[:2] != img.shape[:2]: mask = imresize(mask, img.shape[:2], interp=interp) return (cmap(mask)[:, :, :3] * 255 * blend + img * (1 - blend)).round().astype('uint8')
def visualize(model, latent_dim, rangee, epoch): viz = [] random_index = np.random.randint(len(X)-1) X_random = X[random_index] zi, zi_std = model.encode(torch.Tensor(X_random)) for j in range(latent_dim): # for each latent buf = [] for i in rangee: # updating the z by adding the value in rangee x = zi.clone() x[j] += i zi2 = torch.zeros(latent_dim) gen_imgs = model.decode(model.reparameterize_static(x, zi2)) gen_imgs_np = gen_imgs.data.numpy() buf.append(gen_imgs_np) viz.append(buf) lw = 2 N, M = 5, int(latent_dim / 5) # latent_dim = M x N. cmap = plt.get_cmap('RdYlGn_r') colors = cmap(np.linspace(0, 1.0,len(rangee)).tolist()) fig, axs = plt.subplots(M, N, sharex=True, sharey=True, figsize=(int(N*4), int(M*4))) lantent_idx = 0 for i in range(M): # M: rows for j in range(N): # N: columns axs[i, j].plot(X_random, ls = '--', color = 'black', label='sample') ts = np.array(viz[lantent_idx]).T for k, value in enumerate(rangee): axs[i, j].plot(ts[:,k], lw=lw, color=colors[k], label='z_%s+=%s'%(lantent_idx, rangee[k])) axs[i, j].set_title('Updating z_%s, and others fixed'%lantent_idx) axs[i, j].legend(bbox_to_anchor=(0, 0.02), loc=3, borderaxespad=0.2, ncol=2) lantent_idx += 1 fig.suptitle('Training: epoch_%s with total %s latent states = %s'%(epoch,latent_dim, str(np.round(zi.tolist(),2)))) fig.savefig(figure_path + '/epoch_%s.png'%epoch, format="png")
def __init__(self, obs_df, ref_name, var_name, period, how=np.mean, annual_rule='A'): self.period = period self.var_name = var_name self.ref_name = ref_name self.aggr_how = how self.annual_rule = annual_rule obs_df = obs_df.loc[(obs_df.index >= period[0]) & (obs_df.index <= period[-1])] self.obs = New() self.obs.data = obs_df self.obs.freq = infer_freq(obs_df) if self.obs.freq != 'y': self.obs.monthly = self.obs.data.resample(rule='m', how=self.aggr_how) self.obs.annual = self.obs.data.resample(rule='A', how=self.aggr_how) # self.obs.freq = infer_freq(obs_df) self.models = ObjectDict() self._cmap = plt.get_cmap('gist_rainbow') self.selection = Selector([])
def simulate_sequence(D, L, iterations, min_size, max_size, step_size, loop_avoid, reflect): poly = Polymer(D, L, loop_avoid, reflect=reflect) data = [] for N in range(min_size,max_size, step_size): print N #Poor's man progress bar data_per_N = [] bad_number = 0 for i in range(iterations): (last, count, grid) = poly.create_polymer(N) dist = linalg.norm(last - poly.start_point) #print [dist,count,N] df = pd.DataFrame({"dist":[dist], "N": [N], "count" : [count]}) data.append(df) #Save some example realization. if i == 10 and D == 2: pylab.figure() pylab.imshow(grid, cmap=pylab.get_cmap("binary"), interpolation="none") pylab.savefig("realization_N=%d_self_avoid=%d" % (N, loop_avoid)) bad_ratio = 1.0*bad_number/iterations if bad_ratio > 0.02: print "To many bads with N=%d. Bad ratio %.3f" % (N, bad_ratio) #draw_distribution(D,L,N,iterations,loop_avoid, data_per_N) #R2 = (data_per_N**2).mean() #data.append((R2, N)) data = pd.concat(data) return data
def ShowSlice(vals, min_val, max_val): import matplotlib.pyplot as plt # tell imshow about color map so that only set colors are used img = plt.imshow(vals,cmap = plt.get_cmap('gray'),vmin=min_val, vmax=max_val) plt.show()
def plot_3d(arr, colorsMap='jet'): def make_2d_to_3d_array(arr1): x = [] y = [] z = [] for i in range(0, len(arr1)): for j in range(0, len(arr1[0])): x.append(i) y.append(j) z.append(arr1[i][j]) return [x, y, z] points = make_2d_to_3d_array(arr) cm = plt.get_cmap(colorsMap) cNorm = matplotlib.colors.Normalize(vmin=min(points[2]), vmax=max(points[2])) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(points[0], points[1], points[2], c=scalarMap.to_rgba(points[2])) scalarMap.set_array(points[2]) cbar = fig.colorbar(scalarMap) cbar.ax.tick_params(labelsize=20) ax.tick_params(axis='x', labelsize=20) ax.tick_params(axis='y', labelsize=20) ax.tick_params(axis='z', labelsize=20) # ax.set_xlabel("X direction",fontsize = 20) # ax.set_ylabel("Y direction",fontsize = 20) # ax.set_zlabel("Temperature",fontsize = 20) plt.show()
def showImagesGrid(imageDatas, colCnt=None, rowCnt=None, gap=0.03, sigsize=5, cmap=None): plt.figure(figsize=(sigsize, sigsize)) imgSize = len(imageDatas) if cmap is None: cmap = plt.get_cmap('gray') if rowCnt is None: if colCnt is None: colCnt = math.ceil(math.sqrt(imgSize)) rowCnt = colCnt for idx in range(imgSize): plt.subplot(colCnt, rowCnt, idx + 1) plt.imshow(imageDatas[idx], cmap=cmap) plt.axis("off") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=gap, hspace=gap) plt.show()
def __init__(self,name): self.name=name self.log=False self.filter=lambda x:x self.vmin=None self.vmax=None self._norm=None self.compression=6 self.set_depth(8) m=CM_RE.match(name) if m!=None: LOG.debug("%s -> %s",name,repr(m.groups())) cmap,min_val,max_val,under_color,over_color,bad_color=m.groups() if cmap.endswith('-log'): self.filter=np.log10 self.log=True cmap=cmap[:-4] self.cmap=get_cmap(cmap) if min_val and max_val: self.set_minmax(float(min_val),float(max_val)) if under_color: self.cmap.set_under('#'+under_color[:6],alpha=int(under_color[6:],16)/255.0 if under_color[6:] else 1.0) if over_color: self.cmap.set_over('#'+over_color[:6],alpha=int(over_color[6:],16)/255.0 if over_color[6:] else 1.0) if bad_color: self.cmap.set_bad('#'+bad_color[:6],alpha=int(bad_color[6:],16)/255.0 if bad_color[6:] else 1.0) try: from PIL import Image self.Image=Image self._write=self._write_pil LOG.debug('Using PIL for image writing') except ImportError: self._write=self._write_png LOG.debug('Using PNG for image writing')
def plot_param_by_run(self, bins, h, lbl, logscale=False, ax=None): #runs = np.linspace(self.runs[0]-0.5, self.runs[-1]+0.5, self.nrun+1) runs = np.linspace(0.5, self.nrun + 0.5, self.nrun + 1) hmn = np.min(h[h > 0]) hmn = 1e-4 y, x = np.meshgrid(runs, bins, indexing='ij') plt.rc('text', usetex=True) plt.rc('font', family='serif', size=16) if ax is None: fig = plt.figure(figsize=(16, 4)) ax = fig.gca() cmap = plt.get_cmap() cmap.set_bad(cmap(0)) ax.pcolor(x, y, h, norm=LogNorm(), vmin=hmn, cmap=cmap) if logscale: ax.set_xscale('log') ax.set_ylim(self.nrun + 0.5, 0.5) ax.set_xlabel(lbl) ax.set_ylabel("run") #ax.get_xaxis().set_major_formatter(LogFormatterExponent()) #ax.get_xaxis().set_minor_formatter(ScalarFormatter()) ax.set_yticks(runs[:-1] + 0.5) ax.set_yticklabels(self.runs, fontsize=14)
def plot_image(img, img_number, row0, col0, img_size, vmin=0, vmax=600): """ Plot 6x6 or 8x8 background image :param img: current bgd image, always 8x8 :param img_number: number of image, or number of time frame, to fetch appropriate item from row0/col0 :param row0: list with size=nframes containing IMGROW0 :param row0: list with size=nframes containing IMGCOL0 :img_size: image size, 8px for ER, 6px for Science, to fetch and plot bgd image part used for bgd subtraction """ r_min, r_max, c_min, c_max = patch_coords(row0, col0, img_size) # +3 chosen arbitrary, to plot a bit larger area data = vmin * np.ones((c_max - c_min + 3, r_max - r_min + 3)) dr = row0[img_number] - r_min dc = col0[img_number] - c_min data[dr:dr + img_size, dc:dc + img_size] = img[:img_size, :img_size] im = plt.imshow(data, cmap=plt.get_cmap('hot'), interpolation='none', origin='lower', vmin=vmin, vmax=vmax) return im
def get_colormap(ptype, units="mm/h", colorscale="pysteps"): """ Function to generate a colormap (cmap) and norm. Parameters ---------- ptype : {'intensity', 'depth', 'prob'}, optional Type of the map to plot: 'intensity' = precipitation intensity field, 'depth' = precipitation depth (accumulation) field, 'prob' = exceedance probability field. units : {'mm/h', 'mm', 'dBZ'}, optional Units of the input array. If ptype is 'prob', this specifies the unit of the intensity threshold. colorscale : {'pysteps', 'STEPS-BE', 'BOM-RF3'}, optional Which colorscale to use. Applicable if units is 'mm/h', 'mm' or 'dBZ'. Returns ------- cmap : Colormap instance colormap norm : colors.Normalize object Colors norm clevs: list(float) List of precipitation values defining the color limits. clevs_str: list(str) List of precipitation values defining the color limits (with correct number of decimals). """ if ptype in ["intensity", "depth"]: # Get list of colors color_list, clevs, clevs_str = _get_colorlist(units, colorscale) cmap = colors.LinearSegmentedColormap.from_list( "cmap", color_list, len(clevs) - 1 ) if colorscale == "BOM-RF3": cmap.set_over("black", 1) if colorscale == "pysteps": cmap.set_over("darkred", 1) if colorscale == "STEPS-BE": cmap.set_over("black", 1) norm = colors.BoundaryNorm(clevs, cmap.N) cmap.set_bad("gray", alpha=0.5) cmap.set_under("none") return cmap, norm, clevs, clevs_str if ptype == "prob": cmap = copy.copy(plt.get_cmap("OrRd", 10)) cmap.set_bad("gray", alpha=0.5) cmap.set_under("none") clevs = np.linspace(0, 1, 11) clevs[0] = 1e-3 # to set zeros to transparent norm = colors.BoundaryNorm(clevs, cmap.N) clevs_str = [f"{clev:.1f}" for clev in clevs] return cmap, norm, clevs, clevs_str return cm.get_cmap("jet"), colors.Normalize(), None, None
def makePlot(iFile, title, pltz, c): roiMat = [] for l in iFile: roiMat.append(l) roiMat = np.array(roiMat) roiMat = roiMat.astype(np.float) axes = plt.subplot2grid((4,1), (c, 0)) pltz.append(axes) #pltz[c].set_title(title) #_#_#_#_#_# cmap = plt.get_cmap(lut=np.nanmax(roiMat)-np.nanmin(roiMat)+1) pltz[c].matshow(roiMat, aspect='auto', cmap=cmap, vmin=0, vmax=40) #pltz[c].colorbar(label='Count') if c == 3: pltz[c].set_xlabel('ROI') pltz[c].set_ylabel(title) if c == 0: pltz[c].set_xticks(range(30)) pltz[c].set_xticklabels(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]) else: pltz[c].set_xticklabels([]) pltz[c].set_yticks(range(7)) pltz[c].set_yticklabels(["E", "G", "L", "M", "R", "S", "W"], rotation =90) for asd, cas in enumerate(roiMat): for sdf, c in enumerate(cas): plt.text(sdf-.4, asd+.2, int(c), fontsize=8)
def plot_value_function(self, value_function, prefix, v_folder): fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) X, Y = np.meshgrid(np.arange(self.config.input_size[1]), np.arange(self.config.input_size[0])) reproj_value_function = value_function.reshape( self.config.input_size[0], self.config.input_size[1]) """Build the support""" for i in range(len(X)): for j in range(int(len(X[i]) / 2)): tmp = X[i][j] X[i][j] = X[i][len(X[i]) - j - 1] X[i][len(X[i]) - j - 1] = tmp cm.jet( np.random.rand(reproj_value_function.shape[0], reproj_value_function.shape[1])) ax.plot_surface(X, Y, reproj_value_function, rstride=1, cstride=1, cmap=plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.savefig( os.path.join(v_folder, "SuccessorFeatures" + prefix + 'value_function.png')) plt.close()
def get_cmap(cmap_name): """Return matplotlib colormap object. From matplotlib.cm or cmocean. Additional custom colormap for salinity is provided: - "custom_salinity1" """ cm.register_cmap(name='cubehelix3', data=mpl._cm.cubehelix(gamma=1.0, s=2.0, r=1.0, h=3)) if cmap_name in cmo.cmapnames: colormap = cmo.cmap_d[cmap_name] elif cmap_name in plt.colormaps(): colormap = plt.get_cmap(cmap_name) elif cmap_name == "custom_salinity1": colormap = shiftedcolormap(cm.get_cmap("cubehelix3"), start=0, midpoint=0.89, stop=0.9, name='shiftedcmap') else: raise ValueError('Get unrecognised name for the colormap `{}`.\ Colormaps should be from standard matplotlib \ set or from cmocean package.'.format(cmap_name)) return colormap
def getPolyFit(deg=6): #{{{docstring """ Get the polynomial fit Parameters ---------- deg : int Degree of polynomial to use Returns ------- p : array The polynomial coefficients in ascending order. NOTE: This is revesered as compared to np.polyfit polyStr : str String of the polynomial function. Meant to use in a C++ program. """ #}}} cmap = plt.get_cmap("viridis") p = np.polyfit(TeEV, nuEN, deg) # polyfit gives coefficients of highest polynomial first p = p[::-1] polyStr = "" for i in range(deg + 1): polyStr += "{:+f}*pow(Te0_, {})\n".format(p[i], i) if polyStr[0] == "+": polyStr = polyStr[1:] polyStr = "nuEN = (nn/2.5e-19)*(\n" + polyStr polyStr += ");" return p, polyStr
def make_prediction(i): test_img = test_images[i] test_data= x_test[[i], :] plt.imshow(test_img, cmap=plt.get_cmap('gray')) plt.title("Model Prediction: {}".format(num_to_text[model.predict_classes(test_data)[0]])) plt.show()
def plot_value_function(self, value_function, prefix, folder=None): if folder is None: folder = self.summary_path '''3d plot of a value function.''' fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) X, Y = np.meshgrid(np.arange(self.config.input_size[1]), np.arange(self.config.input_size[0])) Z = value_function.reshape(self.config.input_size[0], self.config.input_size[1]) for i in range(len(X)): for j in range(int(len(X[i]) / 2)): tmp = X[i][j] X[i][j] = X[i][len(X[i]) - j - 1] X[i][len(X[i]) - j - 1] = tmp my_col = cm.jet(np.random.rand(Z.shape[0], Z.shape[1])) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.savefig( os.path.join(folder, "SuccessorFeatures" + prefix + 'value_function.png')) plt.close()
def plotBasisFunctions(self, eigenvalues, eigenvectors): """3d plot of the basis function. Right now I am plotting eigenvectors, so each coordinate of the eigenvector correspond to the value to be plotted for the correspondent state.""" for i in range(len(eigenvalues)): fig, ax = plt.subplots(subplot_kw=dict(projection="3d")) X, Y = np.meshgrid(np.arange(self.numRows), np.arange(self.numCols)) Z = eigenvectors[:, i].reshape(self.numCols, self.numRows) for ii in range(len(X)): for j in range(len(X[ii]) // 2): tmp = X[ii][j] X[ii][j] = X[ii][len(X[ii]) - j - 1] X[ii][len(X[ii]) - j - 1] = tmp my_col = cm.jet(np.random.rand(Z.shape[0], Z.shape[1])) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap("jet")) plt.gca().view_init(elev=30, azim=30) plt.savefig(self.outputPath + str(i) + "_eig" + ".png") plt.close() plt.plot(eigenvalues, "o") plt.savefig(self.outputPath + "eigenvalues.png")
def visualize_model(self): ''' VISUALIZATION TO DO: qualitative analysis of a confusion matrix from the 2d display ''' plt.figure( figsize=(7,7)) cm = plt.get_cmap('viridis') colors = iter( cm( np.linspace(0,1,10))) for digit in range(10): # train_images = x_train[ train_digit_indices[digit]] # train_vector = base_network.predict( train_images) # train_vector = np.mean( train_vector, axis=0) # test_images = x_test[ test_digit_indices[digit]] # test_vector = base_network.predict( test_images) # test_vector = np.mean( test_vector, axis=0) # print( train_vector, test_vector) color = next(colors) # plt.quiver( 0,0 , *train_vector, label='%d train'%digit, color=color) # plt.quiver( 0,0, *test_vector, label='%d test'%digit, color=color) # plt.plot( *train_vector.reshape(2,1), label='%d train'%digit, color=color, marker=r'$%d$'%digit, markersize=22, ls='none') # plt.plot( *test_vector.reshape(2,1), label='%d train'%digit, color=color, marker=r'$%d$'%digit, markersize=22, ls='none') # running for train, test concatenation (because we checked similarity) images = np.concatenate( (self.x_train[ self.train_digit_indices[digit]], self.x_test[ self.test_digit_indices[digit]]), axis=0) vector = self.base_network.predict( images, batch_size=128) # vector = np.mean( vector, axis=0) # plt.plot( *vector.reshape(2,1), label='%d'%digit, color=color, marker=r'$%d$'%digit, markersize=22, ls='none') # PLOTTING DISTRIBUTION INSTEAD x, y = vector.T sns.kdeplot(x, y, shade=True, shade_lowest=False, color=color, label=digit) plt.legend(ncol=2) plt.xticks( []) plt.yticks( []) plt.tight_layout() plt.show()
def plotValueFunction(self, valueFunction, prefix): '''3d plot of a value function.''' fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) X, Y = np.meshgrid(np.arange(self.numCols), np.arange(self.numRows)) Z = valueFunction.reshape(self.numRows, self.numCols) for i in range(len(X)): for j in range(int(len(X[i]) / 2)): tmp = X[i][j] X[i][j] = X[i][len(X[i]) - j - 1] X[i][len(X[i]) - j - 1] = tmp my_col = cm.jet(np.random.rand(Z.shape[0], Z.shape[1])) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.savefig( os.path.join(self.outputPath, "SuccessorFeatures" + prefix + 'value_function.png')) plt.close()
def multicolcheck(pipeline, subsample=0.03, dA=20, xrange=[-1000, 3000], yrange=[-1000, 6000]): p = pipeline plt.figure() plt.subplot(1, 2, 1) estimator = scatterdens(p['fitResults_Ag'], p['fitResults_Ar'], subsample=subsample, s=10) plt.xlim(xrange) plt.ylim(yrange) x1d = np.arange(xrange[0], xrange[1], dA) y1d = np.arange(yrange[0], yrange[1], dA) x2d = x1d[:, None] * np.ones_like(y1d)[None, :] y2d = np.ones_like(x1d)[:, None] * y1d[None, :] imd = estimator.evaluate([x2d.flatten(), y2d.flatten()]) imd2d = imd.reshape(x2d.shape) imd2d /= imd2d.max() #plt.figure() plt.subplot(1, 2, 2) plt.imshow(imd2d[:, ::-1].transpose(), cmap=plt.get_cmap('jet'), extent=[xrange[0], xrange[1], yrange[0], yrange[1]]) plt.grid(True) return imd2d
def draw_matrix_user_ranking(df_stat, higher_better=False, fig=None): """ show matrix as image, sorted per column and unique colour per user :param DF df_stat: table where index are users and columns are scoring :param bool higher_better: ranking such that larger value is better :return Figure: >>> import pandas as pd >>> df = pd.DataFrame(np.random.random((5, 3)), columns=list('abc')) >>> fig = draw_matrix_user_ranking(df) """ ranking = compute_matrix_user_ranking(df_stat, higher_better) if fig is None: fig, _ = plt.subplots( figsize=np.array(df_stat.as_matrix().shape[::-1]) * 0.35) ax = fig.gca() arange = np.linspace(-0.5, len(df_stat) - 0.5, len(df_stat) + 1) norm = plt_colors.BoundaryNorm(arange, len(df_stat)) fmt = plt_ticker.FuncFormatter(lambda x, pos: df_stat.index[x]) draw_heatmap(ranking, np.arange(1, len(df_stat) + 1), df_stat.columns, ax=ax, cmap=plt.get_cmap('nipy_spectral', len(df_stat)), norm=norm, cbar_kw=dict(ticks=range(len(df_stat)), format=fmt), cbarlabel='Users') ax.set_ylabel('Ranking') return fig
def plot_runs(runs): """ Plot population evolutions """ ts = range(len(runs[0])) cmap = plt.get_cmap('viridis') for i, r in enumerate(runs): mean, var = zip(*r) bm, cm = zip(*mean) bv, cv = zip(*var) color = cmap(float(i)/len(runs)) plt.errorbar(ts, bm, fmt='-', yerr=bv, c=color) plt.errorbar(ts, cm, fmt='--', yerr=cv, c=color) plt.title('population evolution overview') plt.xlabel('time') plt.ylabel('value') plt.ylim((0, 1)) plt.plot(0, 0, '-', c='black', label='benefit value') plt.plot(0, 0, '--', c='black', label='cost value') plt.legend(loc='best') plt.savefig('result.pdf') plt.show()
def plot_IR_distribution(self, bR, bI, H, ax=None): plt.rc('text', usetex=False) plt.rc('font', family='serif', size=16) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) plt.rc('axes', labelsize=16) plt.rc('axes', titlesize=16) if ax is None: fig = plt.figure(figsize=(8, 6)) ax = fig.gca() cmap = plt.get_cmap() cmap.set_bad(cmap(0)) x, y = np.meshgrid(bR, bI) im = ax.pcolor(x, y, H, norm=LogNorm(), cmap=cmap) ax.set_yscale('log') ax.set_xscale('log') ax.set_ylabel(self.lbl[1]) ax.set_xlabel(self.lbl[2]) return im
def colorize(vector,cmap='plasma', vmin=None, vmax=None): """Convert a vector to RGBA colors. Parameters ---------- vector : array Array of values to be represented by relative colors cmap : str (optional) Matplotlib Colormap name vmin : float (optional) Minimum value for color normalization. Defaults to np.min(vector) vmax : float (optional) Maximum value for color normalization. Defaults to np.max(vector) Returns ------- vcolors : np.ndarray Array of RGBA colors scalarmap : matplotlib.cm.ScalarMappable ScalerMap to convert values to colors cNorm : matplotlib.colors.Normalize Color normalization """ if vmin is None: vmin = np.min(vector) if vmax is None: vmax = np.max(vector) cm = plt.get_cmap(cmap) cNorm = colors.Normalize(vmin=vmin, vmax=vmax) scalarmap = cmx.ScalarMappable(norm=cNorm, cmap=cm) vcolors = scalarmap.to_rgba(vector) return vcolors,scalarmap,cNorm
def random_colormap(N, colormap='jet', name='random', seed=None): """ Create a random ordered colormap. Default settings creates a colormap named 'random' using the jet colormap. Parameters ----------- N : int Number of bins in the colormap. colormap : str (optional) Name of matplotlib colormap name : str (optional) Name of the colormap seed : int or None Random seed Returns -------- cmap : matplotlib.colors.ListedColormap object """ if seed is not None: np.random.seed(seed) vals = np.arange(0, 1, 1 / N) np.random.shuffle(vals) cmap = plt.get_cmap(colormap) cmap_random = ListedColormap(cmap(vals), name=name) return cmap_random
def plot_line_colored(x, y, t, w=None, color=None, cmap=None): import numpy as np from matplotlib.collections import LineCollection # Create a set of line segments so that we can color them individually # This creates the points as a N x 1 x 2 array so that we can stack points # together easily to get the segments. The segments array for line collection # needs to be numlines x points per line x 2 (x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) extra = {} if w is None: extra['linewidths'] = w # Create the line collection object, setting the colormapping parameters. # Have to set the actual values used for colormapping separately. lc = LineCollection(segments, cmap=p.get_cmap(cmap), **extra #norm=p.Normalize(0, 10) ) lc.set_array(t) lc.set_linewidth(w) if color is not None: lc.set_color(color) p.gca().add_collection(lc)
def over_plot_googlemap(self): import folium from folium import plugins import matplotlib.colors as colors import matplotlib.cm as cmx colorMap = plt.get_cmap('cool') cNorm = colors.Normalize(vmin=1920, vmax=1990) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=colorMap) x = self.dic_nodes['x']; y = self.dic_nodes['y'] Lead = 10**np.array( self.dic_nodes['value'] ) - 1. Year = self._generate_new_value(tag='Year Built') map = folium.Map(location=[43.0125, -83.6875], zoom_start=13) for i in range(len(x)): colorVal = scalarMap.to_rgba(Year[i]) colorVal = colors.rgb2hex(colorVal) radius = 40*np.sqrt(Lead[i]) disc = 'Expected Lead : %i\n'%Lead[i] +\ 'Expected Year : %i\n'%Year[i] folium.CircleMarker([y[i], x[i]], radius=radius, popup=disc, color=None, fill_color=colorVal).add_to(map) map.create_map(path='prediction.html')
def pie_plot_important_activities_2018( ): # pie_plot_important_activities_2018(kaggleSurveyDF_2018, schemaSurveyDF_2018 ): responseCountsList = [] responseOptionsTextListAnnotated = [ 'Analyze and understand data', 'Use ML services to improve product or wokflows', 'Build/run data infrastructure', 'Apply ML to new areas and build prototypes', 'Research/advance state of the art in ML', 'Other / None of these activities are important to my role' ] responseCountsList = [9532, 5481, 5233, 7233, 4934, 4663] plt.figure() plt.pie(x=responseCountsList, labels=responseOptionsTextListAnnotated, startangle=90, autopct='%1.1f%%', wedgeprops={ 'linewidth': 1, 'edgecolor': 'white' }, colors=np.array(plt.get_cmap('tab20').colors)) plt.title( 'What activities make up an important part of your role at work?') plt.show()
def draw_custom(G, pos=None, node_size=1000, edge_width=3, font_size=12, node_color='white', color_map='Blues', edge_label=None): """Draw the graph G using Matplotlib. Draw the graph with Matplotlib with options for node positions, labeling, titles, and many other drawing features. """ if not pos: pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, node_color=node_color, node_size=node_size) nx.draw_networkx_edges(G, pos, width=edge_width, edge_color=range(nx.number_of_edges(G)), edge_cmap=plt.get_cmap(color_map), edge_vmin=-10, edge_vmax=10) nx.draw_networkx_labels(G, pos, font_size=font_size) nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes( G, edge_label)) plt.axis('off')
def plot_basis_function(args, x_range, y_range, basis, prefix): """ Plots 3d graph where the x and y coordinates represent the grid and the z axis encodes the value to be depicted. One could use this to look at q-values, for example. In my work, I've used this plot to show proto-value functions, the successor representation, or eigenvectors. :param args: list of all arguments passed at the execution so we can access the paths we are interested at :param x_range: one of the dimensions of the grid world :param y_range: the other dimension of the grid world :param basis: actual values to be plotted :param prefix: string that will be used as the filename of the generated graph """ fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) data_x, data_y = np.meshgrid(np.arange(y_range), np.arange(x_range)) data_z = basis.reshape(x_range, y_range) for ii in range(len(data_x)): for j in range(int(len(data_x[ii]) / 2)): tmp = data_x[ii][j] data_x[ii][j] = data_x[ii][len(data_x[ii]) - j - 1] data_x[ii][len(data_x[ii]) - j - 1] = tmp ax.plot_surface(data_x, data_y, data_z, rstride=1, cstride=1, cmap=plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.gca().set_zlim(-1.0, 1.0) plt.savefig(args.output + prefix + '.png') plt.close() plt.clf()
def plot(lon, lat, var1, var2, actions, ax, fig, **kwargs): aspect = kwargs.get('aspect', None) height = kwargs.get('height') width = kwargs.get('width') norm = kwargs.get('norm') cmap = get_cmap(kwargs.get('cmap', 'jet')) cmin = kwargs.get('cmin', "None") cmax = kwargs.get('cmax', "None") magnitude = kwargs.get('magnitude', 'False') if var1 is not None: if var2 is not None: mag = np.sqrt(var1**2 + var2**2) else: if magnitude == 'False': mag = var1 else: mag = np.abs(var1) mag = mag.squeeze() if "pcolor" in actions: fig.set_figheight(height/80.0) fig.set_figwidth(width/80.0) pcolor(lon, lat, mag, ax, cmin, cmax, cmap) if "facets" in actions: fig.set_figheight(height/80.0) fig.set_figwidth(width/80.0) pcolor(lon, lat, mag, ax, cmin, cmax, cmap) elif "filledcontours" in actions: fig.set_figheight(height/80.0) fig.set_figwidth(width/80.0) fcontour(lon, lat, mag, ax, norm, cmin, cmax, cmap) elif "contours" in actions: fig.set_figheight(height/80.0) fig.set_figwidth(width/80.0) contour(lon, lat, mag, ax, norm, cmin, cmax, cmap) #elif "facets" in actions: # fig.set_figheight(height/80.0) # fig.set_figwidth(width/80.0) # facet(lon, lat, mag, ax) elif "vectors" in actions: fig.set_figheight(height/80.0/aspect) fig.set_figwidth(width/80.0) vectors(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude) elif "unitvectors" in actions: fig.set_figheight(height/80.0/aspect) fig.set_figwidth(width/80.0) unit_vectors(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude) elif "streamlines" in actions: fig.set_figheight(height/80.0/aspect) fig.set_figwidth(width/80.0) m = kwargs.get('basemap') lonmin = kwargs.get("lonmin") latmin = kwargs.get("latmin") lonmax = kwargs.get("lonmax") latmax = kwargs.get("latmax") streamlines(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude, m, lonmin, latmin, lonmax, latmax) elif "barbs" in actions: fig.set_figheight(height/80.0/aspect) fig.set_figwidth(width/80.0) barbs(lon, lat, var1, var2, mag, ax, norm, cmin, cmax, cmap, magnitude)
def plotConfiguration(conf): cmap = plt.get_cmap('viridis') fig, ax = plt.subplots() for i in range(0,conf.orbitals): ax.plot(conf.configurations[0:conf.beads,i,1],range(0,conf.beads),"o",color=cmap(i*1./conf.orbitals)); return {"fig":fig,"ax":ax}
def plotIntensity(data): #plots intensity in color map plot = data.sumPols().getData() if len(plot.shape) != 2: #check if waterfall file is valid sys.exit("Waterplot may only plot waterfall files") vmin, vmax = vlim(plot) #get color scale if isinstance(data, Data.SpecData): t_all = data.getTrange() f_all = data.getFrange() plt.imshow(plot.T, aspect='auto', interpolation='nearest', origin='lower', cmap=plt.get_cmap('Greys'), extent= t_all + f_all, vmin=vmin, vmax=vmax) elif isinstance(data, Data.Data): plt.imshow(plot.T, aspect='auto', interpolation='nearest', origin='lower', cmap=plt.get_cmap('Greys'), vmin=vmin, vmax=vmax) plt.show()
def plot_sun_image(img, filename, wavelength=193, title = ''): #cmap = plt.get_cmap('sdoaia{}'.format(wavelength)) cmap = plt.get_cmap('sohoeit195') plt.title(title) cax = plt.imshow(img,cmap=cmap,origin='lower',vmin=0, vmax=3000)#,vmin=vmin, vmax=vmax) plt.gcf().colorbar(cax) plt.savefig(filename) plt.close("all")
def group_causality(sig_list, condition, freqs, ROI_labels=None, out_path=None, submount=10): """ Make group causality analysis, by evaluating significant matrices across subjects. ---------- sig_list: list The path list of individual significant causal matrix. condition: string One condition of the experiments. freqs: list The list of interest frequency band. min_subject: string The subject for the common brain space. submount: int Significant interactions come out at least in 'submount' subjects. """ print 'Running group causality...' set_directory(out_path) sig_caus = [] for f in sig_list: sig_cau = np.load(f) print sig_cau.shape[-1] sig_caus.append(sig_cau) sig_caus = np.array(sig_caus) sig_group = sig_caus.sum(axis=0) plt.close() for i in xrange(len(sig_group)): fmin, fmax = freqs[i][0], freqs[i][1] cau_band = sig_group[i] # cau_band[cau_band < submount] = 0 cau_band[cau_band < submount] = 0 # fig, ax = pl.subplots() cmap = plt.get_cmap('hot', cau_band.max()+1-submount) cmap.set_under('gray') plt.matshow(cau_band, interpolation='nearest', vmin=submount, cmap=cmap) if ROI_labels == None: ROI_labels = np.arange(cau_band.shape[0]) + 1 pl.xticks(np.arange(cau_band.shape[0]), ROI_labels, fontsize=9, rotation='vertical') pl.yticks(np.arange(cau_band.shape[0]), ROI_labels, fontsize=9) # pl.imshow(cau_band, interpolation='nearest') # pl.set_cmap('BlueRedAlpha') np.save(out_path + '/%s_%s_%sHz.npy' % (condition, str(fmin), str(fmax)), cau_band) v = np.arange(submount, cau_band.max()+1, 1) # cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=10, vmax=z.max()) # fig.colorbar(extend='min') plt.colorbar(ticks=v, extend='min') # pl.show() plt.savefig(out_path + '/%s_%s_%sHz.png' % (condition, str(fmin), str(fmax)), dpi=300) plt.close() return
def colors(numcolors,map='spectral'): std_col = ['r','b','g','m'] if numcolors <= 4: return std_col[:numcolors] cm=plt.get_cmap(map) col = [] for i in range(numcolors): col.append(cm(1.*i/numcolors)) return col
def showGraph(graph): G_adj = adjacencyList(np.array(graph)) G = nx.DiGraph(G_adj) # nx.write_adjlist(G_adj, ) #initialze Figure pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet')) nx.draw_networkx_edges(G, pos, edge_color='b', arrows=True) plt.show()
def plot_matrix(matrix): fig = plt.figure() ax = fig.add_subplot(111) ax.set_title("colorMap") vmax = np.max(np.max(matrix), -1 * np.min(matrix)) plt.imshow(matrix, interpolation="none", cmap=plt.get_cmap("seismic"), vmin=-1 * vmax, vmax=vmax) ax.set_aspect("equal") plt.colorbar(orientation="vertical") plt.show()
def color_by_prop(propArr, nbins): colorArr = [] for icl in xrange(nbins): colorArr.append(plt.get_cmap("hsv")(float(icl)/(nbins))) color_id_Arr = N.zeros_like(propArr) #propbins = N.logspace(N.log10(colorprops*0.99), N.log10(colorprops*1.01), ncolor+1) p_ids, p_bins = pTdf.group_by_prop(propArr, takelog=True, fixed_interval=True, bins=[]) return p_ids, p_bins, colorArr
def __init__(self,vmin=None,vmax=None, filter=lambda x:x, depth=8,compression=None, colormap=plt.get_cmap('jet'), over_color=None, over_alpha=1.0, under_color=None, under_alpha=1.0, bad_color=None, bad_alpha=1.0, gamma=1.0): self.filter=filter if vmin!=None and vmax!=None: self.set_minmax(float(vmin),float(vmax)) else: self.vmin=None self.vmax=None self._norm=None if compression!=None: compression=int(compression) self.compression=compression self.set_depth(int(depth)) if isinstance(colormap,str): self.colormap=plt.get_cmap(colormap) else: self.colormap=colormap if over_color!=None: try: int(over_color,16) over_color='#'+over_color except ValueError: pass self.colormap.set_over(over_color,alpha=float(over_alpha)) if under_color!=None: try: int(under_color,16) under_color='#'+under_color except ValueError: pass self.colormap.set_under(under_color,alpha=float(under_alpha)) if bad_color!=None: self.colormap.set_bad(bad_color,alpha=float(bad_alpha)) self.colormap.set_gamma(float(gamma))
def _plot_colormap(self,cm): r=Renderer(colormap=plt.get_cmap(cm)) name=os.path.join(self.dir,cm+"_h.png") if not os.path.exists(name): f=open(name,'wb') r.write_h_colorbar(f) f.close() name=os.path.join(self.dir,cm+"_v.png") if not os.path.exists(name): f=open(name,'wb') r.write_v_colorbar(f) f.close()
def plot_2d(params_dir): model_dirs = [name for name in os.listdir(params_dir) if os.path.isdir(os.path.join(params_dir, name))] if len(model_dirs) == 0: model_dirs = [params_dir] colors = plt.get_cmap('plasma') plt.figure(figsize=(20, 10)) ax = plt.subplot(111) ax.set_xlabel('Learning Rate') ax.set_ylabel('Error rate') i = 0 for model_dir in model_dirs: model_df = pd.DataFrame() for param_path in glob.glob(os.path.join(params_dir, model_dir) + '/*.h5'): param = dd.io.load(param_path) gd = {'learning rate': param['hyperparameters']['learning_rate'], 'momentum': param['hyperparameters']['momentum'], 'dropout': param['hyperparameters']['dropout'], 'val. objective': param['best_epoch']['validate_objective']} model_df = model_df.append(pd.DataFrame(gd, index=[0]), ignore_index=True) if i != len(model_dirs) - 1: ax.scatter(model_df['learning rate'], model_df['val. objective'], s=128, marker=(i+3, 0), edgecolor='black', linewidth=model_df['dropout'], label=model_dir, c=model_df['momentum'], cmap=colors) else: im = ax.scatter(model_df['learning rate'], model_df['val. objective'], s=128, marker=(i+3, 0), edgecolor='black', linewidth=model_df['dropout'], label=model_dir, c=model_df['momentum'], cmap=colors) i += 1 plt.colorbar(im, label='Momentum') plt.legend() plt.show() plt.savefig('{}.eps'.format(os.path.join(IMAGES_DIRECTORY, 'params2d')), format='eps', dpi=1000) plt.close()
def visualize(y_true,y_pred,img): score = accuracy_score(y_true, y_pred) print '\n accuracy score : ', score h, w = img.shape target_pred = y_pred.reshape(h, w) target_true = y_true.reshape(h, w) fig1 = plt.figure(1) plt.imshow(img, cmap=plt.get_cmap('gray')) plt.hold(True) plt.imshow(target_pred, alpha=0.7) plt.title('Predicted target - accuracy_score : %s' % round(score, 3)) fig2 = plt.figure(2) plt.imshow(img, cmap=plt.get_cmap('gray')) plt.hold(True) plt.imshow(target_true, alpha=0.7) plt.title('True target') plt.show()
def __display_clusters(centers, clusters, iterations, name, suffix, place): fig = pylab.figure() ax = fig.add_subplot(111) N = len(centers) colors_id = numpy.array(range(N), dtype=numpy.float32) / (N - 1) cm = pylab.get_cmap('jet') colors = cm(colors_id) cid = 0 for c in clusters: for p in c: x = p[0] if p.shape[0] > 1: y = p[1] else: y = 0 ax.scatter([x], [y], c=colors[cid], marker='o') cid += 1 cid = 0 for c in centers: x = c[0] if c.shape[0] > 1: y = c[1] else: y = 0 ax.scatter([x], [y], c=colors[cid], s=200, marker='^') cid += 1 #ax.set_ylabel('True positive rate') #ax.set_xlabel('False positive rate') title = name + ' clustering' title += '\n' + filename title += ' [' + place + '] ' title += ' [iterations=' + str(iterations) if data_size != 0: title += ' data size=' + str(data_size) title += ']' ax.set_title(title) ofname = filename + suffix + "_clustering_" + name + "_" + place pylab.savefig(ofname + ".pdf") pylab.savefig(ofname + ".eps") pylab.savefig(ofname + ".svg")
def draw_cool_graph(G, fig_no=1, node_size=100): colors = [deg for _, deg in G.degree_iter()] fig = plt.figure(fig_no) fig.clear() nx.draw_spring(G, node_color=colors, vmin=min(colors), vmax=max(colors), cmap=plt.get_cmap('cool'), node_size=node_size, alpha=.5, width=.3, edge_color="#FFFFFF" ) fig.set_facecolor("#000000") return fig
def plot(lon, lat, lonn, latn, nv, var1, var2, actions, m, ax, fig, **kwargs): patch1 = None aspect = kwargs.get('aspect', None) height = kwargs.get('height') width = kwargs.get('width') norm = kwargs.get('norm') cmap = get_cmap(kwargs.get('cmap', 'jet')) cmin = kwargs.get('cmin', "None") cmax = kwargs.get('cmax', "None") magnitude = kwargs.get('magnitude', "False") topology_type = kwargs.get('topology_type', 'node') fig.set_figheight(height/80.0) fig.set_figwidth(width/80.0) if var1 is not None: if var2 is not None: mag = np.sqrt(var1**2 + var2**2) else: if magnitude == "True": mag = np.abs(var1) else: mag = var1 mag = mag.squeeze() if "facets" in actions: facet(lon, lat, lonn, latn, mag, nv, m, ax, norm, cmin, cmax, cmap, topology_type, kwargs) elif "vectors" in actions: vectors(lon, lat, lonn, latn, var1, var2, mag, nv, m, ax, norm, cmap, magnitude, topology_type) elif "unitvectors" in actions: unit_vectors(lon, lat, lonn, latn, var1, var2, mag, nv, m, ax, norm, cmap, magnitude, topology_type) #elif "streamlines" in actions: # streamlines(lon, lat, lonn, latn, var1, var2, mag, m, ax, norm, cmap, magnitude, topology_type) elif "barbs" in actions: barbs(lon, lat, lonn, latn, var1, var2, mag, m, ax, norm, cmin, cmax, cmap, magnitude, topology_type) else: lonmin = kwargs.get("lonmin") latmin = kwargs.get("latmin") lonmax = kwargs.get("lonmax") latmax = kwargs.get("latmax") dataset = kwargs.get("dataset") continuous = kwargs.get("continuous") projection = kwargs.get("projection") if "pcolor" in actions: fig, m = pcolor(lon, lat, lonn, latn, mag, nv, m, ax, norm, cmap, topology_type, fig, height, width, lonmin, latmin, lonmax, latmax, dataset, continuous, projection) elif "filledcontours" in actions: fig, m = fcontour(lon, lat, lonn, latn, mag, nv, m, ax, norm, cmin, cmax, cmap, topology_type, fig, height, width, lonmin, latmin, lonmax, latmax, dataset, continuous, projection) elif "contours" in actions: fig, m = contour(lon, lat, lonn, latn, mag, nv, m, ax, norm, cmin, cmax, cmap, topology_type, fig, height, width, lonmin, latmin, lonmax, latmax, dataset, continuous, projection) return fig, m
def make_xy_plot(graph, tag_1, tag_2): import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx Lead = np.log10( np.array(self.data['Lead (ppb)']) + 1.0 ) plt.figure(figsize=(20,20)) jet = plt.get_cmap('seismic') cNorm = colors.Normalize(vmin=0.3, vmax=1.3) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) for x, y, col in zip(np.array(self.data[tag_1]), np.array(self.data[tag_2]), Lead): colorVal = scalarMap.to_rgba(col) plt.plot(x, y, '.', color=colorVal) plt.savefig('./output/graph_vis/Lead.png', bbox_inches='tight')
def __init__( self, colour=None, symbol=None, label=None, level_names=None, colour_map=None, colour_bar_title=None, size=5, colours=None): self.colour = colour self.symbol = symbol self.label = label self.level_names = level_names self.colour_map = get_cmap(colour_map) self.colour_bar_title = colour_bar_title self.size = size self.colours = colours
def plot_color_multigraph(G, graph_colors, n_rows, n_cols, node_size=100, fig_no=1): fig = plt.figure(fig_no) fig.clear() for k, (name, colors) in enumerate(graph_colors): plt.subplot(n_rows, n_cols, k + 1) plt.title(name, color='white') nx.draw_graphviz(G, # this is expensive but at least it's consistent. node_color=colors, vmin=min(colors), vmax=max(colors), cmap=plt.get_cmap('cool'), alpha=.5, width=.3, edge_color="#FFFFFF", node_size=node_size ) fig.set_facecolor("#000000") return fig
def sliderupdate(val): val = int(val) nonzeroc = len(np.nonzero(self.mmc.classvec_ws)[0]) if val > nonzeroc: claims = val - nonzeroc newclazz = 1 elif val < nonzeroc: claims = nonzeroc - val newclazz = 0 else: return print 'Claimed', claims, 'points for class', newclazz #val, nonzeroc, claims self.claims = claims mmc.claim_n_points(claims, newclazz) steepness_vector = mmc.compute_steepness_vector() X = [steepness_vector, steepness_vector] self.slider_axis2.imshow(X, cmap=plt.get_cmap("Oranges")) self.slider_axis2.set_aspect('auto') self.redrawall(newslider = False) #HACK! self.prevnewclazz = newclazz
def init(self, data_len): """ Initialize plots. """ self._t = 0 self._data_len = data_len self._data = np.empty((0, data_len)) cm = plt.get_cmap('spectral') self._plots = [] for i in range(data_len): color = cm(1.0 * i / data_len) alpha = self._alphas[i] if self._alphas is not None else 1.0 label = self._labels[i] if self._labels is not None else str(i) self._plots.append( self._ax.plot([], [], color=color, alpha=alpha, label=label)[0] ) self._ax.set_xlim(0, self._time_window) self._ax.set_ylim(0, 1) self._ax.legend(loc='upper left', bbox_to_anchor=(0, 1.15)) self._init = True
def plot_contour_2d(xi, yi, zi, x=None, y=None, var=None, norm=False, figsize=None): if x is None: x = [] if y is None: y = [] if figsize is None: figsize = (w, golden_mean * w) fig = plt.figure(figsize=figsize, facecolor='white') ax = fig.add_subplot(1, 1, 1) xig, yig = np.meshgrid(xi, yi) x_min, y_min = map(np.nanmin, (xi, yi)) x_max, y_max = map(np.nanmax, (xi, yi)) ax.set_ylim([y_min, y_max]) ax.set_xlim([x_min, x_max]) ax.set_xlabel("Packet Emission Rate (pps)") ax.set_ylabel("Average Node Separation (m)") if norm: vmin, vmax = 0.0, 1.0 else: vmin = np.nanmin(abs(zi)) vmax = np.nanmax(abs(zi)) cset = ax.contourf(zi, alpha=0.75, # hatches=['+','x','-', '/', '\\', '//'], cmap=plt.get_cmap('hot_r'), vmin=vmin, vmax=vmax, extent=[x_min, x_max, y_min, y_max] ) cbar = fig.colorbar(cset) if var is not None: # ax.set_title("{} with varying Packet Emission and Node Separations".format(var)) cbar.set_label(var) if len(x) and len(y): ax.scatter(x, y, color='k', marker='.', s=1) # ax.clabel(cset,inline=1) return fig
def plot_field_2D(file,out=None,filter=lambda d:d,cmap_func=lambda min,max: plt.get_cmap('jet'),opts={}): if out==None: out=os.path.dirname(file) LOG.debug('Plotting file %s to %s',file,out) # Open the hdf5 data h5file=h5py.File(file,'r') try: field=h5file.attrs['field'] # Get the 2D data, timesteps, x and z dset=h5file['/data'] dmax=dset.attrs['max'] dmin=dset.attrs['min'] cmap=cmap_func(dmin,dmax) frames=h5file['/frame'] path, ext = os.path.splitext(file) # get the prefix_fieldname # extent=(left,right,bottom,top) x=h5file['x'].value z=h5file['z'].value extent=(0,(x[0]+x[-1])/1e3,0,(z[0]+z[-1])/1e3) figname=os.path.join(out,os.path.basename(path)+'%05d.png') plot_frames_2D(frames,dset.value[:,:,0,:],figname,mm=(dmin,dmax),title=field,filter=filter,cmap=cmap,extent=extent) finally: h5file.close()