Python matplotlib.pyplot.GridSpec() Examples
The following are 30
code examples of matplotlib.pyplot.GridSpec().
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: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 6 votes |
def _create_likelihood_axis(self, figure=None, subplot_spec=None, **kwargs): # Making the axes: if figure is None: figsize = kwargs.get('figsize', None) fig, _ = plt.subplots(0, 0, figsize=figsize, constrained_layout=False) else: fig = figure if subplot_spec is None: grid = plt.GridSpec(1, 1, hspace=0.1, wspace=0.1, figure=fig) else: grid = gridspect.GridSpecFromSubplotSpec(1, 1, subplot_spec=subplot_spec) ax_like = fig.add_subplot(grid[0, 0]) ax_like.spines['bottom'].set_position(('data', 0.0)) ax_like.yaxis.tick_right() ax_like.spines['right'].set_position(('axes', 1.03)) ax_like.spines['top'].set_color('none') ax_like.spines['left'].set_color('none') ax_like.set_xlabel('Thickness Obs.') ax_like.set_title('Likelihood') return ax_like
Example #2
Source File: plot.py From seqc with GNU General Public License v2.0 | 6 votes |
def __init__(self, n: int, max_cols=3, scale=3): """ :param n: number of axes to generate :param max_cols: maximum number of axes in a given row """ self.n = n self.nrows = int(np.ceil(n / max_cols)) self.ncols = int(min((max_cols, n))) figsize = self.ncols * scale, self.nrows * scale # create figure self.gs = plt.GridSpec(nrows=self.nrows, ncols=self.ncols) self.figure = plt.figure(figsize=figsize) # create axes self.axes = {} for i in range(n): row = int(i // self.ncols) col = int(i % self.ncols) self.axes[i] = plt.subplot(self.gs[row, col])
Example #3
Source File: analyze_hostguest.py From SAMPL6 with MIT License | 5 votes |
def correlation_plots(plotted_methods, file_name): """Shortcut to create correlation plots.""" n_methods = len(plotted_methods) n_cols = 5 n_rows = int(np.floor(n_methods/(n_cols-1))) plot_size = 7.25 / n_cols fig = plt.figure(figsize=(n_cols*plot_size, n_rows*plot_size)) grid = plt.GridSpec(nrows=n_rows, ncols=n_cols*2) # All rows have 4 plots except for last one which has 5. axes = [] for row_idx in range(n_rows-1): axes.extend([fig.add_subplot(grid[row_idx, c:c+2]) for c in range(1,9,2)]) axes.extend([fig.add_subplot(grid[-1, c:c+2]) for c in range(0,10,2)]) # Associate a color to each host. for method, ax in zip(plotted_methods, axes): # Isolate statistics of the method. data = collection_all.data[collection_all.data.method == method] # Build palette. palette = [HOST_PALETTE[host_name] for host_name in sorted(data.host_name.unique())] # Add color for regression line over all data points. palette += [HOST_PALETTE['other1']] # Plot correlations. plot_correlation(x='$\Delta$G (expt) [kcal/mol]', y='$\Delta$G (calc) [kcal/mol]', data=data, title=method, hue='host_name', color=palette, shaded_area_color=HOST_PALETTE['other2'], ax=ax) # Remove legend and axes labels. ax.legend_.remove() ax.set_xlabel('') ax.set_ylabel('') # Make title and axes labels closer to axes. ax.set_title(ax.get_title(), pad=1.5) ax.tick_params(pad=3.0) # Use a single label for the figure. fig.text(0.015, 0.5, '$\Delta$G (calc) [kcal/mol]', va='center', rotation='vertical', size='large') fig.text(0.5, 0.015, '$\Delta$G (exp) [kcal/mol]', ha='center', size='large') plt.tight_layout(pad=0.9, rect=[0.0, 0.025, 1.0, 1.0]) plt.savefig('../Accuracy/PaperImages/{}.pdf'.format(file_name))
Example #4
Source File: figures.py From sklearn_pydata2015 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_image_components(x, coefficients=None, mean=0, components=None, imshape=(8, 8), n_components=6, fontsize=12): if coefficients is None: coefficients = x if components is None: components = np.eye(len(coefficients), len(x)) mean = np.zeros_like(x) + mean fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2)) g = plt.GridSpec(2, 5 + n_components, hspace=0.3) def show(i, j, x, title=None): ax = fig.add_subplot(g[i, j], xticks=[], yticks=[]) ax.imshow(x.reshape(imshape), interpolation='nearest') if title: ax.set_title(title, fontsize=fontsize) show(slice(2), slice(2), x, "True") approx = mean.copy() show(0, 2, np.zeros_like(x) + mean, r'$\mu$') show(1, 2, approx, r'$1 \cdot \mu$') for i in range(0, n_components): approx = approx + coefficients[i] * components[i] show(0, i + 3, components[i], r'$c_{0}$'.format(i + 1)) show(1, i + 3, approx, r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1)) plt.gca().text(0, 1.05, '$+$', ha='right', va='bottom', transform=plt.gca().transAxes, fontsize=fontsize) show(slice(2), slice(-2, None), approx, "Approx")
Example #5
Source File: test_brush.py From viznet with MIT License | 5 votes |
def __enter__(self): plt.ion() plt.figure(figsize=self.figsize) self.gs = plt.GridSpec(*self.grid) return self
Example #6
Source File: false_postive_analysis.py From DETAD with MIT License | 5 votes |
def plot_fp_analysis(fp_error_analysis, save_filename, colors=['#33a02c','#b2df8a','#1f78b4','#fb9a99','#e31a1c','#a6cee3'], error_names=['True Postive', 'Double Detection Err','Wrong Lable Err', 'Localization Err', 'Confusion Err', 'Background Err'], figsize=(10,5), fontsize=24): values,labels = [],[] _, _, fp_error_types_precentage_df = split_predictions_by_score_ranges(fp_error_analysis,fp_error_analysis.limit_factor) order = np.array([4,2,5,3,1,0]) for this_limit_factor, this_fp_error_types_precentage_df in fp_error_types_precentage_df.iteritems(): values+=[this_fp_error_types_precentage_df['avg'].values[order]] labels+=['$%dG$' % (this_limit_factor+1)] fig = plt.figure(figsize=figsize) grid = plt.GridSpec(1, 5) lgd = subplot_fp_profile(fig=fig, ax=fig.add_subplot(grid[:-2]), values=values, labels=labels, colors=colors, xticks=error_names, xlabel='Top Predicitons', ylabel='Error Breakdown ($\%$)', title='False Postive Profile', fontsize=fontsize, ncol=3, legend_loc=(-0.15,1.15)) order = np.array([4,0,1,3,2]) subplot_error_type_impact(fig=fig, ax=fig.add_subplot(grid[-2:]), values=np.array([fp_error_analysis.average_mAP_gain.values()]).T[order,:], labels=np.array(fp_error_analysis.average_mAP_gain.keys())[order], colors=colors[::-1], xlabel='Error Type', ylabel='Average-mAP$_N$\nImprovment $(\%)$', title='Removing Error Impact', fontsize=fontsize, top=np.ceil(np.max(fp_error_analysis.average_mAP_gain.values())*100*1.1)) plt.tight_layout() fig.savefig(save_filename,box_extra_artists=(lgd,), bbox_inches='tight') print('[Done] Output analysis is saved in %s' % save_filename)
Example #7
Source File: gridspec.py From scvelo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def gridspec(ncols=4, nrows=1, figsize=None, dpi=None): figsize, dpi = get_figure_params(figsize, dpi, ncols) gs = pl.GridSpec( nrows, ncols, pl.figure(None, (figsize[0] * ncols, figsize[1] * nrows), dpi=dpi) ) return gs
Example #8
Source File: gridspec.py From scvelo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, ncols=4, nrows=1, figsize=None, dpi=None, **scatter_kwargs): """Specifies the geometry of the grid that a subplots can be placed in Example .. code:: python with scv.GridSpec() as pl: pl.scatter(adata, basis='pca') pl.scatter(adata, basis='umap') pl.hist(adata.obs.initial_size) Parameters ---------- ncols: `int` (default: 4) Number of panels per row. nrows: `int` (default: 1) Number of panels per column. figsize: tuple (default: `None`) Figure size. dpi: `int` (default: `None`) Figure dpi. scatter_kwargs: Arguments to be passed to all scatter plots, e.g. `frameon=False`. """ self.ncols, self.nrows, self.figsize, self.dpi = ncols, nrows, figsize, dpi self.scatter_kwargs = scatter_kwargs self.scatter_kwargs.update({"show": False}) self.get_new_grid() self.new_row = None
Example #9
Source File: analysis.py From velocyto.py with BSD 2-Clause "Simplified" License | 5 votes |
def plot_phase_portraits(self, genes: List[str]) -> None: """Plot spliced-unspliced scatterplots resembling phase portraits Arguments --------- genes: List[str] A list of gene symbols. """ n = len(genes) sqrtn = int(np.ceil(np.sqrt(n))) gs = plt.GridSpec(sqrtn, int(np.ceil(n / sqrtn))) for i, gn in enumerate(genes): self._plot_phase_portrait(gn, gs[i])
Example #10
Source File: figures.py From MachineLearning with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_image_components(x, coefficients=None, mean=0, components=None, imshape=(8, 8), n_components=6, fontsize=12): if coefficients is None: coefficients = x if components is None: components = np.eye(len(coefficients), len(x)) mean = np.zeros_like(x) + mean fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2)) g = plt.GridSpec(2, 5 + n_components, hspace=0.3) def show(i, j, x, title=None): ax = fig.add_subplot(g[i, j], xticks=[], yticks=[]) ax.imshow(x.reshape(imshape), interpolation='nearest') if title: ax.set_title(title, fontsize=fontsize) show(slice(2), slice(2), x, "True") approx = mean.copy() show(0, 2, np.zeros_like(x) + mean, r'$\mu$') show(1, 2, approx, r'$1 \cdot \mu$') for i in range(0, n_components): approx = approx + coefficients[i] * components[i] show(0, i + 3, components[i], r'$c_{0}$'.format(i + 1)) show(1, i + 3, approx, r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1)) plt.gca().text(0, 1.05, '$+$', ha='right', va='bottom', transform=plt.gca().transAxes, fontsize=fontsize) show(slice(2), slice(-2, None), approx, "Approx")
Example #11
Source File: plotting.py From PyFNND with GNU General Public License v3.0 | 5 votes |
def plot_fit(F, n_hat, C_hat, theta_hat, dt): sigma, alpha, beta, lamb, gamma = theta_hat fig = plt.figure() gs = plt.GridSpec(3, 1) ax1 = fig.add_subplot(gs[0:2]) ax2 = fig.add_subplot(gs[2:], sharex=ax1) axes = np.array([ax1, ax2]) t = np.arange(F.shape[1]) * dt F_hat = alpha[:, None] * C_hat[None, :] + beta[:, None] axes[0].hold(True) axes[0].plot(t, F.sum(0), '-b', label=r'$F$') axes[0].plot(t, F_hat.sum(0), '-r', lw=1, label=r'$\hat{\alpha}\hat{C}+\hat{\beta}$') axes[0].legend(loc=1, fancybox=True, fontsize='large') axes[0].tick_params(labelbottom=False) axes[1].plot(t, n_hat, '-k') axes[1].set_xlabel('Time (s)') axes[1].set_ylabel(r'$\hat{n}$', fontsize='large') axes[1].set_xlim(0, t[-1]) fig.tight_layout() return fig, axes
Example #12
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 5 votes |
def plot_base_to_lip_from_knickpoint_profile(self, df = 0, comparison_point = [], size_format='ESURF', FigFormat='png'): if(isinstance(df,int)): df = self.knickpoint_raw raster_directory = self.fpath+'raster_plots/' if not os.path.isdir(raster_directory): os.makedirs(raster_directory) self.get_base_to_lip_from_knickpoint(df) for source in df["source_key"].unique(): print(source) # make a figure with required dimensions if size_format == "geomorphology": fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) elif size_format == "big": fig = plt.figure(1, facecolor='white',figsize=(16,9)) else: fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5)) # create the axis and its position ## axis 1: The Chi profile and the knickpoints gs = plt.GridSpec(100,100,bottom=0.15,left=0.15,right=0.95,top=0.95) ax = fig.add_subplot(gs[0:100,0:100]) CN = self.chanNet[self.chanNet["source_key"] == source] ax.plot(CN["chi"], CN["elevation"],zorder = 100) for i in self.base_to_lip_from_knickpoint: if i.iloc[0]["source_key"] == source: ax.scatter(i.iloc[0]["chi"],i.iloc[0]["segmented_elevation"], s = 10, c = "r", zorder = 150) ax.scatter(i.iloc[-1]["chi"],i.iloc[-1]["segmented_elevation"], s = 10, c = "b", zorder = 150) if(len(comparison_point) == 2): print("I am adding the comparison_point to the profiles") ax.scatter(comparison_point[0]["chi"][comparison_point[0]["source_key"] == source], comparison_point[0]["elevation"][comparison_point[0]["source_key"] == source], marker = "x", c = "r", s = 20,lw = 0.8, zorder = 500) ax.scatter(comparison_point[1]["chi"][comparison_point[1]["source_key"] == source], comparison_point[1]["elevation"][comparison_point[1]["source_key"] == source], marker = "x", c = "y", s = 20,lw = 0.8, zorder = 500) plt.savefig(raster_directory +"profile_base_to_lip"+str(source)+".png",dpi = 300) plt.clf()
Example #13
Source File: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def create_figure(self, marginal=True, likelihood=True, joyplot=True, figsize=None, textsize=None, n_samples=11): figsize, self.ax_labelsize, _, self.xt_labelsize, self.linewidth, _ = _scale_fig_size(figsize, textsize) self.fig, axes = plt.subplots(0, 0, figsize=figsize, constrained_layout=False) gs_0 = gridspect.GridSpec(3, 6, figure=self.fig, hspace=.1) if marginal is True: # Testing if likelihood is False: self.marginal_axes = self._create_joint_axis(figure=self.fig, subplot_spec=gs_0[0:2, 0:4]) elif likelihood is False and joyplot is False: self.marginal_axes = self._create_joint_axis(figure=self.fig, subplot_spec=gs_0[:, :]) else: self.marginal_axes = self._create_joint_axis(figure=self.fig, subplot_spec=gs_0[0:2, 0:3]) if likelihood is True: if marginal is False: self.likelihood_axes = self._create_likelihood_axis(figure=self.fig, subplot_spec=gs_0[0:2, 0:4]) elif joyplot is False: self.likelihood_axes = self._create_likelihood_axis(figure=self.fig, subplot_spec=gs_0[0:2, 4:]) else: self.likelihood_axes = self._create_likelihood_axis(figure=self.fig, subplot_spec=gs_0[0:1, 4:]) if joyplot is True: self.n_samples = n_samples if marginal is False and likelihood is False: self.joy = self._create_joy_axis(self.fig, gs_0[:, :]) else: self.joy = self._create_joy_axis(self.fig, gs_0[1:2, 4:])
Example #14
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 5 votes |
def DEBUG_print_KDE(self): """ This function is used to print one ksn profile per river to check the effect of the different filters on the dataset BG - 12/01/2018 """ plt.clf() print("I will now print ksn(chi) with the different KDE") svdir = self.fpath+'river_plots/' if not os.path.isdir(svdir): os.makedirs(svdir) for SK in self.df_kp_raw["source_key"].unique(): print("printing river: " +str(SK)) # Selecting the river df = self.df_kp_raw[self.df_kp_raw["source_key"] == SK] fig = plt.figure(1, facecolor='white',figsize=(9,5)) gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95) ax1 = fig.add_subplot(gs[0:100,0:100]) ax1.scatter(df["dksn/dchi"], df["KDE"], c = "k", s = 1, marker = "+", label = "ksn") ax1.set_xlabel(r'$ \frac{dk_{sn}}{\chi}$') ax1.set_ylabel(r'$ KDE_pdf $') plt.savefig(svdir + self.fprefix + "_KDE_SK_" +str(SK)+".png", dpi = 300) plt.clf()
Example #15
Source File: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def _create_joint_axis(self, figure=None, subplot_spec=None, figsize=None, textsize=None): figsize, ax_labelsize, _, xt_labelsize, linewidth, _ = _scale_fig_size(figsize, textsize) # Instantiate figure and grid if figure is None: fig, _ = plt.subplots(0, 0, figsize=figsize, constrained_layout=True) else: fig = figure if subplot_spec is None: grid = plt.GridSpec(4, 4, hspace=0.1, wspace=0.1, figure=fig) else: grid = gridspect.GridSpecFromSubplotSpec(4, 4, subplot_spec=subplot_spec) # Set up main plot self.axjoin = fig.add_subplot(grid[1:, :-1]) # Set up top KDE self.ax_hist_x = fig.add_subplot(grid[0, :-1], sharex=self.axjoin) self.ax_hist_x.tick_params(labelleft=False, labelbottom=False) # Set up right KDE self.ax_hist_y = fig.add_subplot(grid[1:, -1], sharey=self.axjoin) self.ax_hist_y.tick_params(labelleft=False, labelbottom=False) sns.despine(left=True, bottom=True) return self.axjoin, self.ax_hist_x, self.ax_hist_y
Example #16
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 5 votes |
def DEBUG_print_ksn_outliers(self): """ This function is used to print one ksn profile per river to check the effect of the different filters on the dataset BG - 12/01/2018 """ plt.clf() print("I will now print ksn(chi) with outliers") svdir = self.fpath+'river_plots/' if not os.path.isdir(svdir): os.makedirs(svdir) for SK in self.df_river["source_key"].unique(): print("printing river: " +str(SK)) # Selecting the river df = self.df_river[self.df_river["source_key"] == SK] dfo = self.df_kp[self.df_kp["source_key"] == SK] fig = plt.figure(1, facecolor='white',figsize=(9,5)) gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95) ax1 = fig.add_subplot(gs[0:100,0:100]) ax1.scatter(df["chi"], df["m_chi"], c = "r", s = 1, marker = "o", label = "ksn", alpha = 0.15) # ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn") # ax1.scatter(df["chi"], df["TVD_ksn_NC"], c = "purple", s = 2, marker = "x", label = "TVD ksn non corrected") ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn") ax1.scatter(dfo["chi"][dfo["out"]==1], dfo["delta_ksn"][dfo["out"]==1], c = "purple" , marker = "s", s = 4) lim = ax1.get_ylim() ax1.vlines(dfo["chi"][dfo["out"]==1],-1000,1000, lw = 0.5, alpha = 0.5) ax1.set_ylim(lim) ax1.legend() ax1.set_xlabel(r'$ \chi$') ax1.set_ylabel(r'$ k_{sn}$') plt.savefig(svdir + self.fprefix + "_outksn_SK_" +str(SK)+".png", dpi = 300) plt.clf()
Example #17
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 5 votes |
def DEBUG_print_ksn_filters(self): """ This function is used to print one ksn profile per river to check the effect of the different filters on the dataset BG - 12/01/2018 """ plt.clf() print("I will now print ksn(chi) with the different filter") svdir = self.fpath+'river_plots/' if not os.path.isdir(svdir): os.makedirs(svdir) for SK in self.df_river["source_key"].unique(): print("printing river: " +str(SK)) # Selecting the river df = self.df_river[self.df_river["source_key"] == SK] fig = plt.figure(1, facecolor='white',figsize=(9,5)) gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95) ax1 = fig.add_subplot(gs[0:100,0:100]) ax1.scatter(df["chi"], df["m_chi"], c = "r", s = 1, marker = "o", label = "ksn") ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn") ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn") ax1.legend() ax1.set_xlabel(r'$ \chi$') ax1.set_ylabel(r'$ k_{sn}$') plt.savefig(svdir + self.fprefix + "_ksn_SK_" +str(SK)+".png", dpi = 300) plt.clf()
Example #18
Source File: plotting.py From PyFNND with GNU General Public License v3.0 | 4 votes |
def plot_fit_2D(F, n_hat, C_hat, theta_hat, dt, nrows, ncols): sigma, alpha, beta, lamb, gamma = theta_hat fig = plt.figure() gs = plt.GridSpec(6, 4) ax1 = fig.add_subplot(gs[0:4, 0:3]) ax2 = fig.add_subplot(gs[4:6, 0:3], sharex=ax1) ax3 = fig.add_subplot(gs[0:3, 3]) ax4 = fig.add_subplot(gs[3:6, 3], sharex=ax3, sharey=ax3) axes = np.array([ax1, ax2, ax3, ax4]) t = np.arange(F.shape[1]) * dt F_hat = alpha[:, None] * C_hat[None, :] + beta[:, None] axes[0].hold(True) axes[0].plot(t, F.sum(0), '-b', label=r'$F$') axes[0].plot(t, F_hat.sum(0), '-r', lw=1, label=r'$\hat{\alpha}\hat{C}+\hat{\beta}$') axes[0].legend(loc=1, fancybox=True, fontsize='large') axes[0].tick_params(labelbottom=False) axes[1].plot(t, n_hat, '-k') axes[1].set_xlabel('Time (s)') axes[1].set_ylabel(r'$\hat{n}$', fontsize='large') axes[1].set_xlim(0, t[-1]) for ax in axes[2:4]: ax.hold(True) ax.set_axis_off() bbox_props = dict(boxstyle="round", fc=[0, 0, 0, 0.5], ec="None") # inferred mask axes[2].imshow(alpha.reshape(nrows, ncols), interpolation='nearest', cmap=plt.cm.gray) axes[2].annotate(r'$\hat{\alpha}$', (0, 0), xycoords='data', xytext=(5, -5), textcoords='offset points', ha='left', va='top', color='y', bbox=bbox_props, fontsize='x-large') # inferred background axes[3].imshow(beta.reshape(nrows, ncols), interpolation='nearest', cmap=plt.cm.gray) axes[3].annotate(r'$\hat{\beta}$', (0, 0), xycoords='data', xytext=(5, -5), textcoords='offset points', ha='left', va='top', color='y', bbox=bbox_props, fontsize='x-large') fig.tight_layout() return fig, axes
Example #19
Source File: plotting.py From PyFNND with GNU General Public License v3.0 | 4 votes |
def ground_truth_1D(F, n_hat, C_hat, theta_hat, n, C, theta, dt): sigma_hat, alpha_hat, beta_hat, lamb_hat, gamma_hat = theta_hat sigma, alpha, beta, lamb, gamma = theta alpha, beta = (np.atleast_1d(a) for a in (alpha, beta)) fig = plt.figure() gs = plt.GridSpec(4, 1) ax1 = fig.add_subplot(gs[0:2]) ax2 = fig.add_subplot(gs[2:3], sharex=ax1) ax3 = fig.add_subplot(gs[3:4], sharex=ax1) axes = np.array([ax1, ax2, ax3]) t = np.arange(F.shape[1]) * dt F_real = alpha[:, None] * C[None, :] + beta[:, None] F_hat = alpha_hat[:, None] * C_hat[None, :] + beta_hat[:, None] axes[0].hold(True) # noisy fluorescence axes[0].plot(t, F.sum(0), '-k', alpha=0.5, label=r'$F$') # fitted fluorescence axes[0].plot(t, F_hat.sum(0), '-b', lw=1, label=r'$\hat{\alpha}\hat{C}+\hat{\beta}$') # true noise-free fluorescence axes[0].plot(t, F_real.sum(0), '-r', lw=2, label=r'$\alpha C+\beta$') axes[0].legend(loc=1, ncol=3, fancybox=True, fontsize='large') axes[0].tick_params(labelbottom=False) # true spikes axes[1].plot(t, n, '-k', label=r'$n$') axes[1].set_ylabel(r'$n$', fontsize='large') axes[1].tick_params(labelbottom=False) # inferred spike probabilities axes[2].plot(t, n_hat, '-k', label=r'$\hat{n}$') axes[2].set_xlabel('Time (s)') axes[2].set_ylabel(r'$\hat{n}$', fontsize='large') axes[2].set_xlim(0, t[-1]) fig.tight_layout() return fig, axes
Example #20
Source File: LSDMap_DrainageCapture.py From LSDMappingTools with MIT License | 4 votes |
def PlotBasinPerimeter(DataDirectory, fname_prefix, size_format='ESURF', FigFormat='png'): """ Make a plot of the basin perimeter ordered by the outlet Args: DataDirectory (str): the data directory fname_prefix (str): filename of the DEM without extension size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf). FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command. Author: FJC """ # check if a directory exists for the perimeter plots. If not then make it. this_dir = DataDirectory+'basin_perimeters/' if not os.path.isdir(this_dir): os.makedirs(this_dir) # Set up fonts for plots label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) #l_pad = -40 elif size_format == "big": fig = plt.figure(1, facecolor='white',figsize=(16,9)) #l_pad = -50 else: fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2)) #l_pad = -35 PerimeterDF = Helper.ReadPerimeterCSV(DataDirectory, fname_prefix) gs = plt.GridSpec(100,100,bottom=0.15,left=0.05,right=0.95,top=0.95) ax = fig.add_subplot(gs[5:100,10:95]) # plot the data ax.plot(PerimeterDF['node_key'],PerimeterDF['elevation']) # set the axis labels ax.set_xlabel('Perimeter node ordered from outlet') ax.set_ylabel('Node elevation') newFilename = this_dir+fname_prefix+"_basin_perimeter."+FigFormat plt.savefig(newFilename,format=FigFormat,dpi=300) ax.cla() plt.close(fig)
Example #21
Source File: plot.py From PyDDM with MIT License | 4 votes |
def plot_decision_variable_distribution(model, conditions={}, resolution=.1, figure=None): """Show the distribution of the decision variable. Show the intermediate distributions for the decision variable. `model` should be the model to plot, and `conditions` should be the conditions over which to plot it. `resolution` should be the timestep of the plot (NOT of the model). Optionally, `figure` is an existing figure on which to make the plot. Also, note that for clarity of the visualization, the square root of the distribution is plotted instead of the distribution itself. Without this, it is quite difficult to see the evolving distribution because the distribution of histogram values is highly skewed. Finally, note that this routine always uses the implicit method because it gives the most reliable histograms for the decision variable. (Crank-Nicoloson tends to oscillate.) """ # Generate the distributions. Note that this is extremely # inefficient (it is O(n) with resolution and should be O(1) with # resolution) so this should be improved someday... s = model.solve_numerical_implicit(conditions=conditions, return_evolution=True) hists = s.pdf_evolution() print(np.max(hists)) top = s.pdf_corr() bot = s.pdf_err() # Plot the output f = figure if figure is not None else plt.figure() # Set up three axes, with one in the middle and two on the borders gs = plt.GridSpec(7, 1, wspace=0, hspace=0) ax_main = f.add_subplot(gs[1:-1,0]) ax_top = f.add_subplot(gs[0,0], sharex=ax_main) ax_bot = f.add_subplot(gs[-1,0], sharex=ax_main) # Show the relevant data on those axes ax_main.imshow(np.log(.0001+np.flipud(hists)), aspect='auto', interpolation='bicubic') ax_top.plot(range(0, len(model.t_domain())), top, clip_on=False) ax_bot.plot(range(0, len(model.t_domain())), -bot, clip_on=False) # Make them look decent ax_main.axis("off") ax_top.axis("off") ax_bot.axis("off") # Set axes to be the right size maxval = np.max([top, bot]) ax_top.set_ylim(0, maxval) ax_bot.set_ylim(-maxval, 0) return f
Example #22
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def pdf_from_bin_one_col(ldf, DataDirectory, saveName = "BasicPDF_", column = "elevation", size_format = "ESURF", pdf_col = "diff", combine_diff_sign = False, argsort = False ): """ Produce some simple pdf plots from a dict of pandas dataframe. Arg: Returns: nothing, but produce a plot. Author: BG """ for inch in ldf: plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size if(combine_diff_sign): ldf[inch]["diff"][ldf[inch]["sign"] == -1] = -ldf[inch]["diff"][ldf[inch]["sign"] == -1] data = np.array(ldf[inch][pdf_col].values) # make a figure if size_format == "geomorphology": fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(1, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:100,5:95]) print(data.shape) if(data.shape[0]>0): ax1.hist(data, 100, normed=1, facecolor='green', alpha=0.75) ax1.set_ylabel("PDF") ax1.set_xlabel("elevation by " + pdf_col) ax1.set_xlim(-100,100) plt.savefig(DataDirectory+saveName+inch+"_"+column+".png",dpi=500)
Example #23
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def pdf_from_bin(ldf, DataDirectory, saveName = "BasicPDF_", column = "elevation", size_format = "ESURF" ): """ Produce some simple pdf plots from a list of pandas dataframe. Arg: Returns: nothing, but produce a plot. Author: BG """ for inch in ldf: plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(2, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:50,10:95]) ax2 = fig.add_subplot(gs[50:100,10:95]) ax2.scatter(ldf[inch]["diff"],norm.pdf(ldf[inch]["diff"]), s = 1.5, lw = 0) ax1.scatter(ldf[inch]["ratio"],norm.pdf(ldf[inch]["ratio"]), s = 1.5, lw = 0) ax2.set_ylabel("PDF (Diff)") ax1.set_ylabel("PDF (Ratio)") ax2.set_xlabel("Diff/ratio binned by " + column + "_" + inch) plt.savefig(DataDirectory+saveName+inch+"_"+column+".png",dpi=500)
Example #24
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def violin_by_bin(ldf, DataDirectory, saveName = "Violin", column = "elevation", size_format = "ESURF"): """ Will plot violin from a list of bins. NOT READY YET. Author: BG matplotlib description: Violin plots are similar to histograms and box plots in that they show an abstract representation of the probability distribution of the sample. Rather than showing counts of data points that fall into bins or order statistics, violin plots use kernel density estimation (KDE) to compute an empirical distribution of the sample. That computation is controlled by several parameters. This example demonstrates how to modify the number of points at which the KDE is evaluated (``points``) and how to modify the band-width of the KDE (``bw_method``). For more information on violin plots and KDE, the scikit-learn docs have a great section: http://scikit-learn.org/stable/modules/density.html """ plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(2, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:50,10:95]) ax2 = fig.add_subplot(gs[50:100,10:95]) ax2.set_ylabel("Ratio") ax1.set_ylabel("Diff") ax2.set_xlabel(column) plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
Example #25
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_pdf_diff_ratio(df, DataDirectory, saveName = "pdf_diff_ratio", save_fmt = ".png", size_format = "ESURF", xlim =[]): """ Basic plot to have a general view of the knickpoints: flow distance against ratio and diff colored by elevation Args: PointData: A PointData object DataDirectory: Where the data is saved saveName: save name returns: Nothing, sorry. Author: BG """ plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(2, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:50,10:95]) ax2 = fig.add_subplot(gs[50:100,10:95]) ax1.scatter(df["ratio"],norm.pdf(df["ratio"]),lw =0, s = 1, c = "red") ax1.set_ylabel("Ratio") ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0) ax1.spines['bottom'].set_visible(False) ax2.scatter(df["diff"],norm.pdf(df["diff"]),lw =0, s = 1, c = "red") ax2.set_ylabel("Diff") ax2.set_xlabel("PDF") #'###### Setting the limits if(xlim != []): ax2.set_xlim(xlim[0],xlim[1]) ax1.set_xlim(xlim[0],xlim[1]) #ax2.tick_params(axis = 'x', labelsize = 6) #ax1.set_xticks([4,5,6,7,8,9,10]) #ax2.set_xticks([4,5,6,7,8,9,10]) #ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"]) plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
Example #26
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_basic_Z(PointData, DataDirectory, saveName = "Basic_Z", save_fmt = ".png", size_format = "ESURF", log_data = False): """ Basic plot to have a general view of the knickpoints: flow distance against ratio and diff colored by elevation Args: PointData: A PointData object DataDirectory: Where the data is saved saveName: save name returns: Nothing, sorry. Author: BG """ plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(2, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 diff = PointData.QueryData("diff") ratio = PointData.QueryData("ratio") Z = PointData.QueryData("elevation") gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:50,10:95]) ax2 = fig.add_subplot(gs[50:100,10:95]) if(log_data): print("I am logging the data") diff = np.log10(diff) ratio = np.log10(ratio) sign = PointData.QueryData("sign") ax1.scatter(Z,ratio, s=0.7, lw = 0, c = sign) ax1.set_ylabel("Ratio") ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0) ax1.spines['bottom'].set_visible(False) ax2.scatter(Z,diff,s=0.7, lw = 0, c = sign) ax2.set_ylabel("Diff") ax2.set_xlabel("elevation") #ax2.tick_params(axis = 'x', labelsize = 6) #ax1.set_xticks([4,5,6,7,8,9,10]) #ax2.set_xticks([4,5,6,7,8,9,10]) #ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"]) plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
Example #27
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_basic_DA(PointData, DataDirectory, saveName = "Basic_DA", save_fmt = ".png", size_format = "ESURF", log_data = False): """ Basic plot to have a general view of the knickpoints: drainage area against ratio and diff colored by elevation Args: PointData: A PointData object DataDirectory: Where the data is saved saveName: save name returns: Nothing, sorry. Author: BG """ plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(2, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 diff = PointData.QueryData("diff") ratio = PointData.QueryData("ratio") DA = PointData.QueryData("drainage area") gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax1 = fig.add_subplot(gs[10:50,10:95]) ax2 = fig.add_subplot(gs[50:100,10:95]) if(log_data): print("I am logging the data") diff = np.log10(diff) ratio = np.log10(ratio) elevation = PointData.QueryData("elevation") DA = np.log10(DA) ax1.scatter(DA,ratio, s=0.7, lw = 0, c = elevation) ax1.set_ylabel("Ratio") ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0) ax1.spines['bottom'].set_visible(False) ax2.scatter(DA,diff,s=0.7, lw = 0, c = elevation) ax2.set_ylabel("Diff") ax2.set_xlabel("Drainage area") #ax2.set_xticks([1,2,3,4,5,6,7]) ax2.tick_params(axis = 'x', labelsize = 6) ax1.set_xticks([4,5,6,7,8,9,10]) ax2.set_xticks([4,5,6,7,8,9,10]) ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"]) plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
Example #28
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_diff_ratio(PointData, DataDirectory, saveName = "Basic_diff_ratio", save_fmt = ".png", size_format = "ESURF", log_data = False): """ Basic plot to have a general view of the knickpoints: diff against ratio colored by elevation Args: PointData: A PointData object DataDirectory: Where the data is saved saveName: save name returns: Nothing, sorry. Author: BG """ plt.clf() label_size = 10 rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Liberation Sans'] rcParams['font.size'] = label_size # make a figure if size_format == "geomorphology": fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5)) l_pad = -40 elif size_format == "big": fig = plt.figure(1, facecolor='white',figsize=(16,9)) l_pad = -50 else: fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5)) l_pad = -35 gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0) ax = fig.add_subplot(gs[25:100,10:95]) diff = PointData.QueryData("diff") ratio = PointData.QueryData("ratio") if(log_data): print("I am logging the data") diff = np.log10(diff) ratio = np.log10(ratio) elevation =PointData.QueryData("elevation") ax.scatter(diff,ratio, s=0.5, lw = 0, c = elevation) ax.set_xlabel("Diff") ax.set_ylabel("Ratio") plt.savefig(DataDirectory+saveName+save_fmt,dpi=500)
Example #29
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_chi_profiles(self, method = "deriv_ksn", group = "source_key"): """ Statistical plot to calibrate the KDE per rivers """ print("I am going to print the chi profile per river/basins depending on what you asked") # check if a directory exists for the chi plots. If not then make it. svdir = self.fpath+'river_plots/' if not os.path.isdir(svdir): os.makedirs(svdir) if method == "deriv_ksn": out_method = "out_KDE_ksn" elif method == "deriv_delta_ksn": out_method = "out_KDE_dksn" for source in self.df[group].unique(): if not np.isnan(source): this_df = self.df[self.df[group] == source] this_MCdf = self.CNMC[self.CNMC[group] == source] fig = plt.figure(2, facecolor='white',figsize=(9,5)) gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95) ax1 = fig.add_subplot(gs[0:100,0:90]) ax2 = fig.add_subplot(gs[0:100,0:90], facecolor = "None") axa = fig.add_subplot(gs[0:100,90:100]) cax = fig.add_subplot(gs[0:100,91:95]) ax2.scatter(this_MCdf["chi"], this_MCdf["elevation"], s = 1, lw = 0, c = this_MCdf["source_key"], cmap = "RdBu_r") ou = self.final_out[self.final_out[group] == source] cb = ax1.scatter(ou["chi"], ou["elevation"], s = 50, c = ou["ksn"], lw = 0,marker = "o", label = "Knickpoint", cmap = "RdBu_r") ax2.set_xlabel(r'$\chi$') ax2.set_ylabel("elevation (m)") #ax2.set_xlim(0,1000) #ax2.scatter(this_df["deriv_delta_ksn"], this_df["KDE_delta_ksn"], s = 100, marker = "x", lw = 1, c = "k",label = "KDE d2(ksn)/d(chi)") ax1.xaxis.set_visible(False) ax1.yaxis.set_visible(False) ax1.set_xlim(ax2.get_xlim()) ax1.set_ylim(ax2.get_ylim()) ax1.set_title(group + " #" +str(source)) ax1.legend(loc = 2) plt.colorbar(cb,cax = cax, ax = axa) axa.axis("off") plt.savefig(svdir+"Chi_profile_"+ str(group)+ "_" + str(source) + "_out_" + method+ ".png", dpi = 300) plt.clf()
Example #30
Source File: LSDMap_KnickpointPlotting_old.py From LSDMappingTools with MIT License | 4 votes |
def plot_mchi_segments(self, method = "deriv_ksn", group = "source_key"): """ Statistical plot to calibrate the KDE per rivers """ print("I am going to plot the m_chi/ksn segments to check my knickpoints") # check if a directory exists for the chi plots. If not then make it. svdir = self.fpath+'river_plots/' if not os.path.isdir(svdir): os.makedirs(svdir) if method == "deriv_ksn": out_method = "out_KDE_ksn" elif method == "deriv_delta_ksn": out_method = "out_KDE_dksn" for source in self.df[group].unique(): if not np.isnan(source): this_df = self.df[self.df[group] == source] this_MCdf = self.CNMC[self.CNMC[group] == source] fig = plt.figure(2, facecolor='white',figsize=(9,5)) gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95) ax1 = fig.add_subplot(gs[0:100,0:100]) ax2 = fig.add_subplot(gs[0:100,0:100], facecolor = "None") ax2.scatter(this_MCdf["chi"], this_MCdf["m_chi"], s = 1, lw = 1, c = this_MCdf["m_chi"], cmap = "RdBu_r") ou = this_df[this_df[out_method]==1] ax1.scatter(ou["chi"], ou["ksn"], s = 40, c = ou["source_key"], lw = 1,marker = "+", label = "outliers before merging", cmap = "jet") ax1.vlines(ou["chi"], ou["ksn"].min() , ou["ksn"].max(), linestyles = "dashdot", lw = 0.5 ) ouf = self.final_out[self.final_out[group] == source] ax1.scatter(ouf["chi"], ouf["ksn"], marker = "x", s = 50, lw = 1,c = "g", label = "outliers after merging" ) ax2.set_xlabel(r'$\chi$') ax2.set_ylabel(r"$M_\chi$") #ax2.set_xlim(0,1000) #ax2.scatter(this_df["deriv_delta_ksn"], this_df["KDE_delta_ksn"], s = 100, marker = "x", lw = 1, c = "k",label = "KDE d2(ksn)/d(chi)") ax1.xaxis.set_visible(False) ax1.yaxis.set_ticks_position("right") ax1.yaxis.set_label_position("right") ax1.set_ylabel(r'$\Delta K_{sn}$') ax1.set_xlim(ax2.get_xlim()) ax1.legend() plt.title(group + " #" +str(source)) plt.savefig(svdir+"M_chi_plot_"+ str(group)+ "_" + str(source) + "_out_" + method+ ".png", dpi = 300) plt.clf()