def get_dataset_color(dataset,depth=None): """Set the colors to ensure a uniform scheme for each dataset """ dataset=string.lower(dataset) d={} d["dai"]=cm.Blues(.5) d["tree"]=cm.summer(.3) d["cru"]=cm.Blues(.9) #models d["picontrol"]=cm.Purples(.8) d["h85"]="k" d["tree_noise"]=cm.PiYG(.2) #Soil moisture d["merra2"]={} d["merra2"]["30cm"]=cm.copper(.3) d["merra2"]["2m"]=cm.copper(.3) d["gleam"]={} d["gleam"]["30cm"]=cm.Reds(.3) d["gleam"]["2m"]=cm.Reds(.7) if depth is None: return d[dataset] else: return d[dataset][depth]
def compare_voxels_single_view(vol1, vol2, elev_azim=(30,45)): fig = plt.figure(figsize=(20, 10)) ##### VOLUME 1 ###### ax = fig.add_subplot(1, 2, 1, projection='3d') colors = np.zeros(vol2.shape + (4,)) # colors[:, :, :, 2] = 1 colors = cm.Blues(vol1) colors[:, :, :, -1] = 0.5 ax.voxels(vol1, facecolors=colors) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.view_init(*elev_azim) ##### VOLUME 2 ####### facecolors = cm.Blues(vol2) facecolors[:, :, :, -1] = 0.5 # vol2 # facecolors = np.zeros(vol2.shape + (4,)) + 0.5 # facecolors[:,:,:,2] = 1-vol2[:,:,:] # # facecolors[:,:,:,3] = vol2[:,:,:] ax = fig.add_subplot(1, 2, 2, projection='3d') ax.voxels(vol2, facecolors=facecolors) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.view_init(*elev_azim) ## Colorbar cmap = mpl.cm.Blues norm = mpl.colors.Normalize(vmin=0, vmax=1) cbaxes = fig.add_axes([0.5, 0.3, 0.03, 0.5]) cb1 = mpl.colorbar.ColorbarBase(ax=cbaxes, cmap=cmap, norm=norm, orientation='vertical') plt.show()
def get_color(self, watson, gene_type): colors = { "Verified": cm.Blues(0.7), "Putative": cm.Blues(0.35), "Dubious": "#898888" } if not watson: colors['Verified'] = cm.Reds(0.5) colors['Putative'] = cm.Reds(0.3) colors['Uncharacterized'] = colors['Putative'] color = colors[gene_type] return color
def plot_single_trajectory(t, ts, ax, thr=0.3): # plot absolute from matplotlib import cm ax[0].set_ylim(-5, 5000) #np.round((np.max(ts[2])/1000)+1)*1000) lineages = [['1.p', '1.pp', '1.ppp'], ['4.a', '4.aa', '4.aaa']] col = np.array([ np.array([ cm.Blues(int(i))[:3] for i in (np.arange(len(lineages[0])) * 254. / (len(lineages[0]) - 1) / 254.) * 127 + 127 ]), np.array([ cm.Reds(int(i))[:3] for i in (np.arange(len(lineages[0])) * 254. / (len(lineages[0]) - 1) / 254.) * 127 + 127 ]) ]) for c in [0, 1]: for j in [0, 1, 2]: ax[0].plot(t[j] / 60., ts[j][:, c], '-', color=col[c, j], lw=2) # plot ratio col = 'kcm' diff_D = [] for j in [0, 1, 2]: diff_D.append( (ts[j][:, 0] - ts[j][:, 1]) / (ts[j][:, 0] + ts[j][:, 1])) ax[1].plot(t[j] / 60., diff_D[j], '-' + col[j], lw=2) # get T_decision (AC_id, T_dec, ind) = get_T_decision(t, ts, 0.3) # and plot in figure if len(ind) > 0: ax[1].plot(t[ind[0]][ind[1]] / 60., diff_D[ind[0]][ind[1]], 'ok')
def channels_chart(data_id, image_uid, user_name): """Plots a user's most active channels""" # Open our file from S3 and read in the data_file_name = f'/tmp/{data_id}-channels.csv.gz' df = pd.read_csv(data_file_name, compression='gzip', encoding='utf-8') # Some data transformations df['datetime'] = df['timestamp'].apply( lambda t: dt.datetime.fromtimestamp(t)) df['day'] = df['datetime'].apply(lambda t: t.strftime("%A")) df['date'] = df['datetime'].apply(lambda t: t.date()) ch_gb = df.groupby('channel') pie_labels = ch_gb['timestamp'].count().index.values pie_values = ch_gb['timestamp'].count().values # Make the channels pie chart fig, ax = plt.subplots() color_scale = cm.Blues( np.flip(np.arange(pie_labels.size)) / pie_labels.size) ax.pie(pie_values, labels=pie_labels, autopct='%1.1f%%', explode=[0.05] * pie_labels.size, colors=color_scale) ax.set_title(f'{user_name}\'s Favorite Channels') file_name_channels = f'{image_uid}-pie-chart-channels.png' fig.savefig(f'/tmp/{file_name_channels}') return file_name_channels
def scale_colors(sizes, shapes): """ Scales colors so they aren't all faded out. Returns R/G/B scales. :param sizes: List of sizes :param shapes: List of shapes :return: Colormap object """ size_set = sorted(list(set(sizes))) linspace = np.linspace(0.2, 1, len(size_set)) redmap = cm.Reds(linspace) greenmap = cm.Greens(linspace) bluemap = cm.Blues(linspace) colors = [] for size, shape in zip(sizes, shapes): if shape == "icosahedron": # Red colors.append(redmap[size_set.index(size)]) elif shape == "elongated-pentagonal-bipyramid": # Green colors.append(greenmap[size_set.index(size)]) elif shape == "cuboctahedron": # Blue colors.append(bluemap[size_set.index(size)]) else: raise ValueError return colors
def draw_vapor(init, end): for f in td_files[init:end]: print(f) ##### retrieve variables ##### dt = netCDF4.Dataset(f) t = int(np.array(dt['Time'])) qc = dt['qc'][0, :len(z), y_prof, xslice] #qv = dt['qv'][0, :len(z), y_prof, :] qr = dt['qr'][0, :len(z), y_prof, xslice] ##### draw qv ##### #qv = np.ma.masked_array(qv, qv<1e-10) #contourf(x, z, qv, levels=50, vmin=0., vmax=0.02, cmap='Blues') #colorbar(extend='max') ##### draw qc ##### colors = cm.Greys( np.hstack([np.array([0.] * 5), np.linspace(0.5, 0.75, 95)])) cmap = LinearSegmentedColormap.from_list('name', colors) #cmap.set_bad('white') qc = np.ma.masked_array(qc, qc < 0.0) contourf(x, z, qc, cmap=cmap, vmin=0, vmax=0.001, levels=100) colorbar() ##### draw qr ##### cmap = nclcmap('BrownBlue12') colors = cm.Blues(np.linspace(0.5, 1)) cmap = LinearSegmentedColormap.from_list('name', colors) qr = np.ma.masked_array(qr, qr <= 1e-6) #5e-6) contourf(x, z, qr, cmap=cmap, vmin=0., vmax=0.01, alpha=.5, levels=20) ##### figure setting ##### title('Vapor Distribution @ t = ' + str(t) + ' min') xlabel('X (m)') ylabel('Z (m)') savefig('vapor' + f[-9:-3] + '.png', dpi=300) clf()
def plot_particle_samples(ax, sample=10, draw_hdg=None): sortidx = np.argsort(PTC_AGE[::sample])[::-1] X = PTC_X[::sample][sortidx] Y = PTC_Y[::sample][sortidx] WX = PTC_WX[::sample][sortidx] WY = PTC_WY[::sample][sortidx] AGE = PTC_AGE[::sample][sortidx] if max(AGE) == min(AGE): Color = "gray" else: Color = cm.Blues(1 + 0.2 - (AGE - min(AGE)) / (max(AGE) - min(AGE))) ax.scatter(X, Y, s=3, color=Color) if draw_hdg: for i, (x, y, wx, wy) in enumerate(zip(X, Y, WX, WY)): ax.plot([x, x + wx / 2], [y, y + wy / 2], color="k", alpha=0.5, lw=1) ax.set_xlim([0, AREA]) ax.set_ylim([0, AREA]) ax.set_aspect("equal")
def get_strand_colors(num_times=6): # colors color_offset = 2 N = num_times + color_offset blues = map(lambda x: cm.Blues(float(x) / (N), 1), range(color_offset, N)) reds = map(lambda x: cm.Reds(float(x) / (N), 1), range(color_offset, N)) return reds, blues
def plot_all(self, site_name, analyzer_name, samples, clim): analyzer = self.get_site_analyzer(site_name, analyzer_name) fname = os.path.join(self.directory, '%s_%s_all' % (site_name, analyzer_name)) fig = plt.figure(fname, figsize=(4, 3)) cmin, cmax = clim for iteration, iter_samples in samples.groupby('iteration'): analyzer_data = self.get_analyzer_data(iteration, site_name, analyzer_name) results_by_sample = iter_samples.reset_index().set_index( 'sample')['total'] for sample, result in results_by_sample.iteritems(): analyzer.plot_comparison(fig, analyzer_data['samples'][sample], fmt='-', color=cm.Blues( (result - cmin) / (cmax - cmin)), alpha=0.5, linewidth=0.5) analyzer.plot_comparison(fig, analyzer_data['ref'], fmt='-o', color='#8DC63F', alpha=1, linewidth=1, reference=True) fig.set_tight_layout(True) plt.savefig(fname + '.png', format='PNG') plt.close(fig)
def get_ib_config(): nodes = [4, 8, 16, 32] fpaths, tags, legends, colors = [], [], [], [] ps_ib_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ps_ib_tags = [ 'SIMPLE-PS-SGD-4IB', 'SIMPLE-PS-SGD-8IB', 'SIMPLE-PS-SGD-16IB', 'SIMPLE-PS-SGD-32IB-4' ] ps_ib_legends = [ 'SGP 4 nodes', 'SGP 8 nodes', 'SGP 16 nodes', 'SGP 32 nodes' ] ps_ib_colors = [ cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_ib_tags)) ] fpaths.append(ps_ib_fpath) tags.append(ps_ib_tags) legends.append(ps_ib_legends) colors.append(ps_ib_colors) ar_ib_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ar_ib_tags = [ 'AR-DPSGD-CPUCOMM-4IB-SCRATCh', 'AR-DPSGD-CPUCOMM-8IB-SCRATCh', 'AR-DPSGD-CPUCOMM-16IB-SCRATCh', 'AR-DPSGD-CPUCOMM-32IB-SCRATCH' ] ar_ib_legends = [ 'AR-SGD 4 nodes', 'AR-SGD 8 nodes', 'AR-SGD 16 nodes', 'AR-SGD 32 nodes' ] ar_ib_colors = [cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_ib_tags))] fpaths.append(ar_ib_fpath) tags.append(ar_ib_tags) legends.append(ar_ib_legends) colors.append(ar_ib_colors) return nodes, fpaths, tags, legends, colors
def plot_3D_infl(sim, vmax=None): """ Plots infiltration `infl_2d` on incline Parameters ---------- sim vmax """ fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(111, projection='3d') ax = fix_3D_axes(ax) if not vmax: vmax = np.percentile(sim.infl_2d, 99) norm = plt.Normalize(vmin=0, vmax=vmax) colors = cm.Blues(norm(sim.infl_2d)) ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) xc = sim.xc yc = sim.yc topo = sim.zc ax.plot_surface(xc, yc, topo, facecolors=colors, rstride=1, cstride=1, linewidth=0, antialiased=False, shade=False) ax.view_init(25, 295) return fig
def plot_particle_samples(ax, sample=10, draw_hdg=None): sortidx = np.argsort(PTC_AGE[::sample])[::-1] X = PTC_X[::sample][sortidx] Y = PTC_Y[::sample][sortidx] VX = PTC_WVX[::sample][sortidx] VY = PTC_WVY[::sample][sortidx] AGE = PTC_AGE[::sample][sortidx] if max(AGE) == min(AGE): Color = 'gray' else: Color = cm.Blues(1 + 0.2 - (AGE - min(AGE)) / (max(AGE) - min(AGE))) ax.scatter(X, Y, s=3, color=Color) if draw_hdg: for i, (x, y, vx, vy) in enumerate(zip(X, Y, VX, VY)): ax.plot([x, x + vx / 2], [y, y + vy / 2], color='k', alpha=0.5, lw=1) ax.set_xlim([0, AREA]) ax.set_ylim([0, AREA]) ax.set_aspect('equal')
def plot_U_surface(sim, scale=20): sim['umag'] = np.sqrt(sim.uc ** 2 + sim.vc ** 2) fig = plt.figure(figsize=(15, 8)) ax = fig.add_subplot(111, projection='3d') ax = fix_3D_axes(ax) norm = plt.Normalize() veg = sim.veg.copy() veg[-1, 0] = -0.3 veg[-1, -1] = 1.5 veg_colors = cm.Greens(norm(veg)) h_norm = colors.Normalize(vmin=10 * sim.umag.ravel().min() - .01, vmax=10 * sim.umag.ravel().max()) h_colors = cm.Blues(h_norm(sim.umag[sim.i_tr] * 10.)) ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.plot_surface(sim.xc, sim.yc + 1, sim.zc * 0, facecolors=veg_colors, rstride=1, cstride=1, alpha=0.9, linewidth=0, antialiased=True, shade=False) ax.plot_surface(sim.xc, sim.yc + 1, sim.zc + sim.hc[sim.i_tr] * scale, facecolors=h_colors, rstride=1, cstride=1, linewidth=0, antialiased=True, shade=False, alpha=0.8) ax.view_init(25, 285) return fig, ax
def plot_particle_samples(mp, ax, zlevel, sample=10, draw_hdg=None): mask = (mp.PTC_Z > zlevel-mp.GRID_BOND_Z) & (mp.PTC_Z < zlevel+mp.GRID_BOND_Z) if len(mp.PTC_X[mask]) < 2: return sortidx = np.argsort(mp.PTC_AGE[mask][::sample])[::-1] xs = mp.PTC_X[mask][::sample][sortidx] ys = mp.PTC_Y[mask][::sample][sortidx] vxs = mp.PTC_WX[mask][::sample][sortidx] vys = mp.PTC_WY[mask][::sample][sortidx] ages = mp.PTC_AGE[mask][::sample][sortidx] if max(ages) == min(ages): Color = 'gray' else: Color = cm.Blues(1 + 0.2 - (ages-min(ages))/(max(ages)-min(ages))) ax.scatter(xs, ys, s=3, color=Color) if draw_hdg: for i, (x, y, vx, vy) in enumerate(zip(xs, ys, vxs, vys)): ax.plot([x, x+vx/2], [y, y+vy/2], color='k', alpha=0.5, lw=1) ax.set_xlim(mp.AREA_XY) ax.set_ylim(mp.AREA_XY) ax.set_aspect('equal')
def plotBars(df, valCol, fileName): #print df #xlabels = list(set(list([val[0] for val in df[[0]].values]))) xlabels = ["512", "1024", "2048", "4096"] print(xlabels) xs = range(len(xlabels)) xx = list(set(list([val[0] for val in df[[1]].values]))) w = 1.0 / (len(xx) + 1.0) i = 0 for tileSize in xx: fdf = df.loc[df[' TileSize'] == tileSize] plt.bar(np.array(xs) + i * w, [ float(str(val[0]).strip().replace(',', '.')) for val in fdf[[valCol]].values ], width=w, label=str(tileSize) + 'x' + str(tileSize), color=cm.Blues((i + 2) * 70), ecolor='black') i += 1 plt.xticks(np.array(xs) + w * len(xlabels) / 3, xlabels) plt.legend(loc='best', ncol=1, fontsize=24) plt.suptitle('Aplicação GoL', fontsize=27) plt.xlabel(df.columns[0], fontsize=27) # plt.ylabel(df.columns[valCol], fontsize=18) plt.xlim(-0.15, 3.9) plt.ylim(0, 140) plt.grid(which='major', axis='y') plt.tick_params(labelsize=27) plt.tick_params(pad=12) # fig.suptitle('Aplicação Fur', fontsize=20) #plt.tick_params(width=2) plt.savefig(fileName, bbox_inches='tight') plt.clf()
def _create_plot_component(self): self.ax1 = self.figure.add_subplot(311) self.ax2 = self.figure.add_subplot(312) self.ax3 = self.figure.add_subplot(313) self.figure.subplots_adjust(bottom=0.05, top=0.95, left=0.05, right=0.95) self.spectrogram_data = np.full((NUM_SAMPLES / 2, SPECTROGRAM_LENGTH), -90) x2 = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / float(SAMPLING_RATE) y2 = SAMPLING_RATE / 2.0 self.image_spectrogram = self.ax1.imshow(self.spectrogram_data, aspect="auto", vmin=-90, vmax=0, origin="lower", extent=[0, x2, 0, y2]) self.frequency = np.linspace(0., y2, num=NUM_SAMPLES / 2) self.time = np.linspace(0., float(NUM_SAMPLES) / SAMPLING_RATE, num=NUM_SAMPLES, endpoint=False) for i in range(NUM_LINES): self.ax2.plot(self.frequency, np.zeros_like(self.frequency), color=cm.Blues(float(i + 1) / (NUM_LINES + 1))) self.line_wave, = self.ax3.plot(self.time, np.zeros_like(self.time)) self.ax3.set_ylim(-1, 1) self.ax3.set_xlim(0, self.time[-1])
def plot_scope_records(scope_records, scope_input_channel, scope_time=0): """ Helper function to plot scope records. """ colors = [ cm.Blues(np.linspace(0, 1, len(scope_records))), cm.Greens(np.linspace(0, 1, len(scope_records))) ] for index, record in enumerate(scope_records): totalsamples = record[0]['totalsamples'] wave = record[0]['wave'][scope_input_channel, :] if not record[0]['channelmath'][scope_input_channel] & 2: # We're in time mode: Create a time array relative to the trigger time. dt = record[0]['dt'] # The timestamp is the timestamp of the last sample in the scope segment. timestamp = record[0]['timestamp'] triggertimestamp = record[0]['triggertimestamp'] t = np.arange(-totalsamples, 0) * dt + ( timestamp - triggertimestamp) / float(clockbase) plt.plot(1e6 * t, wave, color=colors[scope_input_channel][index]) elif record[0]['channelmath'][scope_input_channel] & 2: # We're in FFT mode. scope_rate = clockbase / 2**scope_time f = np.linspace(0, scope_rate / 2, totalsamples) plt.semilogy(f / 1e6, wave, color=colors[scope_input_channel][index]) plt.draw() plt.grid(True) plt.ylabel('Amplitude [V]') plt.autoscale(enable=True, axis='x', tight=True)
def plot_compare_phi_psi(neurons, epsilon_values, tau_y_values, psi_values): '''This only works for summary type saves.''' fig, axs = plt.subplots(1, len(psi_values), sharey=True, figsize=(5*len(psi_values)+2, 5)) cm_section = np.linspace(0.3, 1, len(tau_y_values)) colours = [] colours.append([ cm.Blues(x) for x in cm_section ]) colours.append([ cm.Oranges(x) for x in cm_section ]) colours.append([ cm.Purples(x) for x in cm_section ]) colours.append([ cm.Greens(x) for x in cm_section ]) for j, epsilon in enumerate(epsilon_values): for k, tau_y in enumerate(tau_y_values): label = "$\\tau_y={}$, $\epsilon={}$".format(tau_y,epsilon) E = [] phi_values = [] for i in range(len(psi_values)): E.append([]) phi_values.append([]) for neuron in neurons: if neuron.hyper['psi'] in psi_values: phi_values[psi_values.index(neuron.hyper['psi'])].append(neuron.hyper['phi']) for log in neuron.logs: if log[0]['tau_y'] == tau_y and log[0]['epsilon'] == epsilon: E[psi_values.index(neuron.hyper['psi'])].append(log[2]-log[3]) for i in range(len(psi_values)): if i == 0: axs[i].plot(phi_values[i], E[i], label=label, color=colours[j][k]) axs[i].set_ylabel('$E$') else: axs[i].plot(phi_values[i], E[i], color=colours[j][k]) axs[i].set_title('$\psi={}$'.format(psi_values[i])) axs[i].set_xlabel('$\phi$') fig.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # fig.legend(loc='upper center', bbox_to_anchor=(0.5, -0.02), fancybox=True, shadow=True, ncol=6) fig.tight_layout() plt.show() return fig
def threeColorScales(number_of_lines, start=0.2, stop=1.0): cm_subsection = np.linspace(start, stop, number_of_lines) colorsBlue = [cm.Blues(x) for x in cm_subsection] colorsRed = [cm.Reds(x) for x in cm_subsection] colorsGreen = [cm.Greens(x) for x in cm_subsection] allColors = [colorsBlue, colorsRed, colorsGreen] return allColors
def get_eth_config(): nodes = [4, 8, 16, 32] fpaths, tags, legends, colors = [], [], [], [] ar_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ar_eth_tags = [ 'AR-DPSGD-CPUCOMM-4ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-8ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-16ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-32ETH-SCRATCH' ] ar_eth_legends = [ 'AR-SGD 4 nodes', 'AR-SGD 8 nodes', 'AR-SGD 16 nodes', 'AR-SGD 32 nodes' ] ar_eth_colors = [ cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_eth_tags)) ] fpaths.append(ar_eth_fpath) tags.append(ar_eth_tags) legends.append(ar_eth_legends) colors.append(ar_eth_colors) ds_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ds_eth_tags = [ 'SDS-SGD-4ETH', 'SDS-SGD-8ETH', 'SDS-SGD-16ETH', 'SDS-SGD-32ETH' ] ds_eth_legends = [ 'D-PSGD 4 nodes', 'D-PSGD 8 nodes', 'D-PSGD 16 nodes', 'D-PSGD 32 nodes' ] ds_eth_colors = [ cm.Greens(x) for x in np.linspace(0.3, 0.8, len(ds_eth_tags)) ] fpaths.append(ds_eth_fpath) tags.append(ds_eth_tags) legends.append(ds_eth_legends) colors.append(ds_eth_colors) ps_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ps_eth_tags = [ 'PS-SGD-4ETH-CHORD', 'PS-SGD-8ETH-CHORD', 'PS-SGD-16ETH-CHORD', 'PS-SGD-32ETH-SCRATCH-CHORD' ] ps_eth_legends = [ 'SGP 4 nodes', 'SGP 8 nodes', 'SGP 16 nodes', 'SGP 32 nodes' ] ps_eth_colors = [ cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_eth_tags)) ] fpaths.append(ps_eth_fpath) tags.append(ps_eth_tags) legends.append(ps_eth_legends) colors.append(ps_eth_colors) # return nodes, fpaths[::-1], tags[::-1], legends[::-1], colors[::-1] return nodes, fpaths, tags, legends, colors
def get_colour(): colour_dict = dict() num_range = np.linspace(256, 1, 10) index = 1 for num in num_range: colour = cm.Blues(int(num)) rgb_colour = "rgb({},{},{})".format(int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255)) colour_dict[index] = rgb_colour index += 1 return colour_dict
def get_colors(color_c=3, color_step=100): cmap_colors = np.vstack(( cm.Oranges(np.linspace(0.4, 1, color_step)), cm.Reds(np.linspace(0.4, 1, color_step)), cm.Greys(np.linspace(0.4, 1, color_step)), cm.Purples(np.linspace(0.4, 1, color_step)), cm.Blues(np.linspace(0.4, 1, color_step)), cm.Greens(np.linspace(0.4, 1, color_step)), cm.pink(np.linspace(0.4, 1, color_step)), cm.copper(np.linspace(0.4, 1, color_step)), )) return cmap_colors[np.arange(color_c * color_step) % (color_step * 8)]
def colorregions(region): """Set the colors to ensure a uniform scheme for each region """ d={} d["ALL"]="k" d["NHDA"]=cm.gray(.5) d["NADA"]=cm.Purples(.5) d["OWDA"]=cm.Blues(.5) d["MXDA"]=cm.PiYG(.1) d["ANZDA"]=cm.PiYG(.8) d["MADA"]=cm.Oranges(.5) d["GDA"]="k" return d[region]
def to_heatmap(gcam, start_r, end_r, color='red'): if start_r != -1 and end_r != -1: gcam[0:start_r, ...] = 0 gcam[end_r:, ...] = 0 alpha = gcam[..., None] * PROB_WEIGHT alpha[alpha > 1.0] = 1.0 if color == 'red': cmap = cm.Reds(gcam)[..., :3] * 255.0 else: cmap = cm.Blues(gcam)[..., :3] * 255.0 cmap = cmap[..., ::-1] cmap = cmap.astype(np.float) return cmap, alpha
def to_grapf(parsentage, title): fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(1, 1, 1) ax.bar([x for x in range(20)], parsentage.values[:20], color=cm.Blues(50 + 20 * (c + 1))) ax.yaxis.set_major_formatter(FormatStrFormatter('%.d%%')) plt.title(title) plt.xticks([x for x in range(20)], parsentage.index.values[:20], rotation=270) fig.subplots_adjust(bottom=0.2) plt.savefig("grapf/" + title + ".png")
def plot_hardness(ax): plt.setp(ax.get_yticklabels(), visible=False) # Add grid following the layering im = ax.barh(self.layers_bot - (self.layers_bot - self.layers_top) / 2, self.layers_hardness_index, self.layers_bot - self.layers_top, color=cm.Blues(self.layers_hardness_index / 6), edgecolor='k', linewidth=0.5) ax.set_xlim(0, 7) ax.set_title("Hardness") labels_ax = ['', 'Fist', '4F', '1F', 'P', 'K', 'I'] ax.set_xticklabels(labels_ax, rotation=45) ax.xaxis.set_major_locator(MaxNLocator(integer=True, prune='upper')) return im
def plot_3D_fhU(sim, h_scale=None, ind=None): """ """ if not h_scale: h_scale = int(sim.zc.max() / sim.hc.max() / 3.) if not ind: ind = sim.i_tr fig = plt.figure(figsize=(11, 6)) ax = fig.add_subplot(111, projection='3d', ) ax = fix_3D_axes(ax) veg = sim.veg.copy() veg[0, -1] = -0.2 veg[1, -1] = 1.5 norm = plt.Normalize() veg_colors = cm.Greens(norm(veg)) f_norm = colors.Normalize(vmin=sim.infl_2d.ravel().min() - .01, vmax=sim.infl_2d.ravel().max()) f_colors = cmocean.cm.deep(f_norm(sim.infl_2d)) U = np.sqrt(sim.uc ** 2 + sim.vc ** 2) U_norm = colors.Normalize(vmin=10 * U[ind].ravel().min() - .01, vmax=10 * U[ind].ravel().max()) U_colors = cm.Blues(U_norm(U[ind] * 10.)) ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.plot_surface(sim.xc, sim.yc, sim.zc, facecolors=veg_colors, rstride=1, cstride=1, linewidth=0, antialiased=True, shade=False, alpha=0.5) ax.plot_surface(sim.xc, sim.yc, sim.zc * 0, facecolors=f_colors, rstride=1, cstride=1, linewidth=0, antialiased=True, shade=False, alpha=0.8) ax.plot_surface(sim.xc, sim.yc, sim.zc + sim.hc[ind] * h_scale, facecolors=U_colors, rstride=1, cstride=1, linewidth=0, antialiased=True, shade=False, alpha=0.8) ax.view_init(25, 295) return fig, ax
def map_val_colors(img, v_min=0.0, v_max=1.0, cmap='hot'): fun = { 'hot': lambda t: cm.afmhot(colors.Normalize(vmin=v_min, vmax=v_max)(t), bytes=True), 'jet': lambda t: cm.jet(colors.Normalize(vmin=v_min, vmax=v_max)(t), bytes=True), 'Greys': lambda t: cm.Greys(colors.Normalize(vmin=v_min, vmax=v_max)(t), bytes=True), 'Blues': lambda t: cm.Blues(colors.Normalize(vmin=v_min, vmax=v_max)(t), bytes=True), } return fun[cmap](img)
def draw_month_heatmap(df): #传入当月的df day_series = df['day'].value_counts() first_time = pd.Timestamp.fromtimestamp(df['CreateTime'][0]) #转化北京时间 first_time = first_time + pd.Timedelta(hours=8) #print(first_time) #当月的首日 #print ('%02d月%02d日 星期%1d' %(first_time.month, first_time.day, first_time.dayofweek+1)) first_time = first_time - pd.Timedelta(days=first_time.day - 1) last_time = first_time + pd.Timedelta(days=first_time.daysinmonth - 1) table_height = last_time.week - first_time.week + 1 table_width = 7 datamap = np.zeros(table_width * table_height) maskmap = np.zeros(table_width * table_height) for i in range(table_height * table_width): date_in_month = i - first_time.dayofweek + 1 if date_in_month in day_series.index: datamap[i] = day_series[date_in_month] #将不在本月的数据划掉 if date_in_month <= 0 or date_in_month > first_time.daysinmonth: maskmap[i] = True # else: maskmap=False datamap = datamap.reshape((table_height, table_width)) maskmap = maskmap.reshape((table_height, table_width)) datamap = pd.DataFrame(datamap) datamap.columns = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] #print(maskmap) f, ax1 = plt.subplots(figsize=(9, 5), facecolor=cm.Blues(0)) sns.set() sns.heatmap(datamap, annot=datamap.astype('int32'), mask=maskmap, square=True, yticklabels=False, fmt="d", cmap=cm.Blues, ax=ax1, linewidths=.5) label_y = ax1.get_yticklabels() plt.setp(label_y, rotation=360, horizontalalignment='right') label_x = ax1.get_xticklabels() plt.setp(label_x, rotation=0, horizontalalignment='center', y=1.1) plt.show()