def reactivity_plot(): fig, ax = plt.subplots(figsize=(15, 8)) ax = sns.lineplot(x='Send Date', y='Reactivity Rate', data=digest, linewidth=4, c='#FF0700', label="DeepNews") ax1 = sns.lineplot(x='Send Date', y=20.767494356659142, data=digest, linewidth=2.5, c='navy', label="Moyenne du secteur") ax.lines[1].set_linestyle("--") ax.legend(fontsize=18) plt.ylim(0, 40) plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='minor', labelsize=18) formatter0 = EngFormatter(unit='%') ax.yaxis.set_major_formatter(formatter0) plt.xlabel("Date d'envoi", fontsize=20) plt.ylabel('Taux de réactivité', fontsize=20) plt.xticks(rotation=0) plt.title("Evolution du taux de réactivité", fontsize=27) x_label_list = [ 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ] ax.set_xticklabels(x_label_list) plt.xlim(xmin=("2019-06-15")) plt.tight_layout() plt.show()
def start_stream(self, queue): try: self.lines = self.ax[0].plot(self.signal) self.ax[0].axis((0, len(self.signal), -5000, 5000)) self.ax[0].set(xlabel='Time', ylabel='Volume') self.ax[1].axis((0, self.sample_rate / 2, 0, 10)) hz_format = EngFormatter(unit='Hz') self.ax[1].xaxis.set_major_formatter(hz_format) self.ax[1].set(xlabel='Frequency', ylabel='Amplitude') self.fig.tight_layout() print('Starting animation') anim = FuncAnimation( self.fig, self.update, interval=self.interval, fargs=(queue, ), blit=False ) print('plotting') plt.show() except Exception as e: sys.exit(type(e).__name__ + ': ' + str(e))
def plot_accum(serie, data, real_data=True, ax=None, label="Modelo", blur=1.0, cor_serie="C0", cor_dados='C1x-', eng_fmt=True, legend=True, cut_day=None, loc=1): n_pts = len(serie) start = dt.datetime.strptime("29-03-2020", "%d-%m-%Y") then = start + dt.timedelta(days=n_pts) days = mdates.drange(start, then, dt.timedelta(days=1)) if ax == None: ax = plt.gca() ax.plot(days, serie, cor_serie, label=label, alpha=blur) if cut_day != None: new_cut_day = start + dt.timedelta(days=cut_day) ax.axvline(x=new_cut_day, color="grey", linestyle="--") if real_data: ax.plot(days, data, cor_dados, label="Dados") ax.grid() ax.set_xlabel("Dias") if eng_fmt: ax.yaxis.set_major_formatter(EngFormatter()) if legend: ax.legend(loc=loc) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m")) return
def Bode(b: np.ndarray, a: np.ndarray = [1], fs: float = 1.0, points: int = 1000, show: bool = True): """ Plot Bode diagram for a given filter :param b: Numerator coefficients :param a: Denominator coefficients :param fs: Sampling frequency in Hz :param points: Number of points to plot :param show: True = show plot immediately, False = show() must be called externally """ #Calculate w, h = sps.freqz(b, a, points) f = w / (2 * np.pi) * fs amp = Lin2dB(np.abs(h)) ang = np.unwrap(np.angle(h)) / (2 * np.pi) * 360 #Plot hzFormatter = EngFormatter(unit="Hz") fig, ax = plt.subplots(2) fig.suptitle("Bode Plot") ax[0].plot(f, amp) ax[0].set_ylabel("Gain [dB]") ax[0].set_xlabel("Frequency [Hz]") ax[0].xaxis.set_major_formatter(hzFormatter) ax[1].plot(f, ang) ax[1].set_ylabel("Angle [°]") ax[1].set_xlabel("Frequency [Hz]") ax[1].xaxis.set_major_formatter(hzFormatter) fig.subplots_adjust(hspace=0.5) if show: plt.show()
def graph_deaths(xs, ws, ts, day, labels, x_label, reversed=True): d = dt.date(2020, 3, 29) fig, ax = plt.subplots(figsize=(16, 8)) if reversed: count = len(ts) else: count = 1 for x, w in zip(xs, ws): vpstats = custom_violin_stats(x, w) vplot = ax.violin(vpstats, [count], vert=True, showmeans=True, showextrema=True, showmedians=True) if reversed: count -= 1 else: count += 1 if reversed: labels = labels[::-1] set_axis_style(ax, labels) #ax.set_yscale("log") ax.yaxis.set_major_formatter(EngFormatter()) new_d = d + dt.timedelta(days=day) ax.set_title('Número de mortes até o dia ' + new_d.strftime("%d/%m/%Y")) ax.set_xlabel(x_label) ax.set_ylabel('Número de mortes') #ax.grid() plt.subplots_adjust(bottom=0.15, wspace=5) return
def onPlotButton(self): logger.debug('onPlotButton') if self.image.measurements is None: return import matplotlib.pyplot as plt import seaborn as sns from matplotlib.gridspec import GridSpec plt.style.use('bmh') pal = sns.color_palette("Blues", n_colors=len(self.image.measurements)) fig = plt.figure(figsize=(2, 2 * 4), dpi=300) gs = GridSpec(nrows=2, ncols=1, height_ratios=[4, 0.5]) ax1 = plt.subplot(gs[0, 0]) ax2 = plt.subplot(gs[1, 0]) self.image.drawMeasurements(ax1, pal) lw = 1 for me, c in zip(self.image.measurements, pal): x = np.arange(start=0, stop=len(me['l']) * self.image.dl, step=self.image.dl) ax2.plot(x, me['l'], linewidth=lw, linestyle='-', color=c, alpha=1, zorder=10) ax1.xaxis.set_major_locator(ticker.MultipleLocator(20)) ax1.xaxis.set_minor_locator(ticker.MultipleLocator(10)) ax1.yaxis.set_major_locator(ticker.MultipleLocator(20)) ax1.yaxis.set_minor_locator(ticker.MultipleLocator(10)) ax2.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax2.xaxis.set_minor_locator(ticker.MultipleLocator(0.5)) ax2.yaxis.set_major_locator(ticker.MultipleLocator(1e4)) ax2.yaxis.set_minor_locator(ticker.MultipleLocator(5e3)) ax2.yaxis.set_major_formatter(EngFormatter(unit='')) fig.savefig(os.path.basename(self.image.file) + ".pdf")
def plot_return(model): """ :param model: """ out_dir = 'out/' + model + '/img/' check_dir(out_dir) input_dir = 'out/' + model + '/return.txt' with open(input_dir, 'r') as f: lines = f.readlines()[1:] lines = np.array(lines) lines = np.char.strip(lines, '\n') lines = np.array([x.split(',') for x in lines]) steps = lines[:, 0].astype(np.int) scores = lines[:, 2].astype(np.float) steps = steps.astype(np.float) scores = scores.astype(np.float) plt.figure() plt.plot(steps, scores) plt.xlabel('step', fontsize=11) plt.ylabel('average score per play', fontsize=11) ax = plt.gca() ax.xaxis.set_major_formatter(EngFormatter()) plt.title('Evaluation Return: "' + model + '"', weight='bold', fontsize=12) plt.savefig(out_dir + 'evaluation-return.pdf') plt.close()
def LinePlotTimePercent(parameter, Parameter_name, dataset, title_name, moy_indus, ymin, ymax): fig, axes = plt.subplots(figsize=(15, 8)) ax = sns.lineplot(x=dateDigest, y=parameter, data=dataset, linewidth=4, c='orangered', label="DeepNews") ax1 = sns.lineplot(x='Send Date', y=moy_indus, data=digest, linewidth=2.5, c='navy', label="Moyenne du secteur") ax.lines[1].set_linestyle("--") plt.ylim(ymin, ymax) formatter0 = EngFormatter(unit='%') ax.yaxis.set_major_formatter(formatter0) x_label_list = [ 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ] axes.set_xticklabels(x_label_list) plt.xlim(xmin=("2019-06-15")) plt.tick_params(axis='both', which='major', labelsize=17) plt.tick_params(axis='both', which='minor', labelsize=17) plt.xlabel("Date d'envoi", fontsize=20) plt.ylabel(Parameter_name, fontsize=20) plt.xticks(rotation=30) plt.title(title_name, fontsize=25)
def plot(X,Y): #### set graph position (row column graphPosition) graph = plt.subplot(111) #### set graph scale graph.set_xscale('linear') #### set formatter formatter = EngFormatter(unit='', places=1) graph.xaxis.set_major_formatter(formatter) ## #### assign value to axis ## graph.axis([0, maxX, minY-0.02, 1]) #### plot data graph.plot(X, Y, 'r', label='samples') ## graph.plot(X, Y[0], 'r', label='samples') ## graph.plot(X, Y[1], 'g', label='800 samples') ## graph.plot(X, Y[2], 'b', label='600 samples') ## graph.plot(X, Y[3], 'c', label='400 samples') ## graph.plot(X, Y[4], 'm', label='200 samples') graph.legend(loc='lower right',fancybox=True) #### text on X and Y axis ## graph.set_title("k-fold cross-validation") graph.set_xlabel('principle component analysis') graph.set_ylabel('Accuracy') ## graph.set_xlabel('number of k') graph.set_xlabel('number of features') #### show graph plt.show()
def plot_return_moving_average(model): """ :param model: """ out_dir = 'out/' + model + '/img/' check_dir(out_dir) input_dir = 'out/' + model + '/return_moving_average.txt' with open(input_dir, 'r') as f: lines = f.readlines()[1:] lines = np.array(lines) lines = np.char.strip(lines, '\n') lines = np.array([x.split(',') for x in lines]) return_moving_averages = lines[:, 0].astype(np.float) episodes = np.arange(30, len(return_moving_averages) + 30) plt.figure() plt.plot(episodes, return_moving_averages) plt.xlabel('episodes', fontsize=11) plt.ylabel('return per episode', fontsize=11) ax = plt.gca() ax.xaxis.set_major_formatter(EngFormatter()) plt.title('Training Return: "' + model + '"', weight='bold', fontsize=12) plt.savefig(out_dir + 'training-return.pdf') plt.close()
def plot_timers(hits, frames_idx, ax): index = np.arange(len(hits)) for chip in range(0, 4): # Index frame to only the particular chip chip_events = hits[hits['chipId'] == chip] chip_index = index[hits['chipId'] == chip] # Get only every 1000nth hit toa = chip_events['ToA'][1::1000] toa_index = chip_index[1::1000] ax.scatter(toa_index, toa, label='Chip %d' % chip) ax.set_title('ToA as function of hit index (every 1000nth hit)') formatter0 = EngFormatter(unit='hit') ax.xaxis.set_major_formatter(formatter0) ax.set_xlabel('Hit index') ax.set_ylabel('ToA time') ax.legend() # Frame start and end time for frame_idx in frames_idx: ax.axvline(frame_idx['start_idx']) ax.axvline(frame_idx['end_idx'])
def _tweak_formats(self, axis, unit): # formatting adjustments to ensure proper plot box = axis.get_position() axis.set_position([box.x0, box.y0, box.width * 0.9, box.height]) if unit: y_formatter = EngFormatter(unit=unit, places=1) axis.yaxis.set_major_formatter(y_formatter) axis.set_ymargin(0.05) axis.label_outer() axis.locator_params(axis='both', tight=True) axis.legend(loc='center left', bbox_to_anchor=(1, 0.5)) axis.spines['bottom'].set_visible(True) if axis.is_last_row(): axis.set_xlabel(r'$\mathrm{Time}$') x_formatter = EngFormatter(unit='s', places=0) axis.xaxis.set_major_formatter(x_formatter)
def plot_hit_rate(local_hit_rate, center_time, dtoa_time, beam_on_windows, frames_idx, ax): # Plot ax.step(center_time, local_hit_rate, where='mid', color='red') # Beam on and off time for window in beam_on_windows: if window[0] == -1: start_time = 0 else: start_time = center_time[window[0]] ax.axvspan(start_time, center_time[window[1]], alpha=0.2, color='green') # Frame start and end time for frame in frames_idx: ax.axvline(dtoa_time[frame['start_idx']]) ax.axvline(dtoa_time[frame['end_idx']]) # Format graph formatter0 = EngFormatter(unit='hit') ax.yaxis.set_major_formatter(formatter0) ax.set_title('Hit rate as function of time') ax.set_xlabel('Time (s)') ax.set_ylabel('Hit Rate (hits/s)')
def plot_totals(self, ax): """Plot bars indicating total set size """ orig_ax = ax ax = self._reorient(ax) rects = ax.barh(np.arange(len(self.totals.index.values)), self.totals, .5, color=self._facecolor, edgecolor=self._facecolor, linewidth=2, zorder=10, align='center') self._label_sizes(ax, rects, 'left' if self._horizontal else 'top') max_total = self.totals.max() if self._horizontal: orig_ax.set_xlim(max_total, 0) for x in ['top', 'left', 'right']: ax.spines[self._reorient(x)].set_visible(False) ax.yaxis.set_visible(False) ax.xaxis.grid(True) ax.patch.set_visible(False) ax.set_xlabel('Total size') # ax.xaxis.set_major_formatter( # FuncFormatter(lambda x, p: format(int(x), ','))) ax.xaxis.set_major_formatter(EngFormatter(sep=''))
def plot_intersections(self, ax): """Plot bars indicating intersection size """ ax = self._reorient(ax) rects = ax.bar(np.arange(len(self.intersections)), self.intersections, .5, color=self._facecolor, edgecolor=self._facecolor, linewidth=2, zorder=10, align='center') self._label_sizes(ax, rects, 'top' if self._horizontal else 'right') ax.xaxis.set_visible(False) for x in ['top', 'bottom', 'right']: ax.spines[self._reorient(x)].set_visible(False) tick_axis = ax.yaxis tick_axis.grid(True) ax.set_ylabel('Intersection size') # ax.yaxis.set_major_formatter( # FuncFormatter(lambda x, p: format(int(x), ','))) ax.yaxis.set_major_formatter(EngFormatter(sep=''))
def plot_loss_comparison(models): """ :param models: """ out_dirs = [] steps = [] losses = [] mavg_losses = [] for i, e in enumerate(models): out_dir = 'out/' + e + '/img/comparison/' out_dirs.append(out_dir) check_dir(out_dir) input_dir = 'out/' + e + '/loss.txt' with open(input_dir, 'r') as f: lines = f.readlines()[1:] lines = np.array(lines) lines = np.char.strip(lines, '\n') lines = np.array([x.split(',') for x in lines]) steps.append(lines[:, 0].astype(np.int)) losses.append(lines[:, 2].astype(np.float)) mavg_losses.append(moving_average(losses[i], window=50)) plt.figure() for i, e in enumerate(models): plt.plot(steps[i][50::1000], mavg_losses[i][::1000], label='Loss ' + e) plt.xlabel('episodes', fontsize=11) plt.ylabel('loss', fontsize=11) ax = plt.gca() ax.xaxis.set_major_formatter(EngFormatter()) ax.yaxis.set_major_formatter(EngFormatter()) plt.legend() plt.title('Temporal-difference errors', weight='bold', fontsize=12) for i in range(len(models)): m = str(models).replace('[', '').replace(']', '').replace(', ', '-').replace("'", "") plt.savefig(out_dirs[i] + m + '-losses-comparison.pdf') plt.close()
def Plot(data1, data2, kind='corridor', title='', filename=None): fig = plt.figure(1, facecolor='white', figsize=(6.25, 3.5)) gs = plt.GridSpec(100, 100, bottom=0.15, left=0.1, right=1.0, top=1.0) ax = fig.add_subplot(gs[25:100, 10:95]) ax.spines['top'].set_linewidth(1) ax.spines['left'].set_linewidth(1) ax.spines['right'].set_linewidth(1) ax.spines['bottom'].set_linewidth(1) ax.set_xlabel("Location along reference axis (from network outlet)") ax.set_ylabel('Width (m)') formatter = EngFormatter(unit='m') ax.xaxis.set_major_formatter(formatter) ax.tick_params(axis='both', width=1, pad=2) for tick in ax.xaxis.get_major_ticks(): tick.set_pad(2) ax.grid(which='both', axis='both', alpha=0.5) if kind == 'corridor': PlotContinuityProfile(ax, data1, window=5, basis=0) PlotCorridorLimit(ax, data1, window=5, basis=0) profile = MkCorridorProfile(data2) PlotProfile(ax, profile) else: PlotContinuityProfile(ax, data1, window=5, basis=0, maxclass=2) profile = MkActiveChannelProfile(data2) PlotProfile(ax, profile) # if len(args) > 1: # ax.legend() fig_size_inches = 12.5 aspect_ratio = 4 cbar_L = "None" [fig_size_inches, map_axes, cbar_axes] = MapFigureSizer(fig_size_inches, aspect_ratio, cbar_loc=cbar_L, title=True) plt.title(title) fig.set_size_inches(fig_size_inches[0], fig_size_inches[1]) ax.set_position(map_axes) if filename is None: fig.show() elif filename.endswith('.pdf'): plt.savefig(filename, format='pdf', dpi=600) plt.clf() else: plt.savefig(filename, format='png', dpi=300) plt.clf()
def __init__(self, fmt, set_label_fun=None, label_fmt=None, unit=None): FormatStrFormatter.__init__(self, fmt) self.engfmt = EngFormatter(unit="", places=2) self.set_label_fun = set_label_fun self.default_unit = unit self._label_unit = None self.set_label_fmt(label_fmt) self.label_template = None
def configureFreqAxisFormatting(axes): ''' Configures the x axis of the supplied axes to render Frequency values in a log format. :param axes: ''' hzFormatter = EngFormatter(places=0) axes.get_xaxis().set_major_formatter(hzFormatter) axes.get_xaxis().set_minor_formatter(PrintFirstHalfFormatter(hzFormatter))
def plot(all_data, key_to_plot, directory=".", eng_fmt=False): list_of_n = sorted(all_data.keys()) samples = len(next(iter(all_data.values()))) data = [[all_data[n][i][key_to_plot] for i in range(samples)] for n in list_of_n] data_mean = list(map(mean, data)) data_min = list(map(min, data)) data_max = list(map(max, data)) data_dev = list(map(pstdev, data)) ax = plt.gca() ax2 = ax.twinx() ax.plot(list_of_n, data_mean, label="mean") ax.plot(list_of_n, data_min, label="min/max", color='#808080') ax.plot(list_of_n, data_max, color='#808080') ax2.plot(list_of_n, data_dev, label="stdev", color='#d62728') ax.fill_between(list_of_n, data_min, data_max, color='#539caf', alpha=0.4) # x axis ax.set_xlabel('n') formatter = EngFormatter(sep="") ax.xaxis.set_major_formatter(formatter) # plt.xticks(np.arange(min(list_of_n), max(list_of_n)+1, 10000)) # first y axis ax.set_ylabel(key_to_plot) if eng_fmt: ax.yaxis.set_major_formatter(formatter) ax.yaxis.set_major_locator(MaxNLocator(nbins='auto', integer=True)) # second y axis ax1_range = max(data_max) - min(data_min) dev_middle = min(data_dev) + max(data_dev) / 2 ax2.set_ylim([dev_middle - ax1_range / 2, dev_middle + ax1_range / 2]) no_negative = lambda x, pos=None: "" if x < 0 else (formatter.format_eng( x) if eng_fmt else "%.2f" % x) ax2.yaxis.set_major_formatter(FuncFormatter(no_negative)) ax.legend(loc=2) ax2.legend(loc=1) plt.savefig(os.path.join(directory, 'plot_{}.pdf'.format(key_to_plot))) plt.clf()
class DaqMultiPlotter(): """ """ data_size = None time = None formatter = EngFormatter(unit='s', places=1) # interval frame_limits = None @classmethod def configure(cls, samples_per_channel): """ """ cls.data_size = samples_per_channel cls.time = np.linspace(0, 1, samples_per_channel) cls.formatter = EngFormatter(unit='s', places=1) # interval cls.frame_limits = [0, 1, -10, 10] @classmethod def start(cls): plt.ion() plt.show() @classmethod def send_data(cls, data): """ """ plt.clf() num_charts = len(data) i = 0 for buffer_name in data: i += 1 chart_id = num_charts*100 + 10 + i ax = plt.subplot(chart_id) ax.xaxis.set_major_formatter(cls.formatter) ax.set_xlabel(buffer_name) ax.axis(cls.frame_limits) ax.set_autoscale_on(False) plt.grid() for channel in data[buffer_name]: ax.plot(cls.time, data[buffer_name][channel]) plt.draw() plt.pause(0.0000001) @classmethod def stop(cls): plt.ioff() plt.show()
def format_ticks(ax, x=True, y=True, rotate=True): bp_formatter = EngFormatter('b') if y: ax.yaxis.set_major_formatter(bp_formatter) if x: ax.xaxis.set_major_formatter(bp_formatter) ax.xaxis.tick_bottom() if rotate: ax.tick_params(axis='x', rotation=45)
def plot_return_comparison(model1, model2, label1, label2): """ :param model1: :param model2: :param label1: :parameter label2: """ out_dir = 'out/' + model2 + '/img/comparison/' check_dir(out_dir) input_dir1 = 'out/' + model1 + '/return.txt' input_dir2 = 'out/' + model2 + '/return.txt' with open(input_dir1, 'r') as f: lines = f.readlines()[1:] lines = np.array(lines) lines = np.char.strip(lines, '\n') lines = np.array([x.split(',') for x in lines]) steps1 = lines[:, 0] steps1 = steps1.astype(np.float) score1 = lines[:, 2] score1 = score1.astype(np.float) with open(input_dir2, 'r') as f: lines = f.readlines()[1:] lines = np.array(lines) lines = np.char.strip(lines, '\n') lines = np.array([x.split(',') for x in lines]) steps2 = lines[:, 0].astype(np.float) score2 = lines[:, 2].astype(np.float) plt.figure() plt.plot(steps1[:len(steps2) - 1], score1[:len(score2) - 1], label=label1) # plt.plot(steps1, score1, label=label1) plt.plot(steps2, score2, label=label2) plt.xlabel('episodes', fontsize=11) plt.ylabel('score', fontsize=11) plt.xlim([-10000, 310000]) plt.ylim([-1, 30]) ax = plt.gca() ax.xaxis.set_major_formatter(EngFormatter()) plt.legend() plt.title('Evaluation returns of models "' + model1 + '" and "' + model2 + '"', weight='bold', fontsize=12) plt.savefig(out_dir + 'scores-comparison-' + model1 + '-' + model2 + '.pdf') plt.close()
def graph_scatter(name, df, x, y, group_key): fig, ax = plt.subplots(1, 1) n_groups = len(df.groupby(group_key)) cm = plt.get_cmap('gist_rainbow') colors = [cm(1. * i / n_groups) for i in range(n_groups)] for i, (group_name, group) in enumerate(df.groupby(group_key)): group.plot.line(x, y, ax=ax, label=group_name, color=colors[i], marker='.', linewidth=0.25, linestyle='--', markeredgewidth=.2, markeredgecolor='black') ax.yaxis.grid(True, which='major', linestyle='-') ax.yaxis.grid(True, which='minor', linestyle=':') ax.xaxis.grid(True, which='major', linestyle='-') ax.xaxis.grid(True, which='minor', linestyle=':') ax.set_ylabel('F max') ax.yaxis.set_major_formatter(EngFormatter('MHz')) ax.yaxis.set_minor_formatter(EngFormatter('MHz')) ax.set_xlabel('LUT Utilisation') ax.xaxis.set_major_formatter(PercentFormatter()) cols = math.ceil(n_groups / 10) ax.legend(ncol=int(cols), framealpha=1.0, title=group_key, loc='lower left') fig.set_size_inches(10, 7) plt.tight_layout() plt.savefig(name + '.pdf') plt.show()
def configure(cls, samples_per_channel): """ """ cls.data_size = samples_per_channel cls.time = np.linspace(0, 1, samples_per_channel) cls.formatter = EngFormatter(unit='s', places=1) # interval cls.frame_limits = [0, 1, -10, 10]
def histogram_of_every_row(counts_col, **kwargs): """ Plots the histogram of every row in a dataframe, overlaying them. Meant to be used within a map_dataframe call. Implementation inspired in https://matplotlib.org/gallery/api/histogram_path.html :param df: Dataframe :param counts_col: Name of the counts column :param edges_col: Name of the edges column :param ax: Matplotlib axis object :return: """ ax = plt.gca() edges_col = kwargs.pop( "edges_col") if "edges_col" in kwargs else "hist_edges" data = kwargs.pop("data") color = kwargs.pop("color") label = kwargs.pop("label") if "label" in kwargs else None # FIXME: Find a way to increase opacity resolution min_op = 1. / 256. opacity = 1. / len(data) opacity = opacity if opacity >= min_op else min_op logger.info("plotting %d histograms overlaid with opacity %e." % (len(data), opacity)) # get the corners of the rectangles for the histogram bins = data[edges_col].iloc[0] left = np.array(bins[:-1]) right = np.array(bins[1:]) bottom = np.zeros(len(left)) for _ix, _d in data.iterrows(): counts = _d[counts_col] top = bottom + counts # function to build a compound path XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T # get the Path object barpath = Path.make_compound_path_from_polys(XY) # make a patch out of it patch = PathPatch(barpath, alpha=opacity, lw=0, color=color) ax.add_patch(patch) ax.xaxis.set_major_locator(ticker.LogLocator(base=10)) ax.xaxis.set_major_formatter(ticker.LogFormatterMathtext(base=10)) ax.yaxis.set_major_formatter(EngFormatter(unit='')) ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), data[counts_col].apply(lambda r: np.max(r)).max())
def test_usetex_engformatter(): matplotlib.rcParams['text.usetex'] = True fig, ax = plt.subplots() ax.plot([0, 500, 1000], [0, 500, 1000]) ax.set_xticks([0, 500, 1000]) formatter = EngFormatter() ax.xaxis.set_major_formatter(formatter) fig.canvas.draw() x_tick_label_text = [label.get_text() for label in ax.get_xticklabels()] # Checking if the dollar `$` signs have been inserted around numbers # in tick label text. assert x_tick_label_text == ['$0$', '$500$', '$1$ k']
def plot_variable(dataset, variable=''): """ Plot one or all dependent variables from a Qucs Dataset :param dataset: Qucs Dataset :param variable" """ d = QucsData(dataset) # plot single independent or dependent variable if variable: n = variable fig, ax = plt.subplots(figsize=(8, 6)) ax.plot(d.data[n]) ax.set_xlabel('step') ax.set_ylabel(n) ax.grid(True) plt.show() return # plot all dependent variables for n in d.dependent.keys(): dep = len(d.dependent[n]) if dep == 1: a = d.dependent[n][0] fig, ax = plt.subplots(figsize=(8, 6)) x = d.data[a] y = d.data[n] ax.plot(x, y) ax.set_xlabel(a) ax.set_ylabel(n) ax.grid(True) ax.set_xlim((min(x), max(x))) formatter = EngFormatter(places=1) ax.xaxis.set_major_formatter(formatter) plt.show() if dep == 2: a, b = d.dependent[n] x = d.data[a] y = d.data[b] z = d.data[n] xs, ys = np.meshgrid(x, y) fig = plt.figure() ax = Axes3D(fig) ax.view_init(azim=-120) ax.plot_wireframe(xs, ys, z.transpose()) ax.set_xlabel(a) ax.set_ylabel(b) ax.set_zlabel(n) plt.show()
def __init__(self, cc): self.cc = cc self.all = (pd.read_csv( os.path.join(cc.base_path, "out", "nuclei.pandas.csv")).merge( cc.layout, on=["row", "col"]).drop(columns=["Unnamed: 0"])) self._df = None self._lines = None self._lines_filt = None self._dmax = None self.formatter = EngFormatter(unit='')
def draw_histogram(vals): maxval = max(vals) fig, ax = plt.subplots() formatter = EngFormatter(unit = 'B') n, bins, patches = ax.hist(vals, bins = 10**np.linspace(0, math.ceil(math.log10(maxval)), math.ceil(math.log10(maxval)) + 1)) plt.yscale('symlog') plt.xscale('symlog') ax.xaxis.set_major_formatter(formatter) plt.xlabel("allocation size") plt.ylabel("number of allocations") plt.title("Total number of allocations: " + str(len(vals))) plt.show()