Python matplotlib.pylab.grid() Examples
The following are 30
code examples of matplotlib.pylab.grid().
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.pylab
, or try the search function
.
Example #1
Source File: run_lookup.py From rasa_lookup_demo with Apache License 2.0 | 6 votes |
def plot_metrics(metric_list, save_path=None): # runs through each test case and adds a set of bars to a plot. Saves f, (ax1) = plt.subplots(1, 1) plt.grid(True) print_metrics(metric_list) bar_metrics(metric_list[0], ax1, index=0) bar_metrics(metric_list[1], ax1, index=1) bar_metrics(metric_list[2], ax1, index=2) if save_path is None: save_path = "img/bar_" + key + ".png" plt.savefig(save_path, dpi=400)
Example #2
Source File: plot_kmeans_example.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 6 votes |
def plot_clustering(x, y, title, mx=None, ymax=None, xmin=None, km=None): pylab.figure(num=None, figsize=(8, 6)) if km: pylab.scatter(x, y, s=50, c=km.predict(list(zip(x, y)))) else: pylab.scatter(x, y, s=50) pylab.title(title) pylab.xlabel("Occurrence word 1") pylab.ylabel("Occurrence word 2") pylab.autoscale(tight=True) pylab.ylim(ymin=0, ymax=1) pylab.xlim(xmin=0, xmax=1) pylab.grid(True, linestyle='-', color='0.75') return pylab
Example #3
Source File: trajectory.py From notebook-molecular-visualization with Apache License 2.0 | 6 votes |
def plot(traj, x, y, **kwargs): """ Create a matplotlib plot of property x against property y Args: x,y (str): names of the properties **kwargs (dict): kwargs for :meth:`matplotlib.pylab.plot` Returns: List[matplotlib.lines.Lines2D]: the lines that were plotted """ from matplotlib import pylab xl = yl = None if type(x) is str: strx = x x = getattr(traj, x) xl = '%s / %s' % (strx, getattr(x, 'units', 'dimensionless')) if type(y) is str: stry = y y = getattr(traj, y) yl = '%s / %s' % (stry, getattr(y, 'units', 'dimensionless')) plt = pylab.plot(x, y, **kwargs) pylab.xlabel(xl); pylab.ylabel(yl); pylab.grid() return plt
Example #4
Source File: benchmark.py From osqp_benchmarks with Apache License 2.0 | 6 votes |
def plot_performance_profiles(problems, solvers): """ Plot performance profiles in matplotlib for specified problems and solvers """ # Remove OSQP polish solver solvers = solvers.copy() for s in solvers: if "polish" in s: solvers.remove(s) df = pd.read_csv('./results/%s/performance_profiles.csv' % problems) plt.figure(0) for solver in solvers: plt.plot(df["tau"], df[solver], label=solver) plt.xlim(1., 10000.) plt.ylim(0., 1.) plt.xlabel(r'Performance ratio $\tau$') plt.ylabel('Ratio of problems solved') plt.xscale('log') plt.legend() plt.grid() plt.show(block=False) results_file = './results/%s/%s.png' % (problems, problems) print("Saving plots to %s" % results_file) plt.savefig(results_file)
Example #5
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 6 votes |
def plot_roc(auc_score, name, tpr, fpr, label=None): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) pylab.grid(True) pylab.plot([0, 1], [0, 1], 'k--') pylab.plot(fpr, tpr) pylab.fill_between(fpr, tpr, alpha=0.5) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('False Positive Rate') pylab.ylabel('True Positive Rate') pylab.title('ROC curve (AUC = %0.2f) / %s' % (auc_score, label), verticalalignment="bottom") pylab.legend(loc="lower right") filename = name.replace(" ", "_") pylab.savefig( os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight")
Example #6
Source File: evaluate.py From text-classifier with Apache License 2.0 | 6 votes |
def plot_pr(auc_score, precision, recall, label=None, figure_path=None): """绘制R/P曲线""" try: from matplotlib import pylab pylab.figure(num=None, figsize=(6, 5)) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('Recall') pylab.ylabel('Precision') pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label)) pylab.fill_between(recall, precision, alpha=0.5) pylab.grid(True, linestyle='-', color='0.75') pylab.plot(recall, precision, lw=1) pylab.savefig(figure_path) except Exception as e: print("save image error with matplotlib") pass
Example #7
Source File: demo_mi.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 6 votes |
def plot_entropy(): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) title = "Entropy $H(X)$" pylab.title(title) pylab.xlabel("$P(X=$coin will show heads up$)$") pylab.ylabel("$H(X)$") pylab.xlim(xmin=0, xmax=1.1) x = np.arange(0.001, 1, 0.001) y = -x * np.log2(x) - (1 - x) * np.log2(1 - x) pylab.plot(x, y) # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in # [0,1,2,3,4]]) pylab.autoscale(tight=True) pylab.grid(True) filename = "entropy_demo.png" pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #8
Source File: kNN.py From statistical-learning-methods-note with Apache License 2.0 | 6 votes |
def plotKChart(self, misClassDict, saveFigPath): kList = [] misRateList = [] for k, misClassNum in misClassDict.iteritems(): kList.append(k) misRateList.append(1.0 - 1.0/k*misClassNum) fig = plt.figure(saveFigPath) plt.plot(kList, misRateList, 'r--') plt.title(saveFigPath) plt.xlabel('k Num.') plt.ylabel('Misclassified Rate') plt.legend(saveFigPath) plt.grid(True) plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # 例子
Example #9
Source File: utils.py From ndvr-dml with Apache License 2.0 | 6 votes |
def plot_pr_curve(pr_curve_dml, pr_curve_base, title): """ Function that plots the PR-curve. Args: pr_curve: the values of precision for each recall value title: the title of the plot """ plt.figure(figsize=(16, 9)) plt.plot(np.arange(0.0, 1.05, 0.05), pr_curve_base, color='r', marker='o', linewidth=3, markersize=10) plt.plot(np.arange(0.0, 1.05, 0.05), pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10) plt.grid(True, linestyle='dotted') plt.xlabel('Recall', color='k', fontsize=27) plt.ylabel('Precision', color='k', fontsize=27) plt.yticks(color='k', fontsize=20) plt.xticks(color='k', fontsize=20) plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title(title, color='k', fontsize=27) plt.tight_layout() plt.show()
Example #10
Source File: multirate_helper.py From scikit-dsp-comm with BSD 2-Clause "Simplified" License | 5 votes |
def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]): """ """ fir_d.freqz_resp_list([self.b],[1], mode, fs=fs, Npts = 1024) pylab.grid() pylab.ylim(ylim)
Example #11
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_pr(auc_score, name, precision, recall, label=None): pylab.figure(num=None, figsize=(6, 5)) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('Recall') pylab.ylabel('Precision') pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label)) pylab.fill_between(recall, precision, alpha=0.5) pylab.grid(True, linestyle='-', color='0.75') pylab.plot(recall, precision, lw=1) filename = name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, "pr_" + filename + ".png"))
Example #12
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_bias_variance(data_sizes, train_errors, test_errors, name, title): pylab.figure(num=None, figsize=(6, 5)) pylab.ylim([0.0, 1.0]) pylab.xlabel('Data set size') pylab.ylabel('Error') pylab.title("Bias-Variance for '%s'" % name) pylab.plot( data_sizes, test_errors, "--", data_sizes, train_errors, "b-", lw=1) pylab.legend(["test error", "train error"], loc="upper right") pylab.grid(True, linestyle='-', color='0.75') pylab.savefig( os.path.join(CHART_DIR, "bv_" + name.replace(" ", "_") + ".png"), bbox_inches="tight")
Example #13
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_k_complexity(ks, train_errors, test_errors): pylab.figure(num=None, figsize=(6, 5)) pylab.ylim([0.0, 1.0]) pylab.xlabel('k') pylab.ylabel('Error') pylab.title('Errors for for different values of $k$') pylab.plot( ks, test_errors, "--", ks, train_errors, "-", lw=1) pylab.legend(["test error", "train error"], loc="upper right") pylab.grid(True, linestyle='-', color='0.75') pylab.savefig( os.path.join(CHART_DIR, "kcomplexity.png"), bbox_inches="tight")
Example #14
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_feat_hist(data_name_list, filename=None): if len(data_name_list) > 1: assert filename is not None pylab.figure(num=None, figsize=(8, 6)) num_rows = int(1 + (len(data_name_list) - 1) / 2) num_cols = int(1 if len(data_name_list) == 1 else 2) pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Fraction') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #15
Source File: multirate_helper.py From scikit-dsp-comm with BSD 2-Clause "Simplified" License | 5 votes |
def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]): """ Frequency response plot """ iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs) pylab.grid() pylab.ylim(ylim)
Example #16
Source File: param_scheduler.py From ignite with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_values(cls, num_events, **scheduler_kwargs): """Method to plot simulated scheduled values during `num_events` events. This class requires `matplotlib package <https://matplotlib.org/>`_ to be installed: .. code-block:: bash pip install matplotlib Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: matplotlib.lines.Line2D Examples: .. code-block:: python import matplotlib.pylab as plt plt.figure(figsize=(10, 7)) LinearCyclicalScheduler.plot_values(num_events=50, param_name='lr', start_value=1e-1, end_value=1e-3, cycle_size=10)) """ try: import matplotlib.pylab as plt except ImportError: raise RuntimeError( "This method requires matplotlib to be installed. " "Please install it with command: \n pip install matplotlib" ) values = cls.simulate_values(num_events=num_events, **scheduler_kwargs) label = scheduler_kwargs.get("param_name", "learning rate") ax = plt.plot([e for e, _ in values], [v for _, v in values], label=label) plt.legend() plt.grid(which="both") return ax
Example #17
Source File: Time Series Analysis.py From python-urbanPlanning with MIT License | 5 votes |
def plotModelResults(model, X_train, X_test,y_train,y_test, plot_intervals=False, plot_anomalies=False, scale=1.96): """ Plots modelled vs fact values, prediction intervals and anomalies """ prediction = model.predict(X_test) plt.figure(figsize=(15, 7)) plt.plot(prediction, "g", label="prediction", linewidth=2.0) plt.plot(y_test.values, label="actual", linewidth=2.0) if plot_intervals: cv = cross_val_score(model, X_train, y_train, cv=tscv, scoring="neg_mean_squared_error") #mae = cv.mean() * (-1) deviation = np.sqrt(cv.std()) lower = prediction - (scale * deviation) upper = prediction + (scale * deviation) plt.plot(lower, "r--", label="upper bond / lower bond", alpha=0.5) plt.plot(upper, "r--", alpha=0.5) if plot_anomalies: anomalies = np.array([np.NaN]*len(y_test)) anomalies[y_test<lower] = y_test[y_test<lower] anomalies[y_test>upper] = y_test[y_test>upper] plt.plot(anomalies, "o", markersize=10, label = "Anomalies") error = mean_absolute_percentage_error(prediction, y_test) plt.title("Mean absolute percentage error {0:.2f}%".format(error)) plt.legend(loc="best") plt.tight_layout() plt.grid(True);
Example #18
Source File: Time Series Analysis.py From python-urbanPlanning with MIT License | 5 votes |
def plotCoefficients(model,X_train): """ Plots sorted coefficient values of the model """ coefs = pd.DataFrame(model.coef_, X_train.columns) coefs.columns = ["coef"] coefs["abs"] = coefs.coef.apply(np.abs) coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1) plt.figure(figsize=(15, 7)) coefs.coef.plot(kind='bar') plt.grid(True, axis='y') plt.hlines(y=0, xmin=0, xmax=len(coefs), linestyles='dashed');
Example #19
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_feat_hist(data_name_list, filename=None): pylab.clf() num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Density') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, facecolor='green', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #20
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_log(): pylab.clf() x = np.arange(0.001, 1, 0.001) y = np.log(x) pylab.title('Relationship between probabilities and their logarithm') pylab.plot(x, y) pylab.grid(True) pylab.xlabel('P') pylab.ylabel('log(P)') filename = 'log_probs.png' pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #21
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_pr(auc_score, name, precision, recall, label=None): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) pylab.grid(True) pylab.fill_between(recall, precision, alpha=0.5) pylab.plot(recall, precision, lw=1) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('Recall') pylab.ylabel('Precision') pylab.title('P/R curve (AUC = %0.2f) / %s' % (auc_score, label)) filename = name.replace(" ", "_") pylab.savefig( os.path.join(CHART_DIR, "pr_" + filename + ".png"), bbox_inches="tight")
Example #22
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_pr(auc_score, name, phase, precision, recall, label=None): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) pylab.grid(True) pylab.fill_between(recall, precision, alpha=0.5) pylab.plot(recall, precision, lw=1) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('Recall') pylab.ylabel('Precision') pylab.title('P/R curve (AUC=%0.2f) / %s' % (auc_score, label)) filename = name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, "pr_%s_%s.png" % (filename, phase)), bbox_inches="tight")
Example #23
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_log(): pylab.clf() pylab.figure(num=None, figsize=(6, 5)) x = np.arange(0.001, 1, 0.001) y = np.log(x) pylab.title('Relationship between probabilities and their logarithm') pylab.plot(x, y) pylab.grid(True) pylab.xlabel('P') pylab.ylabel('log(P)') filename = 'log_probs.png' pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #24
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_feat_hist(data_name_list, filename=None): pylab.clf() num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Density') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, facecolor='green', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #25
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_bias_variance(data_sizes, train_errors, test_errors, name): pylab.clf() pylab.ylim([0.0, 1.0]) pylab.xlabel('Data set size') pylab.ylabel('Error') pylab.title("Bias-Variance for '%s'" % name) pylab.plot( data_sizes, train_errors, "-", data_sizes, test_errors, "--", lw=1) pylab.legend(["train error", "test error"], loc="upper right") pylab.grid() pylab.savefig(os.path.join(CHART_DIR, "bv_" + name + ".png"))
Example #26
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_bias_variance(data_sizes, train_errors, test_errors, name): pylab.clf() pylab.ylim([0.0, 1.0]) pylab.xlabel('Data set size') pylab.ylabel('Error') pylab.title("Bias-Variance for '%s'" % name) pylab.plot( data_sizes, train_errors, "-", data_sizes, test_errors, "--", lw=1) pylab.legend(["train error", "test error"], loc="upper right") pylab.grid(True) pylab.savefig(os.path.join(CHART_DIR, "bv_" + name + ".png"))
Example #27
Source File: demo_pca.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 4 votes |
def plot_simple_demo_2(): pylab.clf() fig = pylab.figure(num=None, figsize=(10, 4)) pylab.subplot(121) title = "Original feature space" pylab.title(title) pylab.xlabel("$X_1$") pylab.ylabel("$X_2$") x1 = np.arange(0, 10, .2) x2 = x1 + np.random.normal(scale=1, size=len(x1)) good = x1 > x2 bad = ~good x1g = x1[good] x2g = x2[good] pylab.scatter(x1g, x2g, edgecolor="blue", facecolor="blue") x1b = x1[bad] x2b = x2[bad] pylab.scatter(x1b, x2b, edgecolor="red", facecolor="white") pylab.grid(True) pylab.subplot(122) X = np.c_[(x1, x2)] pca = decomposition.PCA(n_components=1) Xtrans = pca.fit_transform(X) Xg = Xtrans[good] Xb = Xtrans[bad] pylab.scatter( Xg[:, 0], np.zeros(len(Xg)), edgecolor="blue", facecolor="blue") pylab.scatter( Xb[:, 0], np.zeros(len(Xb)), edgecolor="red", facecolor="white") title = "Transformed feature space" pylab.title(title) pylab.xlabel("$X'$") fig.axes[1].get_yaxis().set_visible(False) print(pca.explained_variance_ratio_) pylab.grid(True) pylab.autoscale(tight=True) filename = "pca_demo_2.png" pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #28
Source File: probability.py From razzy-spinner with GNU General Public License v3.0 | 4 votes |
def plot(self, *args, **kwargs): """ Plot the given samples from the conditional frequency distribution. For a cumulative plot, specify cumulative=True. (Requires Matplotlib to be installed.) :param samples: The samples to plot :type samples: list :param title: The title for the graph :type title: str :param conditions: The conditions to plot (default is all) :type conditions: list """ try: from matplotlib import pylab except ImportError: raise ValueError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') cumulative = _get_kwarg(kwargs, 'cumulative', False) conditions = _get_kwarg(kwargs, 'conditions', sorted(self.conditions())) title = _get_kwarg(kwargs, 'title', '') samples = _get_kwarg(kwargs, 'samples', sorted(set(v for c in conditions for v in self[c]))) # this computation could be wasted if not "linewidth" in kwargs: kwargs["linewidth"] = 2 for condition in conditions: if cumulative: freqs = list(self[condition]._cumulative_frequencies(samples)) ylabel = "Cumulative Counts" legend_loc = 'lower right' else: freqs = [self[condition][sample] for sample in samples] ylabel = "Counts" legend_loc = 'upper right' # percents = [f * 100 for f in freqs] only in ConditionalProbDist? kwargs['label'] = "%s" % condition pylab.plot(freqs, *args, **kwargs) pylab.legend(loc=legend_loc) pylab.grid(True, color="silver") pylab.xticks(range(len(samples)), [compat.text_type(s) for s in samples], rotation=90) if title: pylab.title(title) pylab.xlabel("Samples") pylab.ylabel(ylabel) pylab.show()
Example #29
Source File: getFoodContourMorph.py From tierpsy-tracker with MIT License | 4 votes |
def get_food_contour_morph(mask_video, min_area = None, n_bins = 180, frac_lowess=0.1, _is_debug=False): ''' Identify the contour of a food patch. I tested this for the worm rig. It assumes the food has a semi-circular shape. The food lawn is very thin so the challenge was to estimate the contour of a very dim area. ''' #%% try: with tables.File(mask_video, 'r') as fid: full_data = fid.get_node('/full_data')[:5] # I am using the first two images to calculate this info except tables.exceptions.NoSuchNodeError: return None, None img = np.max(full_data[:2], axis=0) #dark_mask = get_dark_mask(full_data) mask = get_patch_mask(img, min_area = min_area) circx, circy, best_fit = mask_to_food_contour(mask, n_bins = n_bins, frac_lowess=frac_lowess) if _is_debug: from skimage.draw import circle_perimeter import matplotlib.pylab as plt cpx, cpy = circle_perimeter(*best_fit[1:]) plt.figure(figsize=(5,5)) plt.gca().xaxis.set_ticklabels([]) plt.gca().yaxis.set_ticklabels([]) (px, py) = np.where(skeletonize(mask)) plt.imshow(img, cmap='gray') plt.plot(py, px, '.') plt.plot(cpx, cpy, '.r') plt.plot(circy, circx, '.') plt.grid('off') food_cnt = np.vstack((circy, circx)).T return food_cnt
Example #30
Source File: B_spatial_accuracy_check.py From pySDC with BSD 2-Clause "Simplified" License | 4 votes |
def plot_accuracy(results): """ Routine to visualize the errors as well as the expected errors Args: results: the dictionary containing the errors """ # retrieve the list of nvars from results assert 'nvars_list' in results, 'ERROR: expecting the list of nvars in the results dictionary' nvars_list = sorted(results['nvars_list']) # Set up plotting parameters params = {'legend.fontsize': 20, 'figure.figsize': (12, 8), 'axes.labelsize': 20, 'axes.titlesize': 20, 'xtick.labelsize': 16, 'ytick.labelsize': 16, 'lines.linewidth': 3 } plt.rcParams.update(params) # create new figure plt.figure() # take x-axis limits from nvars_list + some spacning left and right plt.xlim([min(nvars_list) / 2, max(nvars_list) * 2]) plt.xlabel('nvars') plt.ylabel('abs. error') plt.grid() # get guide for the order of accuracy, i.e. the errors to expect # get error for first entry in nvars_list id = ID(nvars=nvars_list[0]) base_error = results[id] # assemble optimal errors for 2nd order method and plot order_guide_space = [base_error / (2 ** (2 * i)) for i in range(0, len(nvars_list))] plt.loglog(nvars_list, order_guide_space, color='k', ls='--', label='2nd order') min_err = 1E99 max_err = 0E00 err_list = [] # loop over nvars, get errors and find min/max error for y-axis limits for nvars in nvars_list: id = ID(nvars=nvars) err = results[id] min_err = min(err, min_err) max_err = max(err, max_err) err_list.append(err) plt.loglog(nvars_list, err_list, ls=' ', marker='o', markersize=10, label='experiment') # adjust y-axis limits, add legend plt.ylim([min_err / 10, max_err * 10]) plt.legend(loc=1, ncol=1, numpoints=1) # save plot as PDF, beautify fname = 'step_1_accuracy_test_space.png' plt.savefig(fname, rasterized=True, bbox_inches='tight') return None