本文整理匯總了Python中matplotlib.pyplot.GridSpec方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.GridSpec方法的具體用法?Python pyplot.GridSpec怎麽用?Python pyplot.GridSpec使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.GridSpec方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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])
示例2: _create_likelihood_axis
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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
示例3: plot_fp_analysis
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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)
示例4: DEBUG_print_ksn_filters
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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()
示例5: DEBUG_print_ksn_outliers
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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()
示例6: DEBUG_print_KDE
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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()
示例7: plot_base_to_lip_from_knickpoint_profile
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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()
示例8: __enter__
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
def __enter__(self):
plt.ion()
plt.figure(figsize=self.figsize)
self.gs = plt.GridSpec(*self.grid)
return self
示例9: correlation_plots
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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))
示例10: plot_image_components
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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")
示例11: gridspec
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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
示例12: __init__
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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
示例13: plot_phase_portraits
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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])
示例14: plot_fit
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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
示例15: create_figure
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import GridSpec [as 別名]
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:])