def plot_latent_sweep(latent, n_pairs): for d in range(latent.shape[1]): dim = latent[:, d] fig, ax = plt.subplots(1, 1, figsize=(10, 10)) data_df = pd.DataFrame() data_df["Label"] = n_pairs * ["Left"] + n_pairs * ["Right"] data_df["Latent"] = dim[:2 * n_pairs] data_df["Index"] = list(range(n_pairs)) + list(range(n_pairs)) ax = sns.scatterplot(data=data_df, x="Index", y="Latent", hue="Label", ax=ax, s=15) add_connections( range(n_pairs), range(n_pairs), dim[:n_pairs], dim[n_pairs:2 * n_pairs], ax=ax, color="grey", ) remove_spines(ax) ax.xaxis.set_major_locator(plt.FixedLocator([0])) ax.yaxis.set_major_locator(plt.FixedLocator([0])) ax.set_title(f"Dimension {d}")
def plotMatrix(matrix, plot_path, labels, title, ticks, vmin=-1., vmax=1.): """Plot matrix. param matrix: two dimensional array. The matrix to plot param plot_path : string. Full path and name of the plotting picture param labels: list. The labels param title: string. The title of the plot param ticks: list. The ticks of the plot vmin: float. Minimum value vmax: float. Maximum value return: None """ ticks = list(map(lambda x: x - 0.5, ticks)) ticks_middle = [(((ticks[i + 1] - ticks[i]) / 2) + ticks[i]) for i in range(0, len(ticks) - 1)] fig, ax = plt.subplots() fig.set_size_inches(16.5, 9.5) ax.xaxis.set_minor_locator(plt.FixedLocator(ticks[1:])) ax.yaxis.set_minor_locator(plt.FixedLocator(ticks[1:])) ax.grid(color='black', linestyle='-', linewidth=1.2, which='minor') plt.title(label=title, fontsize=20) plotting.plot_matrix(matrix, colorbar=True, axes=ax, vmin=vmin, vmax=vmax) plt.yticks(ticks_middle, list(labels)) plt.xticks(ticks_middle, list(labels), rotation=55, horizontalalignment='right') for item in (ax.get_xticklabels() + ax.get_yticklabels()): item.set_color(net_dic.labelToColorDic[item.get_text()]) item.set_fontsize(14) fig.savefig(plot_path) plt.close()
def visualize_samples(samples, discretized_samples, grid, low=None, high=None): """Visualize original and discretized samples on a given 2-dimensional grid.""" fig, ax = plt.subplots(figsize=(10, 10)) # Show grid ax.xaxis.set_major_locator(plt.FixedLocator(grid[0])) ax.yaxis.set_major_locator(plt.FixedLocator(grid[1])) ax.grid(True) # If bounds (low, high) are specified, use them to set axis limits if low is not None and high is not None: ax.set_xlim(low[0], high[0]) ax.set_ylim(low[1], high[1]) else: # Otherwise use first, last grid locations as low, high (for further mapping discretized samples) low = [splits[0] for splits in grid] high = [splits[-1] for splits in grid] # Map each discretized sample (which is really an index) to the center of corresponding grid cell grid_extended = np.hstack((np.array([low]).T, grid, np.array([high]).T)) # add low and high ends grid_centers = (grid_extended[:, 1:] + grid_extended[:, :-1]) / 2 # compute center of each grid cell locs = np.stack(grid_centers[i, discretized_samples[:, i]] for i in range(len(grid))).T # map discretized samples ax.plot(samples[:, 0], samples[:, 1], 'o') # plot original samples ax.plot(locs[:, 0], locs[:, 1], 's') # plot discretized samples in mapped locations ax.add_collection(mc.LineCollection(list(zip(samples, locs)), colors='orange')) # add a line connecting each original-discretized sample ax.legend(['original', 'discretized'])
def psshow(f, a, title): # Take the fourier transform of the image. f1 = fftpack.fft2(f) print(f.shape) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. f2 = fftpack.fftshift(f1) # Calculate a 2D power spectrum psd2D = np.abs(f2)**2 # Display at log 10 psd2D_log = np.log10(psd2D) min5 = np.percentile(psd2D_log, 5) print(min5) max95 = np.max(psd2D_log) print(max95) a.imshow(psd2D_log, vmin=min5, vmax=max95, cmap='gray') # Look and feel a.xaxis.set_major_locator(plt.FixedLocator([len(psd2D[0]) - 1])) a.yaxis.set_major_locator(plt.FixedLocator([len(psd2D[0]) - 1])) a.set_title(title)
def imshow(frame, a, title): # Calculate events at super resolution min5 = np.percentile(frame, 1) max95 = np.percentile(frame, 99) a.imshow(frame, vmin=min5, vmax=max95, cmap='gray') # Look and feel a.xaxis.set_major_locator(plt.FixedLocator([len(frame[0]) - 1])) a.yaxis.set_major_locator(plt.FixedLocator([len(frame[0]) - 1])) a.set_title(title) return frame
def obspred_plot(paramsplot, fityrs, startage, endage, trans = 'none', trans_time_coords = False, trans_y_coords = False): obsframe = paramsplot['test'].rx2('obs') ptype = paramsplot['ptype'] obsage = obsframe.rx2('age') predage = base.seq(startage, endage, by = 5) xlinlab = r'$\mathrm{log}(t)$' ratelinlab = r'$\mathrm{log}(r(t))$' survlinlab = r'$\mathrm{log}[-\mathrm{log}[S(t)]]$' plotlabs = {'none': {'x': '$t$', 'rate': '$r(t)$', 'surv': '$S(t)$'}, 'gomp_lin': {'x': '$t$', 'rate': ratelinlab, 'surv': survlinlab}, 'weib_lin': {'x': xlinlab,'rate': ratelinlab, 'surv': survlinlab}} plt.close() fig = plt.figure() ax = fig.add_subplot(111) def trans_y_ticks(x, p): ticks_round = np.round(predcols['none'][ptype], 6) return str(ticks_round[p]).replace('.', ',') for yr in fityrs: obs = obsframe.rx2(str(yr)) pred = stats.predict(paramsplot['test'].rx2('sourcefit').rx2(str(yr)), newdata = ro.r['list'](age = predage)) obscols = transdict(np.array(obsage), np.array(obs)) predcols = transdict(np.array(predage), np.array(pred)) obsplot = ax.plot(obscols[trans]['x'], obscols[trans][ptype], 'o', label = str(yr)) curcolor = obsplot[0].get_color() predplot = ax.plot(predcols[trans]['x'], predcols[trans][ptype], color = curcolor) plt.legend(loc = 2, framealpha = 0.5) ax.set_title('Observerad vs förutsedd ' + paramsplot['plottitle']) if (trans_time_coords): ax.xaxis.set_major_locator(plt.FixedLocator(predcols[trans]['x'])) ax.xaxis.set_major_formatter(plt.FixedFormatter(predcols['none']['x'])) ax.set_xlabel(plotlabs['none']['x']) plt.xticks(rotation = 90) else: ax.set_xlabel(plotlabs[trans]['x']) if (trans_y_coords): ax.yaxis.set_major_locator(plt.FixedLocator(predcols[trans][ptype])) ax.yaxis.set_major_formatter(plt.FuncFormatter(trans_y_ticks)) ax.set_ylabel(plotlabs['none'][ptype]) else: ax.set_ylabel(plotlabs[trans][ptype])
def plotMatrix(matrix, plot_path, labels, title, ticks, vmin, vmax): """Plot matrix. param matrix: two dimensional array. The matrix to plot param plot_path : string. Full path and name of the plotting picture param labels: list. The labels param title: string. The title of the plot param ticks: list. The ticks of the plot vmin: float. Minimum value vmax: float. Maximum value return: None """ ticks = list(map(lambda x: x - 0.5, ticks)) labelToColorDic = { "Uncertain": "olive", "SSH": "cyan", "SSM": "orange", "CO": "purple", "Auditory": "m", "DMN": "red", "Memory": "grey", "Visual": "blue", "FP": "gold", "Salience": "black", "Subcortical": "brown", "VAN": "teal", "DAN": "green", "Cerebellum": "purple" } ticks_middle = [(((ticks[i + 1] - ticks[i]) / 2) + ticks[i]) for i in range(0, len(ticks) - 1)] fig, ax = plt.subplots() fig.set_size_inches(16.5, 9.5) plt.yticks(ticks_middle, labels) plt.xticks(ticks_middle, labels, rotation=55, horizontalalignment='right') ax.xaxis.set_minor_locator(plt.FixedLocator(ticks[1:])) ax.yaxis.set_minor_locator(plt.FixedLocator(ticks[1:])) ax.grid(color='black', linestyle='-', linewidth=1.2, which='minor') plt.title(label=title, fontsize=20) for item in (ax.get_xticklabels() + ax.get_yticklabels()): item.set_color(labelToColorDic[item.get_text()]) item.set_fontsize(14) plotting.plot_matrix(matrix, colorbar=True, figure=fig, vmin=vmin, vmax=vmax) fig.savefig(plot_path) plt.close()
def plotBar(pos, cases, dt, color, title): """ This plots based base on the time series data :param pos: :param cases: :param dt: :param color: :param title: :return: """ labels = [val[1] for val in cases] labels2 = [ "Test" ] + labels # this is to overcome a bug in the bar function x = np.arange(len(labels)) # the label locations axs[pos].bar(x, [val[0] for val in cases], color=color, edgecolor='k') axs[pos].set_title("{} on {}".format(title, str(dt)), fontsize=15) axs[pos].xaxis.set_major_locator(plt.FixedLocator(x)) axs[pos].xaxis.set_major_formatter(plt.FixedFormatter(labels)) #axs[pos].set_xticklabels(labels2) axs[pos].grid(axis="y") plt.setp(axs[pos].xaxis.get_majorticklabels(), rotation=35, fontsize=12)
def generate_histrogram_strings(buckets, title, x_label, y_label, output): fig = plt.figure() ax = fig.add_subplot(111) sorted_keys = sorted(buckets.keys(), key=lambda item: int(''.join(x for x in item if x.isdigit()))) indexes = np.arange(0, len(sorted_keys)) # the x locations for the groups width = 0.1 # the width of the bars ax.set_yscale('log') ax.grid(zorder=0, axis="y") bars1 = ax.bar(indexes, [buckets.get(sorted_keys[i], 0) for i in indexes], align='center', color='blue') # axes and labels ax.set_ylim(0.5, max(buckets.values()) + 1) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_title(title) ax.xaxis.set_major_locator(plt.FixedLocator(indexes)) ax.xaxis.set_major_formatter(plt.FixedFormatter(sorted_keys)) labels = ax.get_xticklabels() for tick in labels: tick.set_rotation(90) plt.tight_layout() fig.savefig(output)
def plot_bar_from_counter(counter, title, xlabel, ylabel, ax=None): """" This function creates a bar plot from a counter. :param counter: This is a counter object, a dictionary with the item as the key and the frequency as the value :param ax: an axis of matplotlib :return: the axis wit the object in it """ if ax is None: fig = plt.figure() ax = fig.add_subplot(111) frequencies = counter.values() names = list(counter.keys()) x_coordinates = np.arange(len(counter)) ax.bar(x_coordinates, frequencies, align='center') ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates)) ax.xaxis.set_major_formatter(plt.FixedFormatter(names)) ax.xaxis.set_label_text(xlabel) ax.yaxis.set_label_text(ylabel) ax.set_title(title) plt.autoscale(enable=True, axis='x') DefaultSize = fig.get_size_inches() fig.set_size_inches((DefaultSize[0] * 5, DefaultSize[1] * 2.5)) mkdir_p(IMG_URL) plt.savefig(IMG_URL + 'GIST Data Histogram.png') plt.close() im = crop_image(IMG_URL + 'GIST Data Histogram.png') return ax
def plot_bar_from_counter(counter, ax=None): """" This function creates a bar plot from a counter. :param counter: This is a counter object, a dictionary with the item as the key and the frequency as the value :param ax: an axis of matplotlib :return: the axis wit the object in it """ if ax is None: fig = plt.figure() ax = fig.add_subplot(111) frequencies = counter.values() names = counter.keys() x_coordinates = np.arange(len(counter)) ax.bar(x_coordinates, frequencies, align='center') for idx in xrange(len(frequencies)): x = x_coordinates[idx] y = frequencies[idx] ax.text(x + 3, y + 3, str(v), color='red', fontweight='bold') ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates)) ax.xaxis.set_major_formatter(plt.FixedFormatter(names)) ax.set_ylim(0, np.max(frequencies) * 1.1) return ax
def ohlc_plot(ax, df, open_='open', high_='high', low_='low', close_='close', t_='trading_day', width_=0.7, n_=10): assert isinstance(df, pd.DataFrame) assert all([x in df.columns for x in (open_, high_, low_, close_)]) n = len(df) width = width_ offset = width / 2.0 for i in range(n): op = df[open_].values[i] hi = df[high_].values[i] lo = df[low_].values[i] cl = df[close_].values[i] x = i y = min(op, cl) height = abs(cl - op) is_raise = op < cl clr = 'red' if is_raise else 'green' fill = True # True if is_raise else False rect = Rectangle((x - offset, y), width, height, facecolor=clr, edgecolor=clr, linewidth=1, fill=fill) vline = Line2D(xdata=(x, x), ydata=(lo, hi), linewidth=1, color=clr) ax.add_patch(rect) ax.add_line(vline) ax.autoscale_view() x_label_idx = n_ * np.array(range(len(df) // n_ + 1)) x_labels = df[t_].iloc[x_label_idx].values ax.xaxis.set_major_locator(plt.FixedLocator(x_label_idx)) ax.xaxis.set_major_formatter(plt.FixedFormatter(x_labels))
def plot_summary(self): fig_size = (30, 20) multi_plot = plt.figure(figsize=fig_size, dpi=300) plot_order = ['wind_speed', 'wind_dir', 'T', 'rh_air', 'H'] for sub_name in plot_order: sub_plot = multi_plot.add_subplot( self._get_pos(sub_name, plot_order), xlim=[self.data.index[0].date(), self.data.index[-1].date()], ylim=self.config.plot_settings[sub_name]['ylim']) plt.plot(self.data[sub_name], self.config.plot_settings[sub_name]['style'], **self.config.plot_settings[sub_name]['params']) sub_plot.tick_params(axis='both', length=10, which='major', direction='in', labelsize=14) sub_plot.xaxis.set_major_formatter(dates.DateFormatter('%m/%d')) sub_plot.xaxis.set_major_locator(dates.DayLocator()) sub_plot.set_xlabel('Date', fontsize=18) sub_plot.set_ylabel(self.config.plot_settings[sub_name]['label'], fontsize=18) sub_plot.yaxis.set_major_locator( plt.FixedLocator( self.config.plot_settings[sub_name]['y_ticks'])) # multi_plot.tight_layout() os.makedirs(self.config.plot_path, exist_ok=True) plt.savefig(self.config.plot_path + '\\all_ADV.png') plt.close(multi_plot)
def setup_axis(): ax = plt.gca() # ax.xaxis.set_major_locator(plt.MultipleLocator(50.0)) # 设置x主坐标间隔 1 # ax.xaxis.set_minor_locator(plt.MultipleLocator(10.0)) # 设置x从坐标间隔 0.1 ax.yaxis.set_major_locator( plt.FixedLocator([ 70, 77, 78, 84, 85, 92, 97, 100, ])) # 设置y主坐标间隔 1 ax.yaxis.set_minor_locator(plt.MultipleLocator(1)) # 设置y从坐标间隔 0.1 ax.spines['top'].set_linewidth(0.2) ax.spines['bottom'].set_linewidth(0.2) ax.spines['left'].set_linewidth(0.2) ax.spines['right'].set_linewidth(0.2) # ax.grid(which='major', linewidth=0.2, linestyle='-') ax.grid(which='minor', linewidth=0.1, linestyle='-')
def display_all_etas(etas, event_names, groups=None): for i, event in enumerate(etas): for j, neuron in enumerate(event): if neuron > 1000: etas[i][j] = 1000 elif neuron < -1000: etas[i][j] = -1000 etas = [[etas[i][n] for i in range(len(etas))] for n in range(len(etas[0]))] etas = normalise_vrvs(etas) fig, ax = plt.subplots() fig.set_size_inches(1.85 * len(event_names), 20) if groups: ordered_atas = [] indexes = [ j for sub in [groups[i] for i in groups.keys()] for j in sub ] for i in indexes: ordered_atas.append(etas[i]) ax.pcolor(ordered_atas, cmap='coolwarm') transition_points = [ len(groups[key]) for i, key in enumerate(groups.keys()) ] cumulative_tps = [] for i, t in enumerate(transition_points): if i == 0: continue cumulative_tps.append(sum(transition_points[:i])) transition_points = cumulative_tps # cluster_labels = [i for i in range(len(transition_points))] def format_func_cluster(value, tick): for i, tp in enumerate(transition_points): if value < tp: return i return len(transition_points) for t in transition_points: ax.axhline(t, color="black", linewidth=1) ax.set_yticks(transition_points, minor=True) ax2 = ax.secondary_yaxis("right") # ax2.yaxis.grid(True, which='minor', linewidth=20, linestyle='-', color="b") ax2.yaxis.set_major_locator(plt.FixedLocator(transition_points)) ax2.yaxis.set_major_formatter(plt.FuncFormatter(format_func_cluster)) ax2.set_ylabel("Cluster ID", fontsize=40) ax2.tick_params(axis='y', labelsize=20) else: # atas, t, cat = order_vectors_by_kmeans(atas) ax.pcolor(etas, cmap='coolwarm') # ax.grid(True, which='minor', axis='both', linestyle='-', color='k') plt.xticks(range(len(event_names)), [i for i in event_names], fontsize=25) # ax.set_yticks(lat_grid, minor=True) ax.tick_params(axis="x", labelrotation=45) ax.set_ylabel("Neuron", fontsize=20) ax.set_xlabel("Event", fontsize=40) fig.tight_layout() plt.show()
def plot_bar_from_counter(counter, ax=None): """" This function creates a bar plot from a counter. :param counter: This is a counter object, a dictionary with the item as the key and the frequency as the value :param ax: an axis of matplotlib :return: the axis wit the object in it """ if ax is None: fig = plt.figure(figsize=(7, 5)) ax = fig.add_subplot(111) frequencies = [f[1] for f in counter] names = [f[0] for f in counter] x_coordinates = np.arange(len(counter)) ax.barh(x_coordinates, frequencies, align='center') ax.yaxis.set_major_locator(plt.FixedLocator(x_coordinates)) ax.yaxis.set_major_formatter(plt.FixedFormatter(names)) ax.yaxis.set_tick_params(labelsize=10) ax.set_ylim(-1, len(counter) + 1) ax.set_xlim(0, max(frequencies) + 300) for i, v in enumerate(frequencies): ax.text(v + 20, i - 0.25, str(v), color='black', fontweight='normal', fontsize=10) fig.subplots_adjust(left=0.4) return ax
def graph_flow_generator(total): ticket_dict = {} ticket_dict["Information"] = total[0] ticket_dict["Mineure"] = total[1] ticket_dict["Majeure"] = total[2] ticket_dict["Bloquante"] = total[3] ticket_dict["Autre"] = total[4] fig = plt.figure() ax = fig.add_subplot(111) frequencies = ticket_dict.values() names = ticket_dict.keys() x_coordinates = np.arange(len(ticket_dict)) ax.bar(x_coordinates, frequencies, align='center') ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates)) ax.xaxis.set_major_formatter(plt.FixedFormatter(names)) plt.savefig("flow" + contract_id + ".svg") # plt.show() img_insert("Repartition des demandes", "flow" + contract_id + ".svg", "Repartition des demandes")
def plot_bar_graph_within(names, observered_data, result_data, title, fig, sub_plot_index): """ :param names: labels of x-axis :param observered_data: as variable name :param result_data: as variable name :param title: the title of the subplot :param fig: the fig object :param sub_plot_index: the index number is in order, such 221 means the generate a graph has 2 by 2 figure, which could have 4 subplots in it the 1 means the first subplot in the figure. :return: the fig object """ # define the subplot ax = fig.add_subplot(sub_plot_index) x = np.arange(names.__len__()) * 2 # set the value ax.bar(x, observered_data, align='center', color='red') ax.bar(x + 1, result_data, align='center', color='blue') # create the patch red_patch = mpatches.Patch(color='red', label='Observed Value') blue_patch = mpatches.Patch(color='blue', label='Simulated Value') # Set the label x-axis ax.xaxis.set_major_locator(plt.FixedLocator(x + 0.5)) ax.xaxis.set_major_formatter(plt.FixedFormatter(names)) ax.set_title(title) plt.legend(handles=[red_patch, blue_patch]) return fig
def plot_distr(binned_data_list,binning_increment): norm_concs = [] bin_mids = [] for row in binned_data_list: bin_mid = row[0] bin_conc = row[1] bin_conc_norm = bin_conc/(math.log(bin_mid+binning_increment/2.,10)-math.log(bin_mid-binning_increment/2.,10)) norm_concs.append(bin_conc_norm) bin_mids.append(bin_mid) popt,perr = SP2_utilities.fitFunction(SP2_utilities.lognorm,bin_mids,norm_concs,p0=(100,180,0.5)) fit_bin_mids = np.arange(10,1000,5) fit_concs = [] for fit_bin_mid in fit_bin_mids: fit_conc_norm = SP2_utilities.lognorm(fit_bin_mid, popt[0], popt[1], popt[2]) fit_concs.append(fit_conc_norm) ticks = [10,20,30,40,50,60,80,120,200,300,400,600,1000] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(fit_bin_mids,fit_concs) ax1.scatter(bin_mids,norm_concs) ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%d')) ax1.xaxis.set_major_locator(plt.FixedLocator(ticks)) ax1.set_xscale('log') ax1.set_xlim(10,1000) ax1.set_ylabel('dM/dlogD (ng/m3)') ax1.set_xlabel('rBC VED (nm)') plt.show()
def make_graph(humidities, dates_): firstdate = dates_[0] lastdate = dates_[-1] graph_title = "{} - {}".format(firstdate.strftime(DAY_FORMAT), lastdate.strftime(DAY_FORMAT)) debug_print("Making graph for {}".format(graph_title)) # create new plot fig, ax = plt.subplots() fig.set_size_inches(40.5, 20.5) fig.subplots_adjust(bottom=0.2) # configure axes ax.xaxis_date() ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_minor_locator(HourLocator()) ax.xaxis.set_major_formatter(DateFormatter(DATE_FORMAT)) ax.yaxis.set_major_locator( plt.FixedLocator([ 10, 20, 30, 110, 120, 130, 140, 150, 160, 300, 350, 365, 380, 400, 430, 480 ])) ax.set_xlim(firstdate, lastdate) ax.set_ylim(10, 500) ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.xticks(rotation=15) # add data plt.plot(dates_, humidities, ".") plt.grid() plt.title(graph_title) return fig
def matrix_plot(fig, ax, matrix, position='right'): ''' Create a matrix plot of pop. rates for the stabilization manuscript ''' ax.yaxis.set_ticks_position('none') cm = plt.get_cmap('rainbow') cm = cm.from_list('mycmap', [myblue, myblue2, 'white', myred2, myred], N=256) masked_matrix = np.ma.masked_where(np.isnan(matrix), matrix) cm.set_under('0.3') cm.set_bad('k') im = ax.pcolormesh(masked_matrix, norm=LogNorm( vmin=0.001, vmax=500.), cmap=cm) ax.set_xlim(0, 32) ax.set_xticks([0.5, 3.5, 14.5, 24.5, 28.5]) ax.xaxis.set_major_locator(plt.FixedLocator([0, 1, 4, 9, 24, 31])) ax.xaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_minor_locator(plt.FixedLocator([0.5, 2.5, 6.5, 16.5, 27.5, 31.5])) ax.set_xticklabels([8, 7, 6, 5, 4, 2], minor=True, size=8) ax.tick_params(axis='x', which='minor', length=0.) ax.set_xlabel('Architectural type', labelpad=-0.2) y_index = list(range(8)) y_index = [a + 0.5 for a in y_index] t = plt.FixedLocator([0.01, 0.1, 1., 10., 100., 500.]) cb = plt.colorbar(im, ticks=t, ax=ax) if position == 'left': ax.set_yticklabels(population_labels, size=8) ax.set_yticks(y_index[::-1]) ax.set_ylabel('Population', labelpad=-0.1) cb.remove() elif position == 'center': ax.set_yticks([]) cb.remove() elif position == 'right': ax.set_yticks([]) ax.text(45., 6, r'$\nu (\mathrm{spikes/s})$', rotation=90) if position == 'single': ax.set_yticklabels(population_labels) ax.set_yticks(y_index[::-1]) ax.set_ylabel('Population', labelpad=-0.1) ax.text(45., 6, r'$\nu (\mathrm{spikes/s})$', rotation=90)
def rate_matrix_plot(fig, ax, matrix, position): ''' Create a matrix plot of pop. rates for the stabilization manuscript ''' cm = plt.get_cmap('rainbow') cm = cm.from_list('mycmap', [myblue, myblue2, 'white', myred2, myred], N=256) masked_matrix = np.ma.masked_where(np.isnan(matrix), matrix) cm.set_under('0.3') cm.set_bad('k') im = ax.pcolormesh(masked_matrix, norm=LogNorm(vmin=0.01, vmax=500.), cmap=cm) ax.set_xlim(0, 32) R = plt.Rectangle((area_list.index('TH') + 1, 4), 1, 2, edgecolor='none', facecolor='k') ax.add_patch(R) ax.set_xticks([0.5, 3.5, 14.5, 24.5, 28.5]) ax.xaxis.set_major_locator(plt.FixedLocator([0, 1, 4, 9, 24, 31])) ax.xaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_minor_locator( plt.FixedLocator([0.5, 2.5, 6.5, 16.5, 27.5, 31.5])) ax.set_xticklabels([8, 7, 6, 5, 4, 2], minor=True) ax.tick_params(axis='x', which='minor', length=0.) ax.set_xlabel('Arch. type', labelpad=-0.2) y_index = list(range(8)) y_index = [a + 0.5 for a in y_index] t = plt.FixedLocator([0.01, 0.1, 1., 10., 100.]) cb = plt.colorbar(im, ticks=t, ax=ax) if position == 'left': ax.set_yticklabels(population_labels) ax.set_yticks(y_index[::-1]) ax.set_ylabel('Population') ax.yaxis.set_label_coords(-0.2, 0.5) # cb.remove() elif position == 'right': ax.set_yticks([]) ax.text(42, 5, r'$\nu (1/\mathrm{s})$', rotation=90)
def get_midi_to_performance_difference(midi_hz, measured_hz, performance_key, plot=False, plot_dir="./"): """ Computes frame-wise differences in cents between the midi score and measured f0 when both are non-silent. :param midi_hz: numpy array of frame-wise MIDI frequencies in Hz :param measured_hz: numpy array of frame-wise performance pitch track frequencies in Hz :param performance_key: Performance identifier :return: array of differences in cents when both arrays are non-zero (not silent) """ # find non-silent frames singing_region = np.where((measured_hz > 1.0) & (midi_hz > 1.0))[0] # compute the differences in cents cent_differences = np.log2((midi_hz[singing_region] + 1e-10) / (measured_hz[singing_region] + 1e-10)) * 1200 if plot: fig, ax = plt.subplots() ax.set_xlabel("Frames") ax.set_ylabel("Cents") ax.set_title("Difference between MIDI and pYIN in non-silent frames") plt.plot(cent_differences) plt.tight_layout() plt.savefig(os.path.join( plot_dir, "midi_performance_diff_cents_" + performance_key + ".eps"), format="eps") plt.close() fig, ax = plt.subplots(figsize=(6, 4)) ax.set_xlabel("Frames") ax.set_ylabel("Scientific pitch") note_names = [ 'Gb4', 'G4', 'Ab4', 'A4', 'Bb4', 'B4', 'C5', 'Db5', 'D5', 'Eb5', 'E5', 'F5', 'Gb5', 'G5', 'Ab5', 'A5', 'Bb5', 'B5', 'C6' ] ax.set_ylim(np.log2(370), np.log2(940)) ax.yaxis.set_major_locator( plt.FixedLocator(np.log2(440 * np.power(2, np.arange(-3, 14) / 12)))) ax.set_yticklabels(note_names, fontsize='small') for label in (ax.get_xticklabels()): label.set_fontsize('small') plt.plot(np.log2(midi_hz[singing_region][500:1500]), color="green", label="MIDI") plt.plot(np.log2(measured_hz[singing_region][500:1500]), color="purple", label="pYIN") plt.legend(loc=4, fontsize='small') plt.tight_layout() plt.savefig(os.path.join( plot_dir, "midi_and_pyin_aligned_active_" + performance_key + ".eps"), format="eps") plt.close() return cent_differences
def palplot(k, cmap="viridis"): pal = sns.color_palette(palette=cmap, n_colors=k) fig, ax = plt.subplots(1, 1) pal = np.array(pal) pal = pal.reshape((k, 1, 3)) ax.imshow(pal) ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_formatter(plt.FixedFormatter(np.arange(k, dtype=int))) ax.yaxis.set_major_locator(plt.FixedLocator(np.arange(k))) return ax
def plot_bar_from_counter(counter): ax = fig.add_subplot(1, 1, 1) x_coordinates = np.arange(len(counter)) ax.bar(x_coordinates, counter.values(), align='center') ax.xaxis.set_tick_params(rotation=90) ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates)) ax.xaxis.set_major_formatter(plt.FixedFormatter(list(counter.keys()))) return ax
def plot2d(self, **kwargs): """2D Colormap plot of the Rainflow matrix Args: **kwargs: **kwargs are passed to plt.imshow() Returns: figure: matplotlib figure object axes: matplotlib axes object """ # create fig, ax fig = plt.figure() ax = fig.add_subplot((111)) # imshow plot cax = ax.imshow(self.values, cmap=plt.get_cmap("Blues"), extent=(self.bins[0][0], self.bins[0][-1], self.bins[1][-1], self.bins[1][0]), **kwargs) # create colorbar fig.colorbar(cax) # create grid and ticks ax.grid(which='minor', alpha=0.8, linewidth=0.3) ax.xaxis.tick_top() ax.xaxis.set_label_position('top') ax.xaxis.set_minor_locator(plt.FixedLocator(self.bins[0])) ax.yaxis.set_minor_locator(plt.FixedLocator(self.bins[0])) ax.tick_params(which="minor", direction="in") if self.matrixtype == 'FromTo': ylabel = 'From' xlabel = 'To' elif self.matrixtype == 'RangeMean': ylabel = 'Range' xlabel = 'Mean' ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) fig.tight_layout() return fig, ax
def draw_together(n, Ts, c_num, s, pmin): fig, ax = plt.subplots(figsize=(11, 3)) sim_num = 6 colors = ['b', 'g', 'r', 'c', 'm'] c_show_max = 15 major_ticks = [] minor_ticks = [] ymax = 0 for i, T in enumerate(Ts): df = read_csv("results/simu_n{}t{}cnum{}pmin{}.csv".format( n, T, c_num, pmin), index_col=0) for c in df.columns: if int(c) > c_show_max: continue tick = (c_show_max + 1) * i + int(c) ax.plot([tick] * (sim_num - 1), df[c].values, 'o', color=colors[i]) ymax = max(ymax, np.max(df[c].values)) if int(c) % 2 == 0: major_ticks.append(tick) minor_ticks.append(tick) save_path = "results/simu_n{}cnum{}pmin{}".format(n, c_num, pmin) ax.xaxis.set_major_locator(plt.FixedLocator(major_ticks)) ax.xaxis.set_minor_locator(plt.FixedLocator(minor_ticks)) ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func)) ax.yaxis.set_major_locator( plt.FixedLocator(get_yticks_my_way(0, int(ymax)))) ax.yaxis.set_minor_locator(plt.FixedLocator(list(range(0, int(ymax) + 1)))) # save png and low quality jpg fig.savefig(save_path + ".png", dpi=500) fig.savefig(save_path + ".jpg", dpi=100, optimize=True, quality=30) # clean before doing next graph plt.clf()
def imshow(e, a): # Calculate events at super resolution x = e['x'] * super_resolution y = e['y'] * super_resolution data = np.ones(len(x)) d = scipy.sparse.coo_matrix((data, (y, x)), shape=(shape, shape), dtype=np.uint32) frame = d.todense() min5 = np.percentile(frame, 5) max95 = np.percentile(frame, 95) im = a.imshow(frame, vmin=min5, vmax=max95, cmap='gray') # Look and feel a.xaxis.set_major_locator(plt.FixedLocator([shape - 1])) a.yaxis.set_major_locator(plt.FixedLocator([shape - 1])) # Color bar # colorbar(im) return im
def plot_inertia_silhouette(inertia_vect, silhouette_vect, strategy): """Plot inertia and silhouette vs number of clusters.""" fig, axs = plt.subplots(1, 2) k_vect = np.arange(2, 2 + len(inertia_vect)) for ax, y, label in zip(axs, (inertia_vect, silhouette_vect), LABELS): ax.plot(k_vect, y) ax.xaxis.set_major_locator(plt.FixedLocator(k_vect)) ax.set(xlabel="k", ylabel=label) fig.suptitle(f"Strategy: {strategy}", fontsize=16) plt.show()
def plot_cdf_raw(values, ax, **kwargs): """Plot the cdf of values. :param values: values to plot. :param ax: axis to plot. :param kwargs: any other kwargs that are passed to plot function. """ probabilities = np.linspace(0, 1, len(values)) ax.plot(np.sort(values), probabilities, **kwargs) ax.yaxis.set_major_locator(plt.FixedLocator(np.linspace(0, 1, 5))) ax.set_ylabel('cdf') ax.grid(True)