def plot_one_psd(ax, X_pwr, f_ax, title_str, p_range, f_range): """ Plots ONLY ONE PSD """ X_plot = 10 * np.log10(X_pwr + np.finfo(float).eps) plt.plot(f_ax, X_plot) # Major and Minor ticks ax = plt.gca() ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.yaxis.set_major_locator(ticker.AutoLocator()) ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) plt.xlabel('Modulation frequency (Hz)') plt.ylabel('Conventional frequency (Hz)') if f_range is not None: xlim = f_range else: xlim = f_ax if p_range is not None: ylim = p_range else: ylim = X_plot # set the limits of the plot to the limits of the data plt.axis([xlim.min(), xlim.max(), ylim.min(), ylim.max()]) plt.title(title_str) plt.draw()
def animate(i, st, download, upload, time, ax1, ax2): # Add x and y to lists time.append(dt.datetime.now().strftime("%d/%m/%y %H:%M:%S")) download.append(st.download() / 1e6) upload.append(st.upload() / 1e6) # Draw x and y lists ax1.clear() ax1.plot(time, download) ax2.clear() ax2.plot(time, upload) # Format plot ax1.set_xticks([]) ax1.yaxis.set_major_locator(ticker.AutoLocator()) ax1.yaxis.set_minor_locator(ticker.AutoMinorLocator()) ax2.xaxis.set_major_locator(ticker.AutoLocator()) ax2.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax2.yaxis.set_major_locator(ticker.AutoLocator()) ax2.yaxis.set_minor_locator(ticker.AutoMinorLocator()) plt.xticks(rotation=45, ha='right') plt.subplots_adjust(bottom=0.30) ax1.set_title("Download Speed") ax2.set_title("Upload Speed") ax1.set_ylabel("Speed (Mb/s") ax2.set_ylabel("Speed (Mb/s") ax2.set_xlabel("Time") plt.tight_layout()
def make_plot(args): """ Creates the plot based on the arguments. """ data = load_data(args.input) runtimes = load_data(args.runtime) which_highlight = np.where(np.array([x for x in data.keys()]) == highlight)[0][0] fig, ax = plt.subplots(1) ax = [ax] for a, pprop, pname in zip(ax, particle_properties, particle_names): a.set_xscale("log", basex=10) a.set_yscale("log", basey=10) a.yaxis.set_minor_formatter(mticker.ScalarFormatter()) a.yaxis.set_major_formatter(mticker.ScalarFormatter()) a.yaxis.set_minor_locator(mticker.AutoLocator()) a.yaxis.set_major_locator(mticker.AutoLocator()) a.set_xlabel("Runtime [s]") a.set_ylabel(f"L{args.norm} Norm for {pname}") for sid, sname, alpha, c in zip( scheme_identifiers, scheme_names, scheme_alphas, scheme_colours ): this_data = extract_from_data( data, runtimes, sid, args.kernel, pprop, args.norm ) fitted_data = fitted_line(*this_data) a.scatter(*this_data, color=f"C{c}", s=2, alpha=alpha, zorder=alpha) a.scatter( this_data[0][which_highlight], this_data[1][which_highlight], marker="*", color=f"C{c}", s=30, alpha=alpha, zorder=alpha + 10, edgecolor="white", linewidth=0.2, ) a.plot(*fitted_data, color=f"C{c}", label=sname, alpha=alpha, zorder=alpha) ax[-1].legend() fig.tight_layout() fig.savefig(filename(args)) return
def subax_call(self, method, args, kwargs): result = [] for ax in self.axs: ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.yaxis.set_major_locator(ticker.AutoLocator()) result.append(getattr(ax, method)(*args, **kwargs)) self.standardize_ticks() self.set_spines() return result
def spectrum(spec, color_ions=True, annotate_ions=True, ax=None): if ax is None: ax = plt.gca() max_intensity = spec.intensity.max() for mz, intensity, annotation in zip(spec.mz, spec.intensity, spec.annotation): ion_type = annotation.ion_type if annotation is not None else None color = colors.get(ion_type) if color_ions else colors.get(None) zorder = zorders.get(ion_type) ax.plot([mz, mz], [0, intensity / max_intensity], color=color, zorder=zorder) if annotate_ions and annotation is not None: ax.text(mz + 5, intensity / max_intensity + 0.02, str(annotation), color=color, zorder=5, rotation=90, rotation_mode='anchor') min_mz = max(0, math.floor(spec.mz[0] / 100 - 1) * 100) max_mz = math.ceil(spec.mz[-1] / 100 + 1) * 100 ax.set_xlim(min_mz, max_mz) ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.)) ax.set_ylim(0, 1.15 if annotate_ions else 1.05) ax.xaxis.set_minor_locator(mticker.AutoLocator()) ax.yaxis.set_minor_locator(mticker.AutoLocator()) ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) ax.yaxis.set_minor_locator(mticker.AutoMinorLocator()) ax.grid(b=True, which='major', color='#9E9E9E', linestyle='--', linewidth=1.0) ax.grid(b=True, which='minor', color='#9E9E9E', linestyle='--', linewidth=0.5) ax.set_axisbelow(True) ax.tick_params(axis='both', which='both', labelsize='small') ax.set_xlabel('m/z') ax.set_ylabel('Intensity') return ax
def subax_call(self, method, args, kwargs): """Apply method call to all internal axes. Called by CallCurator. """ result = [] for ax in self.axs: ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.yaxis.set_major_locator(ticker.AutoLocator()) result.append(getattr(ax, method)(*args, **kwargs)) self.standardize_ticks() self.set_spines() return result
def __init__(self, me, buds): # find max values for axes tensors = copy.deepcopy(buds) tensors.insert(0, me) max_ = 12 for t in tensors: temp_max = np.amax(np.abs(t.values)) if temp_max > 10: max_ = temp_max + 0.2 * temp_max # set number line plt.figure(figsize=(8, 6)) n = 8 ax = plt.subplot(n, 1, 6) setup(ax) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05) plt.xlim(-max_, max_) plt.grid(True) origin = [0], [0] bud1 = buds[0] bud2 = buds[1] bud3 = buds[2] V = np.array([[me.values, 0], [bud1.values, 0], [bud2.values, 0], [bud3.values, 0]]) colors = [me.color, bud1.color, bud2.color, bud3.color] plt.scatter(V[:, 0], V[:, 1], color=colors) plt.show()
def line_plot(y_train, y_val, early_stoping, y_label="Loss", y_min=None, y_max=None, best_score=None): iterations = range(1,len(y_train)+1) if y_min is None: y_min = min(min(y_train), min(y_val)) y_min = max(0, (y_min - y_min*0.01)) if y_max is None: y_max = max(max(y_train), max(y_val)) y_max = min(1, (y_max + 0.1*y_max)) plt.plot(iterations, y_train, label="training " ) plt.plot(iterations, y_val, label="validation ") if best_score: plt.title(r"\textbf{Learning curve}" f": best score: {best_score}", fontsize=8) #plt.axvline(early_stoping, linestyle='--', color='r',label='Early Stopping') else: plt.title(r'\textbf{Learning curve}') plt.ylabel(y_label) #plt.ylim(y_min, y_max) plt.xlabel(r"Iterations") plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.legend(loc="best") ax = plt.gca() ax.patch.set_alpha(0.0) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) format_axes(ax)
def draw_graph(xdata, ydata, title=None): xdatas = np.array(xdata) ydatas = np.array(ydata) # 以下两个顺序不能乱 fig, ax = plt.subplots(figsize=(5, 5)) # 画布尺寸 plt.plot(xdatas, ydatas) plt.xticks(rotation=20) # 设置X轴文本倾斜角度 if title: plt.title(title) # 标题 ax.xaxis.set_major_locator(ticker.AutoLocator()) # 划分X轴刻度间隔 # for x, y in zip(mymonth, power): # 显示折线点数据 # plt.text(x, y+0.05, '%.0f' % y, ha='center', va='bottom', fontsize=8) canvas = fig.canvas buf, size = canvas.print_to_buffer() image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) buffer = io.BytesIO() image.save(buffer, 'PNG') graphic = buffer.getvalue() graphic = base64.b64encode(graphic) buffer.close() return str(graphic)[2:-1]
def plot_integral(qa_dict,outfile,plotconf=None,hardplots=False): import matplotlib.ticker as ticker """ Plot integral. Args: qa_dict: qa dictionary outfile : output plot file """ expid=qa_dict["EXPID"] camera=qa_dict["CAMERA"] paname=qa_dict["PANAME"] fig=plt.figure() if plotconf: hardplots=ql_qaplot(fig,plotconf,qa_dict,camera,expid,outfile) if not hardplots: pass else: ax1=fig.add_subplot(111) integral=np.array(qa_dict["METRICS"]["SPEC_MAGS"]) plt.suptitle("Integrated Spectral Magnitudes, Camera: {}, ExpID: {}".format(paname,camera,expid),fontsize=10,y=0.99) index=np.arange(len(integral)) hist_med=ax1.bar(index,integral,color='b',align='center') ax1.set_xlabel('Fibers',fontsize=10) ax1.set_ylabel('Integral (photon counts)',fontsize=10) ax1.tick_params(axis='x',labelsize=10) ax1.tick_params(axis='y',labelsize=10) ax1.xaxis.set_major_locator(ticker.AutoLocator()) #ax1.set_xticklabels(std_fiberid) plt.tight_layout() fig.savefig(outfile)
def stats(reductions_dict): # import pdb # pdb.set_trace() # for k in sorted(reductions_dict.keys()): # np.save(k, reductions_dict[k]) keys = sorted(reductions_dict.keys()) data = [reductions_dict[k] for k in keys] fig = plt.figure() fig.subplots_adjust(left=0.09, right=0.975, bottom=0.15, top=0.975) ax = fig.add_subplot(111) xpos = np.arange(len(keys)) xlim = [-1, len(keys) + 1] # ax.plot(xpos, np.zeros(len(keys)), 'k') ax.hlines(0, xlim[0], xlim[1], linestyles='dotted') # xloc = ticker.FixedLocator(xpos) # xloc = ticker.MaxNLocator(nbins=6, prune=None) xloc = ticker.AutoLocator() boxplot(ax, data, keys, 'Delay [s]', '$\mathit{ROF}$ [\%]', xloc=xloc, xpos=xpos, xlim=xlim) plt.show()
def plot_tweets_vs_retweets(df_tweets_stats, results_folder='', fname_prefix='', csv_out=False, show_chart=False): df_rtw = df_tweets_stats.groupby(['month_year', 'is_retweet']).agg({ 'n_tweets': 'sum', 'tweet_time': 'first' }).reset_index().sort_values('tweet_time') df_rtw = extend_month_year_values(df_rtw, 'volume') if csv_out: df_rtw.drop(columns=['tweet_time']).to_csv( os.path.join(results_folder, 'Tweet vs Retweets.csv')) ax = sns.lineplot(data=df_rtw, x='month_year', y='n_tweets', hue='is_retweet', sort=False) ax.xaxis.set_major_locator(ticker.AutoLocator()) plt.xticks(rotation=45, fontsize=15) plt.title(f'Tweets vs Retweets', fontsize=18) if not show_chart: plt.savefig(f'{results_folder}/{fname_prefix}_tweets_vs_retweets.png', bbox_inches='tight', dpi=200) plt.close() else: return ax
def showPlot(folder, print_file): df = pd.read_csv(print_file) print(df.head()) plt.figure() fig, ax = plt.subplots() # this locator puts ticks at regular intervals loc = ticker.AutoLocator()#MultipleLocator(base=0.2) ax.yaxis.set_major_locator(loc) #ax.xaxis.set_major_locator(loc) x = df['epoch'] y = df['train_loss'] z = df['eval_loss'] plt.xlabel('Epochs') plt.ylabel('Loss') plt.plot(x, y, color='blue', linewidth=2, label='Train_loss') plt.plot(x, z, color='red', linewidth=2, label='Eval_loss') plt.legend(loc='best') #plt.plot(points) #seed(time.time()) #print('seed: {}'.format(seed)) #v1 = randint(1,100) #v2 = randint(1,100) file = os.path.splitext(print_file)[0] + '.png' #file = 'plot_loss_' + str(v1) + str(v2) + '.png' #file = os.path.join(folder, file) plt.savefig(file) print(file)
def plot_static(self, stats_source): '''Plot log data from Reader object.''' stats_source.read_log() x, y = self.set_x_y(stats_source.hash_rates) plt.plot_date(x, y, 'b-', color='green') x2, y2 = self.set_x_y(stats_source.ehrs) plt.plot_date(x2, y2, 'b-', color='blue') x3, y3 = self.set_x_y(stats_source.avgs) plt.plot_date(x3, y3, 'b-', color='orange') # Specific Styling def megahashes(x, pos): '''Provide formatting for the y axis tickers.''' return '{0:.0f} Mh/s'.format(x/1000) # e.g. 26 Mh/s # Create formatters. x_formatter = dates.DateFormatter('%a %d %H:%M') # Sun 02 10:00 self.ax_1.xaxis.set_major_formatter(x_formatter) self.ax_1.yaxis.set_major_formatter(ticker.FuncFormatter(megahashes)) self.ax_1.yaxis.set_major_locator(ticker.AutoLocator()) plt.xlim(x[0], x[-1]) start, end = self.calc_y_range(y) self.ax_1.set_ylim(start, end) print('{}: Showing plot.'.format(__name__)) plt.show()
def assets(pairs): fig, ax = plt.subplots() fig.set_tight_layout(True) for pair in pairs: df = priceof(pair).iloc[::60].iloc[-10000:] df.open = df.open / df.open[0] # normalize to be comparable dates = df.index.strftime('%Y-%m-%d') ax.plot( dates, df.open, # marker='.', markersize=1, ls='-', lw=1, label=pair, ) ax.set_title('Normalized evolution of assets compared to bitcoin') ax.tick_params(axis='x', labelrotation=40) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.legend() return fig
def _format_xaxis_posixtime(axis): xtick_locator = mticker.AutoLocator() xtick_formatter = mticker.FuncFormatter(fmt_truncate_posix) axis.xaxis.set_major_locator(xtick_locator) axis.xaxis.set_major_formatter(xtick_formatter) axis.set_xlabel('Time (s)')
def __init__(self, *args, **kwargs): # Pass a dummy axis to the superclass axis = type('Axis', (object, ), {'axis_name': 'x'})() super().__init__(axis, *args, **kwargs) self._default_major_locator = mticker.AutoLocator() self._default_minor_locator = mticker.AutoMinorLocator() self._default_major_formatter = pticker.AutoFormatter() self._default_minor_formatter = mticker.NullFormatter()
def plot(df, title, equation = 1): """ Plot x1 vs x2 with contour lines. Input df: dataframe with values to be plotted title: chart title equation: 1: f(x1, x2) = x1^2 + 2.x2^2 - 2.x1.x2 - 2.x2 2: f(x1, x2) = r1(x)**2 + r2(x)**2 (method Levenberg-Marquardt) 3: f(x1, x2) = (x1 - 2)^4 + (x1 - 2.x2)^2 """ fig, ax = plt.subplots() # Compute contour lines delta_x1 = (1.5*max(df.x1) - min(df.x1)) / 1000 delta_x2 = (1.5*max(df.x2) - min(df.x2)) / 1000 d1 = (max(df.x1) - min(df.x1)) * 0.1 d2 = (max(df.x2) - min(df.x2)) * 0.1 x_1 = np.arange(min(df.x1) - d1, max(df.x1) + d1, delta_x1) x_2 = np.arange(min(df.x2) - d2, max(df.x2) + d2, delta_x2) x_1, x_2 = np.meshgrid(x_1, x_2) if equation == 1: f = x_1**2 + 2*x_2**2 - 2*x_1*x_2 - 2*x_2 CS = ax.contour(x_1, x_2, f, locator = ticker.SymmetricalLogLocator(linthresh=1, base=10)) locator = ticker.AutoLocator() elif equation == 3: f = (x_1 - 2)**4 + (x_1 - 2*x_2)**2 locator = ticker.SymmetricalLogLocator(linthresh=0.1, base=2) else: print ("Only equations 1 and 3 are supported.") #return # Plot contour lines and labels CS = ax.contour(x_1, x_2, f, locator = locator) ax.clabel(CS, inline=1, fontsize=10) # Points x1 = df.x1 x2 = df.x2 ax.plot(x1, x2) ax.plot(x1, x2, 'ro') # Lables and title ax.set_title(title) ax.set_xlabel('x1') ax.set_ylabel('x2') plt.show() return
def _ticker(self): ''' Return the sequence of ticks (colorbar data locations), ticklabels (strings), and the corresponding offset string. ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator(subs='all') elif isinstance(self.norm, colors.SymLogNorm): # The subs setting here should be replaced # by logic in the locator. locator = ticker.SymmetricalLogLocator( subs=np.arange(1, 10), linthresh=self.norm.linthresh, base=10) else: if mpl.rcParams['_internal.classic_mode']: locator = ticker.MaxNLocator() else: locator = ticker.AutoLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm) and self.boundaries is None: intv = self._values[0], self._values[-1] else: intv = self.vmin, self.vmax locator.create_dummy_axis(minpos=intv[0]) formatter.create_dummy_axis(minpos=intv[0]) locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) b = np.array(locator()) if isinstance(locator, ticker.LogLocator): eps = 1e-10 b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))] else: eps = (intv[1] - intv[0]) * 1e-10 b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)] self._tick_data_values = b ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def plot_costfunction(avg_scores, output_dir, y_label='Fitness score'): '''Creates a plot of the cost function Parameters: ---------- avg_scores : list List of average scores of all itereations of the evolutionary algorithm output_dir : str Path to the directory where the plot is saved Returns: ------- Nothing ''' plot_out = os.path.join(output_dir, 'costFunction.png') if not os.path.exists(output_dir): os.makedirs(output_dir) try: n_gens = len(avg_scores) gen_numbers = np.arange(n_gens) plt.plot(gen_numbers, avg_scores, color='k') plt.xlim(0, n_gens - 1) plt.xticks(np.arange(n_gens - 1)) except: # in case of a genetic algorithm with multiple subpopulations x_max = 0 for i in avg_scores: n_gens = len(avg_scores[i]) if n_gens > x_max: x_max = n_gens if i != 'final': gen_numbers = np.arange(n_gens) plt.plot(gen_numbers, avg_scores[i], color='b') for i in avg_scores: if len(avg_scores[i]) < x_max and i != 'final': line_length = x_max - len(avg_scores[i]) + 1 y_values = [avg_scores[i][-1] for n in range(line_length)] x_values = np.arange(len(avg_scores[i]) - 1, x_max) plt.plot(x_values, y_values, color='b', linestyle='--', alpha=0.2) n_gens_final = x_max + len(avg_scores['final']) - 1 gen_numbers = np.arange(x_max - 1, n_gens_final) plt.plot(gen_numbers, avg_scores['final'], color='k') plt.xlim(0, n_gens_final - 1) plt.xticks(np.arange(n_gens_final - 1)) finally: plt.xlabel('Generation') plt.ylabel(y_label) axis = plt.gca() axis.set_aspect('auto', adjustable='box') axis.xaxis.set_major_locator(ticker.AutoLocator()) plt.grid(True) plt.tick_params(top=True, right=True, direction='in') plt.savefig(plot_out) plt.close('all')
def set_axis_visible(self, name, visible): ax = getattr(self.ax, f'{name}axis') set_label_func = getattr(self.ax, f'set_{name}label') if visible: ax.set_major_locator(ticker.AutoLocator()) set_label_func(name.upper()) else: ax.set_ticks([]) set_label_func('')
def _draw(self, ax: mpl.axes.Axes, plot_timestamps: np.ndarray, date_formatter: Optional[DateFormatter]) -> None: if self.time_plot: self._reindex(plot_timestamps) if date_formatter is not None: ax.xaxis.set_major_formatter(date_formatter) lines = [] ax2 = None if self.secondary_y is not None and len(self.secondary_y): ax2 = ax.twinx() for data in self.data_list: if _VERBOSE: print(f'plotting data: {data.name}') if ax2 and data.name in self.secondary_y: line = _plot_data(ax2, data) else: line = _plot_data(ax, data) lines.append(line) for date_line in self.date_lines: # vertical lines on time plot line = draw_date_line(ax, plot_timestamps, date_line.date, date_line.line_type, date_line.color) if date_line.name is not None: lines.append(line) for horizontal_line in self.horizontal_lines: line = draw_horizontal_line(ax, horizontal_line.y, horizontal_line.line_type, horizontal_line.color) if horizontal_line.name is not None: lines.append(line) for vertical_line in self.vertical_lines: line = draw_vertical_line(ax, vertical_line.x, vertical_line.line_type, vertical_line.color) if vertical_line.name is not None: lines.append(line) self.legend_names = [data.name for data in self.data_list] self.legend_names += [date_line.name for date_line in self.date_lines if date_line.name is not None] self.legend_names += [horizontal_line.name for horizontal_line in self.horizontal_lines if horizontal_line.name is not None] self.legend_names += [vertical_line.name for vertical_line in self.vertical_lines if vertical_line.name is not None] if self.ylim: ax.set_ylim(self.ylim) if (len(self.data_list) > 1 or len(self.date_lines)) and self.display_legend: ax.legend([line for line in lines if line is not None], [self.legend_names[i] for i, line in enumerate(lines) if line is not None], loc=self.legend_loc) if self.log_y: ax.set_yscale('log') ax.yaxis.set_major_locator(mtick.AutoLocator()) ax.yaxis.set_minor_locator(mtick.NullLocator()) if self.y_tick_format: ax.yaxis.set_major_formatter(mtick.StrMethodFormatter(self.y_tick_format)) if self.title: ax.set_title(self.title) if self.xlabel: ax.set_xlabel(self.xlabel) if self.ylabel: ax.set_ylabel(self.ylabel) if self.zlabel: ax.set_zlabel(self.zlabel) ax.relim() ax.autoscale_view()
def make_colorbar(f, image): f.subplots_adjust(right=0.8) cbar_ax = f.add_axes([0.85, 0.3, 0.05, 0.4]) cbar = f.colorbar(image, cax = cbar_ax) tick_locator = ticker.MaxNLocator(nbins = 5) cbar.locator = tick_locator cbar.ax.yaxis.set_major_locator(ticker.AutoLocator()) cbar.update_ticks() cbar.ax.tick_params(labelsize = 6) cbar.set_label('Intensity level', size = 7)
def plotDataFrameChannelsRaw(data_set, title): num_x_vals = data_set.shape[0] total_time_elapsed = num_x_vals * T timestamps = np.arange(start=0, stop=num_x_vals, step=1, dtype=float) timestamps *= T fig, ax = plt.subplots(figsize=(14,6), dpi=200) for i in range(data_set.shape[1]): ax.plot(data_set[data_set.columns[3-i]], label=data_set.columns[3-i], linewidth=.1) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoLocator()) plt.xlabel("Time (seconds)") plt.ylabel("Signal Amplitude") plt.legend(loc='best') ax.set_title(title, fontsize=16) plt.show()
def mirror(spec_top: MsmsSpectrum, spec_bottom: MsmsSpectrum, spectrum_kws: Optional[Dict] = None, ax: Optional[plt.Axes] = None)\ -> plt.Axes: """ Mirror plot two MS/MS spectra. Parameters ---------- spec_top : MsmsSpectrum The spectrum to be plotted on the top. spec_bottom : MsmsSpectrum The spectrum to be plotted on the bottom. spectrum_kws : Optional[Dict], optional Keyword arguments for `plot.spectrum`. ax : Optional[plt.Axes], optional Axes instance on which to plot the spectrum. If None the current Axes instance is used. Returns ------- plt.Axes The matplotlib Axes instance on which the spectra are plotted. """ if ax is None: ax = plt.gca() if spectrum_kws is None: spectrum_kws = {} # Top spectrum. spectrum(spec_top, mirror_intensity=False, ax=ax, **spectrum_kws) y_max = ax.get_ylim()[1] # Mirrored bottom spectrum. spectrum(spec_bottom, mirror_intensity=True, ax=ax, **spectrum_kws) y_min = ax.get_ylim()[0] ax.set_ylim(y_min, y_max) ax.axhline(0, color='#9E9E9E', zorder=10) # Update axes so that both spectra fit. min_mz = max([ 0, math.floor(spec_top.mz[0] / 100 - 1) * 100, math.floor(spec_bottom.mz[0] / 100 - 1) * 100 ]) max_mz = max([ math.ceil(spec_top.mz[-1] / 100 + 1) * 100, math.ceil(spec_bottom.mz[-1] / 100 + 1) * 100 ]) ax.set_xlim(min_mz, max_mz) ax.yaxis.set_major_locator(mticker.AutoLocator()) ax.yaxis.set_minor_locator(mticker.AutoMinorLocator()) ax.yaxis.set_major_formatter( mticker.FuncFormatter(lambda x, pos: f'{abs(x):.0%}')) return ax
def plot_one_modulation_spectrogram(ax, X_pwr, f_ax, modf_ax, title_str, f_range, modf_range, c_range, c_map): """ Plots ONLY ONE Modulation Spectrogram """ MF, F = np.meshgrid(modf_ax, f_ax) X_plot = 10 * np.log10(X_pwr[:, :] + np.finfo(float).eps) pmesh = plt.pcolormesh(MF, F, X_plot, cmap=c_map) # Major and Minor ticks ax = plt.gca() ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.yaxis.set_major_locator(ticker.AutoLocator()) ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) plt.xlabel('Modulation frequency (Hz)') plt.ylabel('Conventional frequency (Hz)') if modf_range is not None: xlim = modf_range else: xlim = modf_ax if f_range is not None: ylim = f_range else: ylim = f_ax # set the limits of the plot to the limits of the data plt.axis([xlim.min(), xlim.max(), ylim.min(), ylim.max()]) if c_range is not None: clim = c_range else: clim = np.array([np.mean(X_plot), np.amax(X_plot)]) pmesh.set_clim(vmin=clim[0], vmax=clim[1]) plt.colorbar() plt.title(title_str) plt.draw()
def plot_matrix(data, ax): im = ax.imshow(data.T, aspect='auto', origin='lower', interpolation='nearest') cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05) cb = pyplot.colorbar(im, cax=cax) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.ax.yaxis.set_major_locator(ticker.AutoLocator()) cb.update_ticks()
def plot_hist(): v = [] with open(os.path.join(out, "sampled.txt"), "r") as fff: for line in fff: v.append(line.split()[1:]) v = np.array(v).astype('float') idx = wid_des_his.currentIndex() ax_hist.cla() ax_hist.hist(v[:, idx], bins=10) ax_hist.xaxis.set_major_locator(ticker.AutoLocator()) canvas_hist.draw()
def plot_alignment_np_new( alignment: np.ndarray, mel_dim_x=16, mel_dim_y=5, factor=1, title: Optional[str] = None) -> Tuple[np.ndarray, np.ndarray]: alignment = alignment.T height, width = alignment.shape width_factor = width / 1000 fig, axes = plt.subplots( nrows=1, ncols=1, figsize=(mel_dim_x * factor * width_factor, mel_dim_y * factor), ) img = axes.imshow(X=alignment, aspect='auto', origin='lower', interpolation='none') axes.set_yticks(np.arange(0, height, step=5)) axes.set_xticks(np.arange(0, width, step=50)) axes.xaxis.set_major_locator(ticker.NullLocator()) axes.yaxis.set_major_locator(ticker.NullLocator()) plt.tight_layout() # font logging occurs here figa_core = figure_to_numpy_rgb(fig) fig.colorbar(img, ax=axes) axes.xaxis.set_major_locator(ticker.AutoLocator()) axes.yaxis.set_major_locator(ticker.AutoLocator()) if title is not None: axes.set_title(title) axes.set_xlabel("Encoder timestep") axes.set_ylabel("Decoder timestep") plt.tight_layout() # font logging occurs here figa_labeled = figure_to_numpy_rgb(fig) plt.close() return figa_core, figa_labeled
def setlocators(self, data): ax = list(self.pinf.daxis.values())[-1] comp = getattr(data, '_compression', 1) tframe = getattr(data, '_timeframe', TimeFrame.Days) if tframe == TimeFrame.Years: fmtmajor = '%Y' fmtminor = '%Y' fmtdata = '%Y' elif tframe == TimeFrame.Months: fmtmajor = '%Y' fmtminor = '%b' fmtdata = '%Y-%m' elif tframe == TimeFrame.Weeks: fmtmajor = '%b' fmtminor = '%d' fmtdata = '%Y-%m-%d' elif tframe == TimeFrame.Days: fmtmajor = '%b' fmtminor = '%d' fmtdata = '%Y-%m-%d' elif tframe == TimeFrame.Minutes: fmtmajor = '%H:%M' fmtminor = '%H:%M' fmtdata = '%Y-%m-%d %H:%M' elif tframe == TimeFrame.Seconds: fmtmajor = '%M:%S' fmtminor = '%M:%S' fmtdata = '%M:%S' elif tframe == TimeFrame.MicroSeconds: fmtmajor = '%M:%S' fmtminor = '%S.%f' fmtdata = '%M:%S.%f' elif tframe == TimeFrame.Ticks: fmtmajor = '%M:%S' fmtminor = '%S.%f' fmtdata = '%M:%S.%f' fordata = MyDateFormatter(self.pinf.xreal, fmt=fmtdata) for dax in self.pinf.daxis.values(): dax.fmt_xdata = fordata locmajor = mticker.AutoLocator() locminor = mticker.AutoMinorLocator() ax.xaxis.set_minor_locator(locminor) ax.xaxis.set_major_locator(locmajor) formajor = MyDateFormatter(self.pinf.xreal, fmt=fmtmajor) forminor = MyDateFormatter(self.pinf.xreal, fmt=fmtminor) ax.xaxis.set_major_formatter(formajor) ax.xaxis.set_minor_formatter(forminor)