Python matplotlib.pyplot.fill_between() Examples
The following are 30
code examples of matplotlib.pyplot.fill_between().
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: main.py From DDLO with MIT License | 6 votes |
def plot_gain(gain_his,name=None): #display data import matplotlib.pyplot as plt import pandas as pd import matplotlib as mpl gain_array = np.asarray(gain_his) df = pd.DataFrame(gain_his) mpl.style.use('seaborn') fig, ax = plt.subplots(figsize=(15,8)) rolling_intv = 60 df_roll=df.rolling(rolling_intv, min_periods=1).mean() if name != None: sio.savemat('./data/MUMT(%s)'%name,{'ratio':gain_his}) plt.plot(np.arange(len(gain_array))+1, df_roll, 'b') plt.fill_between(np.arange(len(gain_array))+1, df.rolling(rolling_intv, min_periods=1).min()[0], df.rolling(rolling_intv, min_periods=1).max()[0], color = 'b', alpha = 0.2) plt.ylabel('Gain ratio') plt.xlabel('learning steps') plt.show()
Example #2
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 #3
Source File: plot_3.py From cs294-112_hws with MIT License | 6 votes |
def plot_3(data): x = data.Iteration.unique() y_mean = data.groupby('Iteration').mean() y_std = data.groupby('Iteration').std() sns.set(style="darkgrid", font_scale=1.5) value = 'AverageReturn' plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_train'); plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2); value = 'ValAverageReturn' plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_test'); plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2); plt.xlabel('Iteration') plt.ylabel('AverageReturn') plt.legend(loc='best')
Example #4
Source File: viz.py From form2fit with MIT License | 6 votes |
def plot_loss(arr, window=50, figsize=(20, 10), name=None): def _rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) arr = np.asarray(arr) fig, ax = plt.subplots(figsize=figsize) rolling_mean = np.mean(_rolling_window(arr, 50), 1) rolling_std = np.std(_rolling_window(arr, 50), 1) plt.plot(range(len(rolling_mean)), rolling_mean, alpha=0.98, linewidth=0.9) plt.fill_between( range(len(rolling_std)), rolling_mean - rolling_std, rolling_mean + rolling_std, alpha=0.5, ) plt.grid() plt.xlabel("Iteration #") plt.ylabel("Loss") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show()
Example #5
Source File: viz_midpoint.py From python_primer with MIT License | 6 votes |
def viz_rect(f, a, b, n, N): h = (b - a) / float(n) data = [] for i in range(1, n + 1): for j in range(50): data.append(f(a + (i - 0.5) * h)) x = np.linspace(a, b, n * N) plt.plot(x, f(x), linewidth=2, color=colorset[-1]) plt.plot(x, data, color=colorset[-2], linestyle='--') for i in range(n): plt.plot([h * i, h * i], [0, data[i * N]], color=colorset[-2], linestyle='--') plt.fill_between(x, f(x), data, color=colorset[1]) plt.xlabel('x') plt.ylabel('f(x)') plt.title('%g segments' % n) plt.show()
Example #6
Source File: viz_trapezoidal.py From python_primer with MIT License | 6 votes |
def viz_trap(f, a, b, n, N): h = (b - a) / float(n) midpoints = [] for i in range(n + 1): midpoints.append(f(a + (i * h))) print midpoints data = np.zeros(n * N) for i in range(n): data[i * N:(i + 1) * N] = np.linspace(midpoints[i], midpoints[i + 1], N) x = np.linspace(a, b, n * N) plt.plot(x, f(x), linewidth=2, color=colorset[-1]) plt.plot(x, data, color=colorset[-2], linestyle='--') for i in range(n): plt.plot([h * i, h * i], [0, data[i * N]], color=colorset[-2], linestyle='--') plt.fill_between(x, f(x), data, color=colorset[1]) plt.xlabel('x') plt.ylabel('f(x)') plt.title('%g segments' % n) plt.show()
Example #7
Source File: spike_test_logs_graph_builder.py From indy-node with Apache License 2.0 | 6 votes |
def add_graph(values, color): load_coefficient = 0 time_ax = [] load_ax = [] spike_length = get_spike_length(values) initial_rate = values[0][2] for i in range(0, len(values)): if i % spike_length == 0: load_coefficient = 0 time_ax.extend([values[i][0], values[i][0]]) load_ax.extend([0, initial_rate]) else: time_ax.extend([values[i][0], values[i][0]]) load_ax.append(initial_rate + values[i][2] * load_coefficient) load_coefficient += 1 load_ax.append(initial_rate + values[i][2] * load_coefficient) if (i + 1) % spike_length == 0: time_ax.extend([values[i][1], values[i][1]]) load_ax.extend([initial_rate + values[i][2] * load_coefficient, 0]) plt.fill_between(time_ax, load_ax, facecolor=color, alpha=0.4)
Example #8
Source File: spike_test_logs_graph_builder.py From indy-node with Apache License 2.0 | 6 votes |
def add_bg_graph(values, color): load_coefficient = 0 time_ax = [] load_ax = [] initial_rate = values[0][2] for i in range(0, len(values)): if i == 0: load_coefficient = 0 time_ax.extend([values[i][0], values[i][0]]) load_ax.extend([0, initial_rate]) else: time_ax.extend([values[i][0], values[i][0]]) load_ax.append(initial_rate + values[i][2] * load_coefficient) load_coefficient += 1 load_ax.append(initial_rate + values[i][2] * load_coefficient) if i == len(values) - 1: time_ax.extend([values[i][1], values[i][1]]) load_ax.extend([initial_rate + values[i][2] * load_coefficient, 0]) plt.fill_between(time_ax, load_ax, facecolor=color, alpha=0.4)
Example #9
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 #10
Source File: utils.py From pytorch-hessian-eigenthings with MIT License | 6 votes |
def plot_eigenval_estimates(estimates, label): """ estimates = 2D array (num_trials x num_eigenvalues) x-axis = eigenvalue index y-axis = eigenvalue estimate """ if len(estimates.shape) == 1: var = np.zeros_like(estimates) else: var = np.var(estimates, axis=0) y = np.mean(estimates, axis=0) x = list(range(len(y))) error = np.sqrt(var) plt.plot(x, y, label=label) plt.fill_between(x, y-error, y+error, alpha=.2)
Example #11
Source File: plot_util.py From DeepLearningSmells with Apache License 2.0 | 6 votes |
def save_precision_recall_curve(eval_labels, pred_labels, average_precision, smell, config, out_folder, dim, method): fig = plt.figure() precision, recall, _ = precision_recall_curve(eval_labels, pred_labels) step_kwargs = ({'step': 'post'} if 'step' in signature(plt.fill_between).parameters else {}) plt.step(recall, precision, color='b', alpha=0.2, where='post') plt.fill_between(recall, precision, alpha=0.2, color='b', **step_kwargs) plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) if isinstance(config, cfg.CNN_config): title_str = smell + " (" + method + " - " + dim + ") - L=" + str(config.layers) + ", E=" + str(config.epochs) + ", F=" + str(config.filters) + \ ", K=" + str(config.kernel) + ", PW=" + str(config.pooling_window) + ", AP={0:0.2f}".format(average_precision) # plt.title(title_str) # plt.show() file_name = get_plot_file_name(smell, config, out_folder, dim, method, "_prc_") fig.savefig(file_name)
Example #12
Source File: utils.py From pytorch-hessian-eigenthings with MIT License | 6 votes |
def plot_eigenvec_errors(true, estimates, label): """ plots error for all eigenvector estimates in L2 norm estimates = (num_trials x num_eigenvalues x num_params) true = (num_eigenvalues x num_params) """ diffs = [] num_eigenvals = true.shape[0] for i in range(num_eigenvals): cur_estimates = estimates[:, i, :] cur_eigenvec = true[i] diff = compute_eigenvec_cos_similarity(cur_eigenvec, cur_estimates) diffs.append(diff) diffs = np.array(diffs).T var = np.var(diffs, axis=0) y = np.mean(diffs, axis=0) x = list(range(len(y))) error = np.sqrt(var) plt.plot(x, y, label=label) plt.fill_between(x, y-error, y+error, alpha=.2)
Example #13
Source File: dos.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_total_dos(self, **kwargs): """ Plots the total DOS Args: **kwargs: Variables for matplotlib.pylab.plot customization (linewidth, linestyle, etc.) Returns: matplotlib.pylab.plot """ try: import matplotlib.pylab as plt except ImportError: import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(6, 4)) ax1 = fig.add_subplot(111) ax1.set_xlabel("E (eV)", fontsize=14) ax1.set_ylabel("DOS", fontsize=14) plt.fill_between(self.energies, self.t_dos, **kwargs) return plt
Example #14
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 #15
Source File: utils_squad_evaluate.py From CCF-BDCI-Sentiment-Analysis-Baseline with Apache License 2.0 | 5 votes |
def plot_pr_curve(precisions, recalls, out_image, title): plt.step(recalls, precisions, color='b', alpha=0.2, where='post') plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(title) plt.savefig(out_image) plt.clf()
Example #16
Source File: plotter.py From message-analyser with MIT License | 5 votes |
def lineplot_messages(msgs, your_name, target_name, path_to_save): sns.set(style="whitegrid") (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs) y_your = [len([msg for msg in period if msg.author == your_name]) for period in y_total] y_target = [len([msg for msg in period if msg.author == target_name]) for period in y_total] plt.fill_between(x, y_your, alpha=0.3) ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name) plt.fill_between(x, y_target, alpha=0.3) sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name) ax.set(xlabel=xlabel, ylabel="messages") ax.set_xticklabels(xticks_labels) ax.tick_params(axis='x', bottom=True, color="#A9A9A9") plt.xticks(xticks, rotation=65) ax.margins(x=0, y=0) # plt.tight_layout() fig = plt.gcf() fig.set_size_inches(13, 7) fig.savefig(os.path.join(path_to_save, lineplot_messages.__name__ + ".png"), dpi=500) # plt.show() plt.close("all") log_line(f"{lineplot_messages.__name__} was created.")
Example #17
Source File: evaluations.py From Efficient-GAN-Anomaly-Detection with MIT License | 5 votes |
def do_prc(scores, true_labels, file_name='', directory='', plot=True): """ Does the PRC curve Args : scores (list): list of scores from the decision function true_labels (list): list of labels associated to the scores file_name (str): name of the PRC curve directory (str): directory to save the jpg file plot (bool): plots the PRC curve or not Returns: prc_auc (float): area under the under the PRC curve """ precision, recall, thresholds = precision_recall_curve(true_labels, scores) prc_auc = auc(recall, precision) if plot: plt.figure() plt.step(recall, precision, color='b', alpha=0.2, where='post') plt.fill_between(recall, precision, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision-Recall curve: AUC=%0.4f' %(prc_auc)) if not os.path.exists(directory): os.makedirs(directory) plt.savefig('results/' + file_name + '_prc.jpg') plt.close() return prc_auc
Example #18
Source File: test_rand_feat.py From nispat with GNU General Public License v3.0 | 5 votes |
def plot_dist(x, mean, lb, ub, color_mean=None, color_shading=None): # plot the shaded range of the confidence intervals plt.fill_between(x, ub, lb, color=color_shading, alpha=.5) # plot the mean on top plt.plot(x,mean, color_mean)
Example #19
Source File: mlab.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def offset_line(y, yerr): """ Offsets an array *y* by +/- an error and returns a tuple (y - err, y + err). The error term can be: * A scalar. In this case, the returned tuple is obvious. * A vector of the same length as *y*. The quantities y +/- err are computed component-wise. * A tuple of length 2. In this case, yerr[0] is the error below *y* and yerr[1] is error above *y*. For example:: import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, num=100, endpoint=True) y = np.sin(x) y_minus, y_plus = mlab.offset_line(y, 0.1) plt.plot(x, y) plt.fill_between(x, y_minus, y2=y_plus) plt.show() """ if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and len(yerr) == len(y)): ymin = y - yerr ymax = y + yerr elif len(yerr) == 2: ymin, ymax = y - yerr[0], y + yerr[1] else: raise ValueError("yerr must be scalar, 1xN or 2xN") return ymin, ymax
Example #20
Source File: thinkplot.py From Lie_to_me with MIT License | 5 votes |
def FillBetween(xs, y1, y2=None, where=None, **options): """Fills the space between two lines. Args: xs: sequence of x values y1: sequence of y values y2: sequence of y values where: sequence of boolean options: keyword args passed to plt.fill_between """ options = _UnderrideColor(options) options = _Underride(options, linewidth=0, alpha=0.5) plt.fill_between(xs, y1, y2, where, **options)
Example #21
Source File: grid_search_cv.py From text-classifier with Apache License 2.0 | 5 votes |
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, train_sizes=np.linspace(.1, 1.0, 5), n_jobs=1, figure_path=None): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") plt.savefig(figure_path) return plt
Example #22
Source File: squad_utils.py From embedding-as-service with MIT License | 5 votes |
def plot_pr_curve(precisions, recalls, out_image, title): plt.step(recalls, precisions, color='b', alpha=0.2, where='post') plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(title) plt.savefig(out_image) plt.clf()
Example #23
Source File: kernel.py From RGAN with MIT License | 5 votes |
def compare_y(X, scale, gamma=1): seq_length = X.shape[1] num_signals = X.shape[2] Y = X + np.random.normal(size=(seq_length, num_signals), scale=scale) x = X[0, :, :] y = Y[0, :, :] kxy = my_rbf(x, y, gamma=gamma) print(kxy) plt.plot(x[:, 0], color='blue') plt.plot(x[:, 1], color='green') plt.plot(x[:, 2], color='red') plt.plot(y[:, 0], color='#4286f4') plt.plot(y[:, 1], color='#20cc4b') plt.plot(y[:, 2], color='#ea4b4b') plt.axhline(y=kxy, color='black', linestyle='-', label='kxy') plt.fill_between(plt.xlim(), 0, 1, facecolor='black', alpha=0.15) plt.title('gamma' + str(gamma) + ' scale' + str(scale).zfill(3)) plt.xlim(0, seq_length-1) plt.ylim(-1.01, 1.01) #plt.ylim(4, 4) plt.savefig('sine_gamma' + str(gamma) + '_scale' + str(scale*100).zfill(5) + '.png') plt.clf() plt.close() #for scale in np.concatenate(([5, 1, 0.5, 0.4, 0.3, 0.2, 0.15, 0.1], np.arange(0.09, 0.00, -0.01))): # compare_y(X, scale, 0.1) # compare_y(X, scale, 0.5) # compare_y(X, scale, 1) # compare_y(X, scale, 2)
Example #24
Source File: benchmark.py From perses with MIT License | 5 votes |
def plot_logPs(logps, molecule_name, scheme, component): """ Create line plot of mean and standard deviation of given logPs. Arguments: ---------- logps: dict { int : np.ndarray } key : number of total NCMC steps value : array of `niterations` logP values molecule_name : str The molecule featured in the NullTestSystem being analyzed in ['naphthalene','butane','propane'] scheme : str Which NCMC scheme is being used in ['hybrid','two-stage'] component : str Which logP is being plotted in ['NCMC','EXEN'] """ x = list(logps.keys()) x.sort() y = [logps[steps].mean() for steps in x] dy = [logps[steps].std() for steps in x] plt.fill_between(x, [mean - dev for mean, dev in zip(y, dy)], [mean + dev for mean, dev in zip(y, dy)]) plt.plot(x, y, 'k') plt.xscale('log') plt.title("{0} {1} {2} {3}".format(ENV, molecule_name, scheme, component)) plt.ylabel('logP') plt.xlabel('ncmc steps') plt.tight_layout() plt.savefig('{0}_{1}_{2}{3}_logP'.format(ENV, molecule_name, scheme, component)) print('Saved plot to {0}_{1}_{2}{3}_logP.png'.format(ENV, molecule_name, scheme, component)) plt.clf()
Example #25
Source File: test_backend_pgf.py From neural-network-animation with MIT License | 5 votes |
def create_figure(): plt.figure() x = np.linspace(0, 1, 15) plt.plot(x, x ** 2, "b-") plt.fill_between([0., .4], [.4, 0.], hatch='//', facecolor="lightgray", edgecolor="red") plt.plot(x, 1 - x**2, "g>") plt.plot([0.9], [0.5], "ro", markersize=3) plt.text(0.9, 0.5, 'unicode (ü, °, µ) and math ($\\mu_i = x_i^2$)', ha='right', fontsize=20) plt.ylabel('sans-serif, blue, $\\frac{\\sqrt{x}}{y^2}$..', family='sans-serif', color='blue') # test compiling a figure to pdf with xelatex
Example #26
Source File: squad_utils.py From Chinese-XLNet with Apache License 2.0 | 5 votes |
def plot_pr_curve(precisions, recalls, out_image, title): plt.step(recalls, precisions, color='b', alpha=0.2, where='post') plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(title) plt.savefig(out_image) plt.clf()
Example #27
Source File: displayer.py From cherry with MIT License | 5 votes |
def plot_learning_curve(self, estimator, title, X, y, ylim=None, cv=None, n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)): # From https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html print('Drawing curve, depending on your datasets size, this may take several minutes to several hours.') plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") plt.show()
Example #28
Source File: evaluate-v2.0.py From GPT2sQA with Apache License 2.0 | 5 votes |
def plot_pr_curve(precisions, recalls, out_image, title): plt.step(recalls, precisions, color='b', alpha=0.2, where='post') plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(title) plt.savefig(out_image) plt.clf()
Example #29
Source File: print_figures.py From Generative_Continual_Learning with MIT License | 5 votes |
def plot_perf_by_class(save_dir, list_method, list_overall_best_score, list_overall_best_score_classes, Dataset, Task): style_c = cycle(['-', '--', ':', '-.']) for Method in list_method: # there is no results for this case if Task == 'upperbound_disjoint' and not Method == 'Baseline': continue for iter, [best_result_class, dataset, method, model, num_task, task] in enumerate( list_overall_best_score_classes): if method == Method and dataset == Dataset and task == Task: label = model if best_result_class.shape[0] == 0: print("plot_perf_by_class : Problem with : " + str([dataset, method, model, num_task, task])) print(best_result_class) continue # print(best_result_class.shape) # [task, class] if len(best_result_class) > 1: best_result_mean = np.mean(best_result_class, axis=0) best_result_std = np.std(best_result_class, axis=0) plt.plot(range(num_task), best_result_mean[:, 0], label=label, linestyle=next(style_c)) plt.fill_between(range(num_task), best_result_mean[:, 0] - best_result_std[:, 0], best_result_mean[:, 0] + best_result_std[:, 0], alpha=0.4) else: best_result_class = best_result_class.reshape(num_task, 10) plt.plot(range(num_task), best_result_class[:, 0], label=label, linestyle=next(style_c)) plt.xlabel("Tasks") plt.ylabel("Task 0 Accuracy") plt.ylim([0, 100]) plt.legend(loc=2, title='Algo') plt.title('accuracy_all_tasks') plt.savefig(os.path.join(save_dir, Dataset + '_' + Task + '_' + Method + "_task0_accuracy.png")) plt.clf()
Example #30
Source File: mlab.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def offset_line(y, yerr): """ Offsets an array *y* by +/- an error and returns a tuple (y - err, y + err). The error term can be: * A scalar. In this case, the returned tuple is obvious. * A vector of the same length as *y*. The quantities y +/- err are computed component-wise. * A tuple of length 2. In this case, yerr[0] is the error below *y* and yerr[1] is error above *y*. For example:: import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, num=100, endpoint=True) y = np.sin(x) y_minus, y_plus = mlab.offset_line(y, 0.1) plt.plot(x, y) plt.fill_between(x, y_minus, y2=y_plus) plt.show() """ if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and len(yerr) == len(y)): ymin = y - yerr ymax = y + yerr elif len(yerr) == 2: ymin, ymax = y - yerr[0], y + yerr[1] else: raise ValueError("yerr must be scalar, 1xN or 2xN") return ymin, ymax