Python matplotlib.pyplot.yscale() Examples
The following are 30
code examples of matplotlib.pyplot.yscale().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: QCreport.py From geoist with MIT License | 6 votes |
def graph_event_types(catalog, prefix): """Graph number of cumulative events by type of event.""" typedict = {} for evtype in catalog['type'].unique(): typedict[evtype] = (catalog['type'] == evtype).cumsum() plt.figure(figsize=(12, 6)) for evtype in typedict: plt.plot_date(catalog['convtime'], typedict[evtype], marker=None, linestyle='-', label=evtype) plt.yscale('log') plt.legend() plt.xlim(min(catalog['convtime']), max(catalog['convtime'])) plt.xlabel('Date', fontsize=14) plt.ylabel('Cumulative number of events', fontsize=14) plt.title('Cumulative Event Type', fontsize=20) plt.savefig('%s_cumuleventtypes.png' % prefix, dpi=300) plt.close()
Example #2
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def hist_mrates(d, i=0, m=10, bins=(0, 4000, 100), yscale='log', pdf=False, dense=True, plot_style=None): """Histogram of m-photons rates. See also :func:`hist_mdelays`. """ ph = d.get_ph_times(ich=i) if dense: ph_mrates = 1.*m/((ph[m-1:]-ph[:ph.size-m+1])*d.clk_p*1e3) else: ph_mrates = 1.*m/(np.diff(ph[::m])*d.clk_p*1e3) hist = HistData(*np.histogram(ph_mrates, bins=_bins_array(bins))) ydata = hist.pdf if pdf else hist.counts plot_style_ = dict(marker='o') plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(hist.bincenters, ydata, **plot_style_) gca().set_yscale(yscale) xlabel("Rates (kcps)") ## Bursts stats
Example #3
Source File: test_axes.py From neural-network-animation with MIT License | 6 votes |
def test_markevery_log_scales(): cases = [None, 8, (30, 8), [16, 24, 30], [0,-1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.xscale('log') plt.yscale('log') plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
Example #4
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def _hist_burst_taildist(data, bins, pdf, weights=None, yscale='log', color=None, label=None, plot_style=None, vline=None): hist = HistData(*np.histogram(data[~np.isnan(data)], bins=_bins_array(bins), weights=weights)) ydata = hist.pdf if pdf else hist.counts default_plot_style = dict(marker='o') if plot_style is None: plot_style = {} if color is not None: plot_style['color'] = color if label is not None: plot_style['label'] = label default_plot_style.update(_normalize_kwargs(plot_style, kind='line2d')) plt.plot(hist.bincenters, ydata, **default_plot_style) if vline is not None: plt.axvline(vline, ls='--') plt.yscale(yscale) if pdf: plt.ylabel('PDF') else: plt.ylabel('# Bursts')
Example #5
Source File: plots.py From clusterGAN with MIT License | 6 votes |
def plot_train_loss(df=[], arr_list=[''], figname='training_loss.png'): fig, ax = plt.subplots(figsize=(16,10)) for arr in arr_list: label = df[arr][0] vals = df[arr][1] epochs = range(0, len(vals)) ax.plot(epochs, vals, label=r'%s'%(label)) ax.set_xlabel('Epoch', fontsize=18) ax.set_ylabel('Loss', fontsize=18) ax.set_title('Training Loss', fontsize=24) ax.grid() #plt.yscale('log') plt.legend(loc='upper right', numpoints=1, fontsize=16) print(figname) plt.tight_layout() fig.savefig(figname)
Example #6
Source File: gradev-demo.py From allantools with GNU Lesser General Public License v3.0 | 6 votes |
def example1(): """ Compute the GRADEV of a white phase noise. Compares two different scenarios. 1) The original data and 2) ADEV estimate with gap robust ADEV. """ N = 1000 f = 1 y = np.random.randn(1,N)[0,:] x = [xx for xx in np.linspace(1,len(y),len(y))] x_ax, y_ax, (err_l, err_h), ns = allan.gradev(y,data_type='phase',rate=f,taus=x) plt.errorbar(x_ax, y_ax,yerr=[err_l,err_h],label='GRADEV, no gaps') y[int(np.floor(0.4*N)):int(np.floor(0.6*N))] = np.NaN # Simulate missing data x_ax, y_ax, (err_l, err_h) , ns = allan.gradev(y,data_type='phase',rate=f,taus=x) plt.errorbar(x_ax, y_ax,yerr=[err_l,err_h], label='GRADEV, with gaps') plt.xscale('log') plt.yscale('log') plt.grid() plt.legend() plt.xlabel('Tau / s') plt.ylabel('Overlapping Allan deviation') plt.show()
Example #7
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def hist_width(d, i=0, bins=(0, 10, 0.025), pdf=True, weights=None, yscale='log', color=None, plot_style=None, vline=None): """Plot histogram of burst durations. Parameters: d (Data): Data object i (int): channel index bins (array or None): array of bin edges. If len(bins) == 3 then is interpreted as (start, stop, step) values. pdf (bool): if True, normalize the histogram to obtain a PDF. color (string or tuple or None): matplotlib color used for the plot. yscale (string): 'log' or 'linear', sets the plot y scale. plot_style (dict): dict of matplotlib line style passed to `plot`. vline (float): If not None, plot vertical line at the specified x position. """ weights = weights[i] if weights is not None else None burst_widths = d.mburst[i].width * d.clk_p * 1e3 _hist_burst_taildist(burst_widths, bins, pdf, weights=weights, vline=vline, yscale=yscale, color=color, plot_style=plot_style) plt.xlabel('Burst width (ms)') plt.xlim(xmin=0)
Example #8
Source File: meep_utils.py From python-meep-utils with GNU General Public License v2.0 | 6 votes |
def diagnostic_plot(x, values_and_labels=(), plotmodulus=False, ylog=True, title="diagnostic plot", xlabel="x", ylabel="y"): # {{{ #try: plt.figure(figsize=(7,6)) plotmin = None for value, label in values_and_labels: plt.plot(x, np.abs(value) if plotmodulus else value, label=label) if len(value)>0: if plotmin==None or plotmin > np.min(value): plotmin = max(np.min(np.abs(value)), np.max(np.abs(value))/1e10) plt.legend(prop={'size':10}, loc='lower left') plt.xlabel(xlabel); plt.ylabel(ylabel); plt.title(title) if ylog and plotmin is not None: plt.yscale("log") plt.ylim(bottom=plotmin) ## ensure reasonable extent of values of 10 orders of magnitude plt.savefig("%s.png" % title, bbox_inches='tight') #except: #meep.master_printf("Diagnostic plot %s failed with %s, computation continues" % (title, sys.exc_info()[0])) # }}}
Example #9
Source File: predcel_plot.py From AiGEM_TeamHeidelberg2017 with MIT License | 6 votes |
def draw(x, y1, y2, y3, y4, y5, log, name, prefix, suffix, summariesdir): plt.figure(1, dpi=300) plt.plot(x, y2, label='Uninfected', color=colors['mblue']) plt.plot(x, y1, label='Infected', color=colors['lblue']) plt.plot(x, y3, label='Phage-producing', color=colors['blue']) plt.plot(x, y4, label='All E. coli', color=colors['fblue']) plt.plot(x, y5, label='Phage', color=colors['red']) plt.legend() logstr = '' if log: plt.yscale('log') logstr = '_log' plt.ylabel('c in Lagoon [cfu]/[pfu]') plt.title('Calculation of Concentrations during PREDCEL') plt.xlabel('Time [min]') plt.savefig(os.path.join(summariesdir, '{}{}_{}.png'.format(prefix, name, logstr, suffix))) plt.gcf().clear()
Example #10
Source File: test_axes.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_markevery_log_scales(): cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.xscale('log') plt.yscale('log') plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
Example #11
Source File: lending_plots.py From ml-fairness-gym with Apache License 2.0 | 6 votes |
def plot_cumulative_recall_differences(cumulative_recalls, path): """Plot differences in cumulative recall between groups up to time T.""" plt.figure(figsize=(8, 3)) style = {'dynamic': '-', 'static': '--'} for setting, recalls in cumulative_recalls.items(): abs_array = np.mean(np.abs(recalls[0::2, :] - recalls[1::2, :]), axis=0) plt.plot(abs_array, style[setting], label=setting) plt.title( 'Recall gap for EO agent in dynamic vs static environments', fontsize=16) plt.yscale('log') plt.xscale('log') plt.ylabel('TPR gap', fontsize=16) plt.xlabel('# steps', fontsize=16) plt.grid(True) plt.legend() plt.tight_layout() _write(path)
Example #12
Source File: distribution.py From pyprob with BSD 2-Clause "Simplified" License | 6 votes |
def plot(self, min_val=-10, max_val=10, step_size=0.1, figsize=(10, 5), xlabel=None, ylabel='Probability', xticks=None, yticks=None, log_xscale=False, log_yscale=False, file_name=None, show=True, fig=None, *args, **kwargs): if fig is None: if not show: mpl.rcParams['axes.unicode_minus'] = False plt.switch_backend('agg') fig = plt.figure(figsize=figsize) fig.tight_layout() xvals = np.arange(min_val, max_val, step_size) plt.plot(xvals, [torch.exp(self.log_prob(x)) for x in xvals], *args, **kwargs) if log_xscale: plt.xscale('log') if log_yscale: plt.yscale('log', nonposy='clip') if xticks is not None: plt.xticks(xticks) if yticks is not None: plt.xticks(yticks) # if xlabel is None: # xlabel = self.name plt.xlabel(xlabel) plt.ylabel(ylabel) if file_name is not None: plt.savefig(file_name) if show: plt.show()
Example #13
Source File: test_examples.py From pynvme with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_ioworker_performance(nvme0n1): import matplotlib.pyplot as plt output_io_per_second = [] percentile_latency = dict.fromkeys([90, 99, 99.9, 99.99, 99.999]) nvme0n1.ioworker(io_size=8, lba_random=True, read_percentage=100, output_io_per_second=output_io_per_second, output_percentile_latency=percentile_latency, time=10).start().close() logging.info(output_io_per_second) logging.info(percentile_latency) X = [] Y = [] for _, k in enumerate(percentile_latency): X.append(k) Y.append(percentile_latency[k]) plt.plot(X, Y) plt.xscale('log') plt.yscale('log') #plt.show()
Example #14
Source File: test_replayer.py From pynvme with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_replay_pynvme_trace(nvme0, nvme0n1, accelerator=1.0): filename = sg.PopupGetFile('select the trace file to replay', 'pynvme') if filename: logging.info(filename) # format before replay nvme0n1.format(512) responce_time = [0]*1000000 replay_logfile(filename, nvme0n1, nvme0.mdts, accelerator, responce_time) import matplotlib.pyplot as plt plt.plot(responce_time) plt.xlabel('useconds') plt.ylabel('# IO') plt.xlim(1, len(responce_time)) plt.ylim(bottom=1) plt.xscale('log') plt.yscale('log') plt.title(filename) plt.tight_layout() plt.show()
Example #15
Source File: test_axes.py From ImageFusion with MIT License | 6 votes |
def test_markevery_log_scales(): cases = [None, 8, (30, 8), [16, 24, 30], [0,-1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] cols = 3 gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols) delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta for i, case in enumerate(cases): row = (i // cols) col = i % cols plt.subplot(gs[row, col]) plt.title('markevery=%s' % str(case)) plt.xscale('log') plt.yscale('log') plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
Example #16
Source File: plot.py From readgssi with GNU Affero General Public License v3.0 | 6 votes |
def histogram(ar, verbose=True): """ Shows a y-log histogram of data value distribution. :param numpy.ndarray ar: The radar array :param bool verbose: Verbose, defaults to False """ mean = np.mean(ar) std = np.std(ar) ll = mean - (std * 3) # lower color limit ul = mean + (std * 3) # upper color limit if verbose: fx.printmsg('drawing log histogram...') fx.printmsg('mean: %s (if high, use background removal)' % mean) fx.printmsg('stdev: %s' % std) fx.printmsg('lower limit: %s [mean - (3 * stdev)]' % ll) fx.printmsg('upper limit: %s [mean + (3 * stdev)]' % ul) fig = plt.figure() hst = plt.hist(ar.ravel(), bins=256, range=(ll, ul), fc='k', ec='k') plt.yscale('log', nonposy='clip') plt.show()
Example #17
Source File: engine_mpl.py From tellurium with Apache License 2.0 | 6 votes |
def __init__(self, layout=PlottingLayout(), use_legend=True, xtitle=None, ytitle=None, title=None, linewidth=None, xlim=None, ylim=None, logx=None, logy=None, xscale=None, yscale=None, grid=None, ordinates=None, tag=None, labels=None, figsize=(9,6), savefig=None, dpi=None): super(MatplotlibFigure, self).__init__(title=title, layout=layout, xtitle=xtitle, ytitle=ytitle, logx=logx, logy=logy) self.use_legend = use_legend self.linewidth = linewidth self.xscale = xscale self.yscale = yscale self.grid = grid self.ordinates = ordinates self.tag = tag self.labels = labels self.figsize = figsize self.savefig = savefig self.dpi = dpi
Example #18
Source File: plot.py From f-AnoGAN with MIT License | 6 votes |
def flush(plt_dir): prints = [] for name, vals in _since_last_flush.items(): prints.append("{}\t{}".format(name, np.mean(vals.values()))) _since_beginning[name].update(vals) x_vals = np.sort(_since_beginning[name].keys()) y_vals = [_since_beginning[name][x] for x in x_vals] plt.clf() plt.plot(x_vals, y_vals) #plt.yscale('log') plt.xlabel('iteration') plt.ylabel(name) plt.savefig('%s/%s.jpg' %(plt_dir,name.replace(' ', '_'))) print "iter {}\t{}".format(_iter[0], "\t".join(prints)) _since_last_flush.clear() with open('%s/log.pkl'%plt_dir, 'wb') as f: pickle.dump(dict(_since_beginning), f, pickle.HIGHEST_PROTOCOL)
Example #19
Source File: analyze_dimension_and_radius.py From megaman with BSD 2-Clause "Simplified" License | 6 votes |
def find_dimension_plot(avg_neighbors, radii, fit_range, savefig=False, fname='dimension_plot.png'): tickrange = np.append(np.arange(0, len(radii)-1, 10), len(radii)-1) try: m,b = polyfit(np.log(radii[fit_range]), np.log(avg_neighbors[fit_range]), 1) except: m = 0 b = 0 if MATPLOTLIB_LOADED: plt.scatter(radii, avg_neighbors) plt.plot(radii, avg_neighbors, color='red') plt.plot(radii[fit_range], np.exp(b)*radii[fit_range]**m, color='blue') plt.yscale('log') plt.xscale('log') plt.xlabel('radius') plt.ylabel('neighbors') plt.title('data dim='+repr(m)[:4] + "\nRadius = [" + str(np.min(radii)) + ", " + str(np.max(radii)) + "]") plt.xlim([np.min(radii), np.max(radii)]) plt.xticks(np.round(radii[tickrange], 1), np.round(radii[tickrange], 1)) plt.grid(b=True,which='minor') print('dim=', m ) plt.show() if savefig: plt.savefig(fname, format='png') return(m)
Example #20
Source File: example_fwding_summary.py From lndmanage with MIT License | 6 votes |
def plot_fees(forwarding_events): """ Plots forwarding fees and effective fee rate in color code. :param forwarding_events: """ times = [] amounts = [] color = [] for f in forwarding_events: times.append(datetime.datetime.fromtimestamp(f['timestamp'])) amounts.append(f['fee_msat']) color.append(f['effective_fee']) plt.xticks(rotation=45) plt.scatter(times, amounts, c=color, norm=colors.LogNorm(vmin=1E-6, vmax=1E-3), s=2) plt.yscale('log') plt.ylabel('Fees [msat]') plt.ylim((0.5, 1E+6)) plt.colorbar(label='effective feerate (base + rate)') plt.show()
Example #21
Source File: log_analyzer.py From pylinac with MIT License | 6 votes |
def plot_histogram(self, scale='log', bins=None, show=True): """Plot a histogram of the gamma map values. Parameters ---------- scale : {'log', 'linear'} Scale of the plot y-axis. bins : sequence The bin edges for the gamma histogram; see numpy.histogram for more info. """ self.is_map_calced(raise_error=True) if bins is None: bins = self.bins plt.clf() plt.hist(self.array.flatten(), bins=bins) plt.yscale(scale) if show: plt.show()
Example #22
Source File: example_fwding_summary.py From lndmanage with MIT License | 6 votes |
def plot_forwardings(forwarding_events): """ Plots a time series of the forwarding amounts. :param forwarding_events: """ times = [] amounts = [] for f in forwarding_events: times.append(datetime.datetime.fromtimestamp(f['timestamp'])) amounts.append(f['amt_in']) plt.xticks(rotation=45) plt.scatter(times, amounts, s=2) plt.yscale('log') plt.ylabel('Forwarding amount [sat]') plt.show()
Example #23
Source File: utils.py From scvelo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot( arrays, normalize=False, colors=None, labels=None, xlabel=None, ylabel=None, xscale=None, yscale=None, ax=None, figsize=None, dpi=None, show=True, ): ax = pl.figure(None, figsize, dpi=dpi) if ax is None else ax arrays = np.array(arrays) arrays = ( arrays if isinstance(arrays, (list, tuple)) or arrays.ndim > 1 else [arrays] ) palette = default_palette(None).by_key()["color"][::-1] colors = palette if colors is None or len(colors) < len(arrays) else colors for i, array in enumerate(arrays): X = array[np.isfinite(array)] X = X / np.max(X) if normalize else X pl.plot(X, color=colors[i], label=labels[i] if labels is not None else None) pl.xlabel(xlabel if xlabel is not None else "") pl.ylabel(ylabel if xlabel is not None else "") if labels is not None: pl.legend() if xscale is not None: pl.xscale(xscale) if yscale is not None: pl.yscale(yscale) if not show: return ax else: pl.show()
Example #24
Source File: basis_time.py From PyAbel with MIT License | 5 votes |
def plot(directory, xlim, ylim, linex): plt.figure(figsize=(6, 6), frameon=False) plt.xlabel('Image size ($n$, pixels)') plt.xscale('log') plt.xlim(xlim) plt.ylabel('Basis-set generation time (seconds)') plt.yscale('log') plt.ylim(ylim) plt.gca().yaxis.set_major_locator(LogLocator(base=10.0, numticks=12)) plt.grid(which='both', color='#EEEEEE') plt.grid(which='minor', linewidth=0.5) plt.tight_layout(pad=0.1) # quadratic guiding line plt.plot(xlim, ylim[0] * (np.array(xlim) / linex)**2, color='#AAAAAA', ls=':') # its annotation (must be done after all layout for correct rotation) p = plt.gca().transData.transform(np.array([[1, 1**2], [2, 2**2]])) plt.text(linex, ylim[0], '\n (quadratic scaling)', color='#AAAAAA', va='center', linespacing=2, rotation_mode='anchor', rotation=90 - np.degrees(np.arctan2(*(p[1] - p[0])))) # all timings for meth, color, pargs in transforms: try: times = np.loadtxt(directory + '/' + meth + '.dat', unpack=True) except OSError: continue if times.shape[0] < 3: continue n = times[0] t = times[2] * 1e-3 # in ms plt.plot(n, t, 'o-', label=meth, ms=5, color=color) plt.legend() # plt.show()
Example #25
Source File: qbo_plot.py From e3sm_diags with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_panel(n, fig, plot_type, label_size, title, x, y, z=None, plot_colors=None, color_levels=None, color_ticks=None): # x,y,z should be of the form: # dict(axis_range=None, axis_scale=None, data=None, data_label=None, data2=None, data2_label=None, label=None) # Create new figure axis using dimensions from panel (hard coded) ax = fig.add_axes(panel[n]) # Plot either a contourf or line plot if plot_type == 'contourf': if 'data' not in z: raise RuntimeError('Must set z["data"] to use plot_type={}.'.format(plot_type)) p1 = ax.contourf(x['data'], y['data'], z['data'], color_levels, cmap=plot_colors) cbar = plt.colorbar(p1, ticks=color_ticks) cbar.ax.tick_params(labelsize=label_size) if plot_type == 'line': if 'data2' not in x or 'data2' not in y: raise RuntimeError('Must set data2 for both x and y to use plot_type={}.'.format(plot_type)) elif 'data_label' not in x or 'data2_label' not in x: raise RuntimeError('Must set data_label and data2_label for x to use plot_type={}.'.format(plot_type)) p1, = ax.plot(x['data'], y['data'], '-ok') p2, = ax.plot(x['data2'], y['data2'], '--or') plt.grid('on') ax.legend((p1, p2), (x['data_label'], x['data2_label']), loc='upper right', fontsize=label_size) ax.set_title(title, size=label_size, weight='demi') ax.set_xlabel(x['label'], size=label_size) ax.set_ylabel(y['label'], size=label_size) plt.yscale(y['axis_scale']) plt.ylim([y['axis_range'][0], y['axis_range'][1]]) plt.yticks(size=label_size) plt.xscale(x['axis_scale']) plt.xlim([x['axis_range'][0], x['axis_range'][1]]) plt.xticks(size=label_size) return ax
Example #26
Source File: empirical.py From pyprob with BSD 2-Clause "Simplified" License | 5 votes |
def plot_histogram(self, figsize=(10, 5), xlabel=None, ylabel='Frequency', xticks=None, yticks=None, log_xscale=False, log_yscale=False, file_name=None, show=True, density=1, fig=None, *args, **kwargs): if fig is None: if not show: mpl.rcParams['axes.unicode_minus'] = False plt.switch_backend('agg') fig = plt.figure(figsize=figsize) fig.tight_layout() values = self.values_numpy() weights = self.weights_numpy() plt.hist(values, weights=weights, density=density, *args, **kwargs) if log_xscale: plt.xscale('log') if log_yscale: plt.yscale('log', nonposy='clip') if xticks is not None: plt.xticks(xticks) if yticks is not None: plt.xticks(yticks) if xlabel is None: xlabel = self.name plt.xlabel(xlabel) plt.ylabel(ylabel) if file_name is not None: plt.savefig(file_name) if show: plt.show()
Example #27
Source File: data_process.py From Deep-Reinforcement-Learning-in-Large-Discrete-Action-Spaces with MIT License | 5 votes |
def plot_rewards(self): rewards = self.get_full_episode_rewards() # print(rewards) episodes = len(rewards) batch_size = int(episodes * .01) plt.subplot(211) total_avg = average_timeline(rewards) plt.plot(total_avg, 'm', label='total avg: {}'.format(total_avg[len(total_avg) - 1])) avg = apply_func_to_window(rewards, batch_size, np.average) plt.plot(avg, 'g', label='batch avg') maxima = apply_func_to_window(rewards, batch_size, np.max) plt.plot(maxima, 'r', linewidth=1, label='max') minima = apply_func_to_window(rewards, batch_size, np.min) plt.plot(minima, 'b', linewidth=1, label='min') plt.ylabel("Reward") plt.xlabel("Episode") plt.legend() plt.grid(True) plt.subplot(212) hist = plt.hist(rewards, facecolor='g', alpha=0.75, rwidth=0.8) max_values = int(hist[0][len(hist[0]) - 1]) x_max_values = int(hist[1][len(hist[0]) - 1]) plt.annotate(str(max_values), xy=(x_max_values, int(max_values * 1.1))) plt.ylabel("Distribution") plt.xlabel("Value") plt.yscale("log") plt.grid(True) plt.show()
Example #28
Source File: plot_benchmarks_samplesloss_3D.py From geomloss with MIT License | 5 votes |
def full_bench(Loss) : """Benchmarks the varied backends of a geometric loss function.""" print("Benchmarking : {} ===============================".format(Loss.loss)) lines = [ NS ] backends = ["tensorized", "online", "multiscale"] for backend in backends : Loss.backend = backend lines.append( bench_config(Loss, "cuda" if use_cuda else "cpu") ) benches = np.array(lines).T # Creates a pyplot figure: plt.figure() linestyles = ["o-", "s-", "^-"] for i, backend in enumerate(backends): plt.plot( benches[:,0], benches[:,i+1], linestyles[i], linewidth=2, label='backend="{}"'.format(backend) ) plt.title('Runtime for SamplesLoss("{}") in dimension {}'.format(Loss.loss, D)) plt.xlabel('Number of samples per measure') plt.ylabel('Seconds') plt.yscale('log') ; plt.xscale('log') plt.legend(loc='upper left') plt.grid(True, which="major", linestyle="-") plt.grid(True, which="minor", linestyle="dotted") plt.axis([ NS[0], NS[-1], 1e-3, MAXTIME ]) plt.tight_layout() # Save as a .csv to put a nice Tikz figure in the papers: header = "Npoints " + " ".join(backends) np.savetxt("output/benchmark_"+Loss.loss+"_3D.csv", benches, fmt='%-9.5f', header=header, comments='') ############################################## # Gaussian MMD, with a small blur # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
Example #29
Source File: test_axes.py From ImageFusion with MIT License | 5 votes |
def test_hexbin_log(): # Issue #1636 fig = plt.figure() np.random.seed(0) n = 100000 x = np.random.standard_normal(n) y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) y = np.power(2, y * 0.5) ax = fig.add_subplot(111) ax.hexbin(x, y, yscale='log')
Example #30
Source File: char_frequency_check.py From text_renderer with MIT License | 5 votes |
def show_plot(log=False): if log: plt.yscale('log', nonposy='clip') plt.ylabel('Count') plt.legend() plt.show()