Python matplotlib.pyplot.axvline() Examples
The following are 30
code examples of matplotlib.pyplot.axvline().
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: loop.py From SampleScanner with MIT License | 6 votes |
def process(aif, sample_rate=48000): file = read_wave_file(aif) # loop_start, loop_size = window_match(file) # loop_start, loop_size = zero_crossing_match(file) loop_start, loop_end = find_loop_points(file) loop_size = loop_end - loop_start file = file[0] print 'start, end', loop_start, loop_end plt.plot(file[loop_start:loop_end]) plt.plot(file[loop_end:loop_start + (2 * loop_size)]) plt.show() plt.plot(file[ loop_start - (sample_rate * 2): loop_start + (sample_rate * 2) ]) plt.axvline(sample_rate * 2) plt.axvline((sample_rate * 2) + loop_size) plt.show()
Example #2
Source File: clustering.py From malss with MIT License | 6 votes |
def plot_davies(cls, algorithm, dname): if dname is None: return if not os.path.exists(dname): os.mkdir(dname) plt.figure() plt.title(algorithm.estimator.__class__.__name__) plt.xlabel("Number of clusters") plt.ylabel("Davies-Bouldin score") plt.plot(range(algorithm.results['min_nc'], algorithm.results['max_nc'] + 1), algorithm.results['davies'], 'o-', color='limegreen') plt.axvline(x=algorithm.results['davies_nc'], ls='--', C='gray', zorder=0) plt.savefig('%s/davies_%s.png' % (dname, algorithm.estimator.__class__.__name__), bbox_inches='tight', dpi=75) plt.close()
Example #3
Source File: clustering.py From malss with MIT License | 6 votes |
def plot_calinski(cls, algorithm, dname): if dname is None: return if not os.path.exists(dname): os.mkdir(dname) plt.figure() plt.title(algorithm.estimator.__class__.__name__) plt.xlabel("Number of clusters") plt.ylabel("Calinski and Harabasz score") plt.plot(range(algorithm.results['min_nc'], algorithm.results['max_nc'] + 1), algorithm.results['calinski'], 'o-', color='crimson') plt.axvline(x=algorithm.results['calinski_nc'], ls='--', C='gray', zorder=0) plt.savefig('%s/calinski_%s.png' % (dname, algorithm.estimator.__class__.__name__), bbox_inches='tight', dpi=75) plt.close()
Example #4
Source File: clustering.py From malss with MIT License | 6 votes |
def plot_gap(cls, algorithm, dname): if dname is None: return if not os.path.exists(dname): os.mkdir(dname) plt.figure() plt.title(algorithm.estimator.__class__.__name__) plt.xlabel("Number of clusters") plt.ylabel("Gap statistic") plt.plot(range(algorithm.results['min_nc'], algorithm.results['max_nc'] + 1), algorithm.results['gap'], 'o-', color='dodgerblue') plt.errorbar(range(algorithm.results['min_nc'], algorithm.results['max_nc'] + 1), algorithm.results['gap'], algorithm.results['gap_sk'], capsize=3) plt.axvline(x=algorithm.results['gap_nc'], ls='--', C='gray', zorder=0) plt.savefig('%s/gap_%s.png' % (dname, algorithm.estimator.__class__.__name__), bbox_inches='tight', dpi=75) plt.close()
Example #5
Source File: plotting.py From privacy with Apache License 2.0 | 6 votes |
def plot_histograms(train: Iterable[float], test: Iterable[float], xlabel: Text = 'x', thresh: float = None) -> plt.Figure: """Plot histograms of training versus test metrics.""" xmin = min(np.min(train), np.min(test)) xmax = max(np.max(train), np.max(test)) bins = np.linspace(xmin, xmax, 100) fig = plt.figure() plt.hist(test, bins=bins, density=True, alpha=0.5, label='test', log='y') plt.hist(train, bins=bins, density=True, alpha=0.5, label='train', log='y') if thresh is not None: plt.axvline(thresh, c='r', label=f'threshold = {thresh:.3f}') plt.xlabel(xlabel) plt.ylabel('normalized counts (density)') plt.legend() return fig
Example #6
Source File: Agent.py From Deep-RL-agents with MIT License | 6 votes |
def predict_action(self, s, plot_distrib): if plot_distrib: action, distrib, value = self.sess.run([self.network.actions, self.network.Q_distrib_suggested_actions, self.network.Q_values_suggested_actions], feed_dict={self.network.state_ph: s[None]}) action, distrib, value = action[0], distrib[0], value[0] fig = plt.figure(2) fig.clf() plt.bar(self.z, distrib, self.delta_z) plt.axvline(value, color='red', linewidth=0.7) plt.show(block=False) plt.pause(0.001) return action return self.sess.run(self.network.actions, feed_dict={self.network.state_ph: s[None]})[0]
Example #7
Source File: clustering.py From malss with MIT License | 6 votes |
def plot_silhouette(cls, algorithm, dname): if dname is None: return if not os.path.exists(dname): os.mkdir(dname) plt.figure() plt.title(algorithm.estimator.__class__.__name__) plt.xlabel("Number of clusters") plt.ylabel("Silhouette score") plt.plot(range(algorithm.results['min_nc'], algorithm.results['max_nc'] + 1), algorithm.results['silhouette'], 'o-', color='darkorange') plt.axvline(x=algorithm.results['silhouette_nc'], ls='--', C='gray', zorder=0) plt.savefig('%s/silhouette_%s.png' % (dname, algorithm.estimator.__class__.__name__), bbox_inches='tight', dpi=75) plt.close()
Example #8
Source File: Agent.py From Deep-RL-agents with MIT License | 6 votes |
def predict_action(self, s, plot_distrib): if plot_distrib: action, distrib, value = self.sess.run([self.network.actions, self.network.Q_distrib_suggested_actions, self.network.Q_values_suggested_actions], feed_dict={self.network.state_ph: s[None]}) action, distrib, value = action[0], distrib[0], value[0] fig = plt.figure(2) fig.clf() plt.bar(self.z, distrib, self.delta_z) plt.axvline(value, color='red', linewidth=0.7) plt.show(block=False) plt.pause(0.001) return action return self.sess.run(self.network.actions, feed_dict={self.network.state_ph: s[None]})[0]
Example #9
Source File: run_visual.py From time-series-machine-learning with Apache License 2.0 | 6 votes |
def main(): train_date = None tickers, periods, targets = parse_command_line(default_tickers=['BTC_ETH', 'BTC_LTC'], default_periods=['day'], default_targets=['high']) for ticker in tickers: for period in periods: for target in targets: job = JobInfo('_data', '_zoo', name='%s_%s' % (ticker, period), target=target) result_df = predict_multiple(job, raw_df=read_df(job.get_source_name()), rows_to_predict=120) result_df.index.names = [''] result_df.plot(title=job.name) if train_date is not None: x = train_date y = result_df['True'].min() plt.axvline(x, color='k', linestyle='--') plt.annotate('Training stop', xy=(x, y), xytext=(result_df.index.min(), y), color='k', arrowprops={'arrowstyle': '->', 'connectionstyle': 'arc3', 'color': 'k'}) plt.show()
Example #10
Source File: example1d.py From pyGPGO with MIT License | 6 votes |
def plotGPGO(gpgo, param): param_value = list(param.values())[0][1] x_test = np.linspace(param_value[0], param_value[1], 1000).reshape((1000, 1)) hat = gpgo.GP.predict(x_test, return_std=True) y_hat, y_std = hat[0], np.sqrt(hat[1]) l, u = y_hat - 1.96 * y_std, y_hat + 1.96 * y_std fig = plt.figure() r = fig.add_subplot(2, 1, 1) r.set_title('Fitted Gaussian process') plt.fill_between(x_test.flatten(), l, u, alpha=0.2) plt.plot(x_test.flatten(), y_hat, color='red', label='Posterior mean') plt.legend(loc=0) a = np.array([-gpgo._acqWrapper(np.atleast_1d(x)) for x in x_test]).flatten() r = fig.add_subplot(2, 1, 2) r.set_title('Acquisition function') plt.plot(x_test, a, color='green') gpgo._optimizeAcq(method='L-BFGS-B', n_start=1000) plt.axvline(x=gpgo.best, color='black', label='Found optima') plt.legend(loc=0) plt.tight_layout() plt.savefig(os.path.join(os.getcwd(), 'mthesis_text/figures/chapter3/sine/{}.pdf'.format(i))) plt.show()
Example #11
Source File: validation_plots.py From TheCannon with MIT License | 6 votes |
def chisq_dist(): fig = plt.figure(figsize=(6,4)) ivar = np.load("%s/val_ivar_norm.npz" %DATA_DIR)['arr_0'] npix = np.sum(ivar>0, axis=1) chisq = np.load("%s/val_chisq.npz" %DATA_DIR)['arr_0'] redchisq = chisq/npix nbins = 25 plt.hist(redchisq, bins=nbins, color='k', histtype="step", lw=2, normed=False, alpha=0.3, range=(0,3)) plt.legend() plt.xlabel("Reduced $\chi^2$", fontsize=16) plt.tick_params(axis='both', labelsize=16) plt.ylabel("Count", fontsize=16) plt.axvline(x=1.0, linestyle='--', c='k') fig.tight_layout() #plt.show() plt.savefig("chisq_dist.png")
Example #12
Source File: acqzoo.py From pyGPGO with MIT License | 6 votes |
def plotGPGO(gpgo, param, index, new=True): param_value = list(param.values())[0][1] x_test = np.linspace(param_value[0], param_value[1], 1000).reshape((1000, 1)) y_hat, y_var = gpgo.GP.predict(x_test, return_std=True) std = np.sqrt(y_var) l, u = y_hat - 1.96 * std, y_hat + 1.96 * std if new: plt.figure() plt.subplot(5, 1, 1) plt.fill_between(x_test.flatten(), l, u, alpha=0.2) plt.plot(x_test.flatten(), y_hat) plt.subplot(5, 1, index) a = np.array([-gpgo._acqWrapper(np.atleast_1d(x)) for x in x_test]).flatten() plt.plot(x_test, a, color=colors[index - 2], label=acq_titles[index - 2]) gpgo._optimizeAcq(method='L-BFGS-B', n_start=1000) plt.axvline(x=gpgo.best) plt.legend(loc=0)
Example #13
Source File: hicCompartmentalization.py From HiCExplorer with GNU General Public License v3.0 | 6 votes |
def plot_polarization_ratio(polarization_ratio, plotName, labels, number_of_quantiles): """ Generate a plot to visualize the polarization ratio between A and B compartments. It presents how well 2 compartments are seperated. """ for i, r in enumerate(polarization_ratio): plt.plot(r, marker="o", label=labels[i]) plt.axhline(1, c='grey', ls='--', lw=1) plt.axvline(number_of_quantiles / 2, c='grey', ls='--', lw=1) plt.legend(loc='best') plt.xlabel('Quantiles') plt.ylabel('signal within comp. / signla between comp.') plt.title('compartment polarization ratio') plt.savefig(plotName)
Example #14
Source File: memory_cpu_profile.py From mlens with MIT License | 6 votes |
def plot_rss(cm, t1, t2, t3): """Plot the memory profile.""" f = plt.figure(figsize=(8, 6)) plt.plot(range(cm.cpu.shape[0]), cm.rss / 1000000) plt.axvline(t1 - 3, color='darkcyan', linestyle='--', linewidth=1.0, label='load data') plt.axvline(t2, color='blue', linestyle='--', linewidth=1.0, label='fit start') plt.axvline(t3, color='blue', linestyle='-.', linewidth=1.0, label='fit end') plt.xticks([i for i in [0, 50, 100, 150, 200, 250]], [i for i in [0, 5, 10, 15, 20, 25]]) # plt.ylim(120, 240) plt.title("ML-Ensemble memory profile (working set)") plt.ylabel("Working set memory (MB)") plt.xlabel("Time (s)") plt.legend() plt.show() if PRINT: try: f.savefig("dev/img/memory_profile.png", dpi=600) except: f.savefig("memory_profile.png", dpi=600)
Example #15
Source File: memory_cpu_profile.py From mlens with MIT License | 6 votes |
def plot_cpu(cm, t1, t2, t3): """Plot the CPU profile.""" f = plt.figure() plt.plot(range(cm.cpu.shape[0]), cm.cpu) plt.axvline(t1 - 3, color='darkcyan', linestyle='--', linewidth=1.0, label='load data') plt.axvline(t2, color='blue', linestyle='--', linewidth=1.0, label='fit start') plt.axvline(t3, color='blue', linestyle='-.', linewidth=1.0, label='fit end') plt.xticks([i for i in [0, 50, 100, 150, 200, 250]], [i for i in [0, 5, 10, 15, 20, 25]]) plt.title("ML-Ensemble CPU profile") plt.ylabel("CPU utilization (%)") plt.xlabel("Time (s)") plt.legend() if PRINT: try: f.savefig("dev/cpu_profile.png", dpi=600) except: f.savefig("cpu_profile.png", dpi=600)
Example #16
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 #17
Source File: measures.py From nolds with MIT License | 6 votes |
def plot_histogram_matrix(data, name, fname=None): # local import to avoid dependency for non-debug use import matplotlib.pyplot as plt nhists = len(data[0]) nbins = 25 ylim = (0, 0.5) nrows = int(np.ceil(np.sqrt(nhists))) plt.figure(figsize=(nrows * 4, nrows * 4)) for i in range(nhists): plt.subplot(nrows, nrows, i + 1) absmax = max(abs(np.max(data[:, i])), abs(np.min(data[:, i]))) rng = (-absmax, absmax) h, bins = np.histogram(data[:, i], nbins, rng) bin_width = bins[1] - bins[0] h = h.astype("float32") / np.sum(h) plt.bar(bins[:-1], h, bin_width) plt.axvline(np.mean(data[:, i]), color="red") plt.ylim(ylim) plt.title("{:s}[{:d}]".format(name, i)) if fname is None: plt.show() else: plt.savefig(fname) plt.close()
Example #18
Source File: m_dos_pdos_eigenvalues.py From pyscf with Apache License 2.0 | 6 votes |
def dosplot (filename = None, data = None, fermi = None): if (filename is not None): data = np.loadtxt(filename) elif (data is not None): data = data import matplotlib.pyplot as plt from matplotlib import rc plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.plot(data.T[0], data.T[1], label='MF Spin-UP', linestyle=':',color='r') plt.fill_between(data.T[0], 0, data.T[1], facecolor='r',alpha=0.1, interpolate=True) plt.plot(data.T[0], data.T[2], label='QP Spin-UP',color='r') plt.fill_between(data.T[0], 0, data.T[2], facecolor='r',alpha=0.5, interpolate=True) plt.plot(data.T[0],-data.T[3], label='MF Spin-DN', linestyle=':',color='b') plt.fill_between(data.T[0], 0, -data.T[3], facecolor='b',alpha=0.1, interpolate=True) plt.plot(data.T[0],-data.T[4], label='QP Spin-DN',color='b') plt.fill_between(data.T[0], 0, -data.T[4], facecolor='b',alpha=0.5, interpolate=True) if (fermi!=None): plt.axvline(x=fermi ,color='k', linestyle='--') #label='Fermi Energy' plt.axhline(y=0,color='k') plt.title('Total DOS', fontsize=20) plt.xlabel('Energy (eV)', fontsize=15) plt.ylabel('Density of States (electron/eV)', fontsize=15) plt.legend() plt.savefig("dos_eigen.svg", dpi=900) plt.show()
Example #19
Source File: electronic.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_fermi_dirac(self): """ Plots the obtained eigenvalue vs occupation plot """ try: import matplotlib.pylab as plt except ModuleNotFoundError: import matplotlib.pyplot as plt arg = np.argsort(self.eigenvalues) plt.plot( self.eigenvalues[arg], self.occupancies[arg], linewidth=2.0, color="blue" ) plt.axvline(self.efermi, linewidth=2.0, linestyle="dashed", color="black") plt.xlabel("Energies (eV)") plt.ylabel("Occupancy") return plt
Example #20
Source File: correlation_analysis.py From copper_price_forecast with GNU General Public License v3.0 | 6 votes |
def data_visualization(co_price, pcb_price): """ 原始数据可视化 """ x_co_values = co_price.index y_co_values = co_price.price / 100 x_pcb_values = pcb_price.index y_pcb_values = pcb_price.price plt.figure(figsize=(10, 6)) plt.title('copper price(100rmb/t) vs. pcb price(rmb/sq.m.)') plt.xlabel('date') plt.ylabel('history price') plt.plot(x_co_values, y_co_values, '-', label='co price') plt.plot(x_pcb_values, y_pcb_values, '-', label='pcb price') plt.axvline('2015-04-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2015-10-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2016-04-23', linewidth=1, color='r', linestyle='dashed') plt.axvline('2016-10-23', linewidth=1, color='r', linestyle='dashed') plt.legend(loc='upper right') plt.show()
Example #21
Source File: report.py From wub with Mozilla Public License 2.0 | 5 votes |
def plot_histograms(self, data_map, title="", xlab="", ylab="", bins=50, alpha=0.7, legend_loc='best', legend=True, vlines=None): """Plot histograms of multiple data arrays. :param self: object. :param data_map: A dictionary with labels as keys and data arrays as values. :param title: Figure title. :param xlab: X axis label. :param ylab: Y axis label. :param bins: Number of bins. :param alpha: Transparency value for histograms. :param legend_loc: Location of legend. :param legend: Plot legend if True. :param vlines: Dictionary with labels and positions of vertical lines to draw. :returns: None :rtype: object """ fig = plt.figure() for label, data in six.iteritems(data_map): if len(data) > 0: plt.hist(data, bins=bins, label=label, alpha=alpha) if vlines is not None: for label, pos in six.iteritems(vlines): plt.axvline(x=pos, label=label) if legend: plt.legend(loc=legend_loc) self._set_properties_and_close(fig, title, xlab, ylab)
Example #22
Source File: plot_tools.py From neuronaldynamics-exercises with GNU General Public License v2.0 | 5 votes |
def plot_population_activity_power_spectrum(freq, ps, max_freq, average_At=None, plot_f0=False): """ Plots the power spectrum of the population activity A(t) Args: freq: frequencies (= x axis) ps: power spectrum of the population activity max_freq (Quantity): The data is plotted in the interval [-.05*max_freq, max_freq] plot_f0 (bool): if true, the power at frequency 0 is plotted. Default is False and the value is not plotted. Returns: the figure """ first_idx_to_plot = 0 if plot_f0 else 1 f = plt.figure() plt.plot(freq[first_idx_to_plot:], ps[first_idx_to_plot:], ".b") plt.axvline(x=0., lw=1, color="k") plt.xlim([-.05*max_freq/b2.Hz, max_freq/b2.Hz]) plt.grid() plt.xlabel("Frequency [Hz]") plt.ylabel("Power") if average_At is None: plt.title("Power Spectrum of population activity A(t).") else: plt.title("Power Spectrum of population activity A(t). Avg. rate = {}".format(round(average_At, 1))) return f
Example #23
Source File: analyser.py From spotpy with MIT License | 5 votes |
def plot_objectivefunction(results,evaluation,limit=None,sort=True, fig_name = 'objective_function.png'): """Example Plot as seen in the SPOTPY Documentation""" import matplotlib.pyplot as plt likes=calc_like(results,evaluation,spotpy.objectivefunctions.rmse) data=likes #Calc confidence Interval mean = np.average(data) # evaluate sample variance by setting delta degrees of freedom (ddof) to # 1. The degree used in calculations is N - ddof stddev = np.std(data, ddof=1) from scipy.stats import t # Get the endpoints of the range that contains 95% of the distribution t_bounds = t.interval(0.999, len(data) - 1) # sum mean to the confidence interval ci = [mean + critval * stddev / np.sqrt(len(data)) for critval in t_bounds] value="Mean: %f" % mean print(value) value="Confidence Interval 95%%: %f, %f" % (ci[0], ci[1]) print(value) threshold=ci[1] happend=None bestlike=[data[0]] for like in data: if like<bestlike[-1]: bestlike.append(like) if bestlike[-1]<threshold and not happend: thresholdpos=len(bestlike) happend=True else: bestlike.append(bestlike[-1]) if limit: plt.plot(bestlike,'k-')#[0:limit]) plt.axvline(x=thresholdpos,color='r') plt.plot(likes,'b-') #plt.ylim(ymin=-1,ymax=1.39) else: plt.plot(bestlike) plt.savefig(fig_name)
Example #24
Source File: plot_early_classification.py From tslearn with BSD 2-Clause "Simplified" License | 5 votes |
def plot_partial(time_series, t, y_true=0, y_pred=0, color="k"): plt.plot(time_series[:t+1].ravel(), color=color, linewidth=1.5) plt.plot(numpy.arange(t+1, time_series.shape[0]), time_series[t+1:].ravel(), linestyle="dashed", color=color, linewidth=1.5) plt.axvline(x=t, color=color, linewidth=1.5) plt.text(x=t - 20, y=time_series.max() - .25, s="Prediction time") plt.title( "Sample of class {} predicted as class {}".format(y_true, y_pred) ) plt.xlim(0, time_series.shape[0] - 1) ############################################################################## # Data loading and visualization # ------------------------------
Example #25
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 5 votes |
def _fitted_E_plot(d, i=0, F=1, no_E=False, ax=None, show_model=True, verbose=False, two_gauss_model=False, lw=2.5, color='k', alpha=0.5, fillcolor=None): """Plot a fitted model overlay on a FRET histogram.""" if ax is None: ax2 = gca() else: ax2 = plt.twinx(ax=ax) ax2.grid(False) if d.fit_E_curve and show_model: x = r_[-0.2:1.21:0.002] y = d.fit_E_model(x, d.fit_E_res[i, :]) scale = F*d.fit_E_model_F[i] if two_gauss_model: assert d.fit_E_res.shape[1] > 2 if d.fit_E_res.shape[1] == 5: m1, s1, m2, s2, a1 = d.fit_E_res[i, :] a2 = (1-a1) elif d.fit_E_res.shape[1] == 6: m1, s1, a1, m2, s2, a2 = d.fit_E_res[i, :] y1 = a1*normpdf(x, m1, s1) y2 = a2*normpdf(x, m2, s2) ax2.plot(x, scale*y1, ls='--', lw=lw, alpha=alpha, color=color) ax2.plot(x, scale*y2, ls='--', lw=lw, alpha=alpha, color=color) if fillcolor is None: ax2.plot(x, scale*y, lw=lw, alpha=alpha, color=color) else: ax2.fill_between(x, scale*y, lw=lw, alpha=alpha, edgecolor=color, facecolor=fillcolor, zorder=10) if verbose: print('Fit Integral:', np.trapz(scale*y, x)) ax2.axvline(d.E_fit[i], lw=3, color=red, ls='--', alpha=0.6) xtext = 0.6 if d.E_fit[i] < 0.6 else 0.2 if d.nch > 1 and not no_E: ax2.text(xtext, 0.81, "CH%d: $E_{fit} = %.3f$" % (i+1, d.E_fit[i]), transform=gca().transAxes, fontsize=16, bbox=dict(boxstyle='round', facecolor='#dedede', alpha=0.5))
Example #26
Source File: utils.py From generative-graph-transformer with MIT License | 5 votes |
def plot_histogram_streetmover(x, args): r""" Plot histogram of streetmover distance, to better analyze the performance of different models :param x: streetmover distances :param args: parsed arguments """ sns.set(color_codes=True, style="white") sns_plot = sns.distplot(x, bins=int(np.max(x) / 0.002), kde=False) # kde_kws=dict(bw=0.01)) sns_plot.set_xticks(np.linspace(0, 0.08, 5)) sns_plot.set_yticks(np.linspace(0, 10000, 6)) sns_plot.set_xlim(0, 0.09) sns_plot.set_ylim(0, 10000) plt.grid(which='major', axis='y', color='gray', linestyle='-', linewidth=1, alpha=.5) mean = np.mean(x) median = np.median(x) std = np.std(x) plt.axvline(mean, 0, 40, ls='--', c='r', label="mean") plt.axvline(median, 0, 40, ls='--', c='g', label="median") plt.text(0.088, 4000, f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20, fontdict=dict(horizontalalignment='right')) sns_plot.set_ylabel("N datapoints", fontsize=20) sns_plot.set_xlabel("StreetMover distance", fontsize=20) sns.despine(ax=sns_plot, left=True, bottom=True) # sns_plot.set_title(f"Mean: {str(mean)[:6]}\nMedian: {str(median)[:6]}\nStd: {str(std)[:6]}", fontsize=20, # fontdict=dict(horizontalalignment='right')) sns_plot.legend(prop={'size': 20}) sns_plot.figure.savefig(f"{args.statistics_path}/{args.file_name}.png", bbox_inches='tight')
Example #27
Source File: circuit.py From qkit with GNU General Public License v2.0 | 5 votes |
def plotall(self): if not plot_enable: raise ImportError("matplotlib not found") real = self.z_data_raw.real imag = self.z_data_raw.imag real2 = self.z_data_sim.real imag2 = self.z_data_sim.imag plt.subplot(221, aspect="equal") plt.axvline(0, c="k", ls="--", lw=1) plt.axhline(0, c="k", ls="--", lw=1) plt.plot(real,imag,label='rawdata') plt.plot(real2,imag2,label='fit') plt.xlabel('Re(S21)') plt.ylabel('Im(S21)') plt.legend() plt.subplot(222) plt.plot(self.f_data*1e-9,np.absolute(self.z_data_raw),label='rawdata') plt.plot(self.f_data*1e-9,np.absolute(self.z_data_sim),label='fit') plt.xlabel('f (GHz)') plt.ylabel('|S21|') plt.legend() plt.subplot(223) plt.plot(self.f_data*1e-9,np.angle(self.z_data_raw),label='rawdata') plt.plot(self.f_data*1e-9,np.angle(self.z_data_sim),label='fit') plt.xlabel('f (GHz)') plt.ylabel('arg(|S21|)') plt.legend() plt.show()
Example #28
Source File: plot_analysed_telemetry.py From SpaceXtract with MIT License | 5 votes |
def add_lines(events, y, rotation=-90): for key in events: if events[key] is not None: plt.text(int(events[key]), y, events_to_text[key], fontsize=15, rotation=rotation) plt.axvline(x=int(events[key]), color='black', linestyle='--')
Example #29
Source File: confidence_analyzer.py From assistant-dialog-skill-analysis with Apache License 2.0 | 5 votes |
def create_threshold_graph(data): """ display threshold analysis graph :param data: :return: None """ sns.set(rc={"figure.figsize": (20.7, 10.27)}) plt.ylim(0, 1.1) plt.axvline(0.2, 0, 1) plot = sns.lineplot(data=data, palette="tab10", linewidth=3.5) plt.setp(plot.legend().get_texts(), fontsize="22") plot.set_xlabel("Threshold T", fontsize=18) plot.set_ylabel("Metrics mentioned above", fontsize=18)
Example #30
Source File: backtest.py From bt with MIT License | 5 votes |
def plot_histogram(self, statistic='monthly_sharpe', figsize=(15, 5), title=None, bins=20, **kwargs): """ Plots the distribution of a given statistic. The histogram represents the distribution of the random strategies' statistic and the vertical line is the value of the benchmarked strategy's statistic. This helps you determine if your strategy is statistically 'better' than the random versions. Args: * statistic (str): Statistic - any numeric statistic in Result is valid. * figsize ((x, y)): Figure size * title (str): Chart title * bins (int): Number of bins * kwargs (dict): Passed to pandas hist function. """ if statistic not in self.r_stats.index: raise ValueError("Invalid statistic. Valid statistics" "are the statistics in self.stats") if title is None: title = '%s histogram' % statistic plt.figure(figsize=figsize) ser = self.r_stats.loc[statistic] ax = ser.hist(bins=bins, figsize=figsize, density=True, **kwargs) ax.set_title(title) plt.axvline(self.b_stats[statistic], linewidth=4, color = 'r') ser.plot(kind='kde')