本文整理汇总了Python中mpl_toolkits.axes_grid1.inset_locator.inset_axes函数的典型用法代码示例。如果您正苦于以下问题:Python inset_axes函数的具体用法?Python inset_axes怎么用?Python inset_axes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inset_axes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: make_colorbar
def make_colorbar(fig,orientation='horizontal',label=''):
# plt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)
if orientation == 'horizontal':
cbar_ax = fig['fig_handle'].add_axes([0.2, 0,0.6,1])
axins = inset_axes(cbar_ax,
width="100%", # width = 10% of parent_bbox width
height="5%", # height : 50%
loc=10,
bbox_to_anchor=(0, -0.01, 1 , 0.15),
bbox_transform=cbar_ax.transAxes,
borderpad=0,
)
else:
cbar_ax = fig['fig_handle'].add_axes([0, 0.2,1,0.6])
axins = inset_axes(cbar_ax,
width="5%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc=6,
bbox_to_anchor=(1.01, 0, 0.15, 1),
bbox_transform=cbar_ax.transAxes,
borderpad=0,
)
cbar_ax.get_xaxis().tick_bottom()
cbar_ax.axes.get_yaxis().set_visible(False)
cbar_ax.axes.get_xaxis().set_visible(False)
cbar_ax.set_frame_on(False)
cbar=plt.colorbar(cax=axins, orientation=orientation,label=label)
levels = fig['cont_handle'].levels
cbar.set_ticks(levels)
cbar.set_ticklabels(format_ticks(levels,decimals=2))
return cbar
开发者ID:hzshao,项目名称:pycosmo,代码行数:34,代码来源:utilities.py
示例2: insertStruct
def insertStruct(ax,**args):
import matplotlib.pyplot as plt
colors = ['r','g','b']
#if not os.path.exists('struct.png'):
generateStructPNG(**args)
image = plt.imread('struct.png')
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
axin = inset_axes(ax,
width=args['width'], # width = 30% of parent_bbox
height=args['height'], # height : 1 inch
loc=args['loc'])
im = axin.imshow(image)
axin.axis('off')
#axins.axis('equal')
#axins.axis('tight')
#axins.set_xticks([])
#axins.set_yticks([])
axin.annotate(s='',xy=(0.4,0),xytext=(0,0),xycoords='axes fraction',
arrowprops=dict(width=2.0,color=colors[0]))
axin.text(0.45,-0.02,'x',fontsize='xx-large',transform=axin.transAxes)
axin.text(0,0.45,'y',fontsize='xx-large',transform=axin.transAxes)
axin.text(0.22,0.22,'z',fontsize='xx-large',transform=axin.transAxes)
axin.annotate(s='',xy=(0,0.4),xytext=(0,0),xycoords='axes fraction',
arrowprops=dict(width=2.0,color=colors[1]))
axin.annotate(s='',xy=(0.2,0.2),xytext=(0,0),xycoords='axes fraction',
arrowprops=dict(width=2.0,color=colors[2]))
return axin, im
开发者ID:charleslian,项目名称:PYRAMIDS,代码行数:31,代码来源:PlotUtility.py
示例3: setup_axes
def setup_axes(fig, header):
gh = pywcsgrid2.GridHelper(wcs=header)
gh.locator_params(nbins=3)
g = axes_grid.ImageGrid(fig, 111,
nrows_ncols=(2,3),
ngrids=None, direction='row',
axes_pad=0.02,
add_all=True,
share_all=True,
aspect=True,
label_mode='L',
cbar_mode=None,
axes_class=(pywcsgrid2.Axes, dict(grid_helper=gh)))
#make colorbar
ax = g[-1]
cax = inset_axes(ax,
width="8%",
height="200%",
loc=3,
bbox_to_anchor=(1.02,0,1,1),
bbox_transform=ax.transAxes,
borderpad=0.
)
return g, cax
开发者ID:TuahZh,项目名称:tuahcube,代码行数:29,代码来源:channel_maps_co13_v2.py
示例4: initialize_subplots
def initialize_subplots(self, overview=False):
## p = AlignmentPlot(self.figure, 212, aln=self.aln)
p = AlignmentPlot(self.figure, 111, aln=self.aln, app=self)
self.detail = self.figure.add_subplot(p)
self.detail.plot_aln()
if overview:
self.overview = inset_axes(
self.detail, width="30%", height="20%", loc=1
)
self.overview.xaxis.set_major_locator(NullLocator())
self.overview.yaxis.set_major_locator(NullLocator())
self.overview.imshow(
self.detail.array, interpolation='nearest', aspect='auto',
origin='lower'
)
rect = UpdatingRect(
[0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5
)
self.overview.zoomrect = rect
rect.target = self.detail
self.detail.callbacks.connect('xlim_changed', rect)
self.detail.callbacks.connect('ylim_changed', rect)
self.overview.add_patch(rect)
rect(self.overview)
else:
self.overview = None
开发者ID:ChriZiegler,项目名称:ivy,代码行数:27,代码来源:alignment.py
示例5: setup_axes02
def setup_axes02(fig, rect, zoom=0.35, loc=4, axes_class=None, axes_kwargs=None):
"""
ax2 is an inset axes, but shares the x- and y-axis with ax1.
"""
from mpl_toolkits.axes_grid1.axes_grid import ImageGrid, CbarAxes
import mpl_toolkits.axes_grid1.inset_locator as inset_locator
grid = ImageGrid(fig, rect,
nrows_ncols=(1,1),
share_all=True, aspect=True,
label_mode='L', cbar_mode="each",
cbar_location='top', cbar_pad=None, cbar_size='5%',
axes_class=(axes_class, axes_kwargs))
ax1 = grid[0]
kwargs = dict(zoom=zoom, loc=loc)
ax2 = inset_locator.zoomed_inset_axes(ax1,
axes_class=axes_class,
axes_kwargs=axes_kwargs,
**kwargs
)
cax = inset_locator.inset_axes(ax2, "100%", 0.05, loc=3,
borderpad=0.,
bbox_to_anchor=(0, 0, 1, 0),
bbox_transform=ax2.transAxes,
axes_class=CbarAxes,
axes_kwargs=dict(orientation="top"),
)
ax2.cax = cax
return grid[0], ax2
开发者ID:leejjoon,项目名称:matplotlib_astronomy_gallery,代码行数:35,代码来源:tycho_hst_kpno.py
示例6: setup_axes
def setup_axes(fig, header):
gh = pywcsgrid2.GridHelper(wcs=header)
gh.locator_params(nbins=3)
g = axes_grid.ImageGrid(
fig,
111,
nrows_ncols=(5, 4),
ngrids=None,
direction="row",
axes_pad=0.02,
add_all=True,
share_all=True,
aspect=True,
label_mode="L",
cbar_mode=None,
axes_class=(pywcsgrid2.Axes, dict(grid_helper=gh)),
)
# make colorbar
ax = g[-1]
cax = inset_axes(
ax,
width="8%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc=3,
bbox_to_anchor=(1.01, 0, 1, 1),
bbox_transform=ax.transAxes,
borderpad=0.0,
)
return g, cax
开发者ID:leejjoon,项目名称:matplotlib_astronomy_gallery,代码行数:33,代码来源:ic443_channel_map.py
示例7: plot_vp_vs_profile
def plot_vp_vs_profile(
self, nsamp_per_layer=10, depth=False, crust_zoom_depth_km=None,
vlim_crust=(2.5, 8.), title=None, show=True,
inset_axes_kwargs={'width': '30%', 'height': '30%', 'loc': 3}):
figure, ax = plt.subplots()
colormap = {'VP': 'k', 'VS': 'r'}
if crust_zoom_depth_km:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
axins = inset_axes(ax, **inset_axes_kwargs)
axins.yaxis.tick_right()
axins.xaxis.tick_top()
for param in ['VP', 'VS']:
p = np.zeros((self.nregions, nsamp_per_layer))
x = np.zeros((self.nregions, nsamp_per_layer))
for iregion in range(self.nregions):
x[iregion, :] = np.linspace(
self.discontinuities[iregion],
self.discontinuities[iregion+1], nsamp_per_layer)
centroid = np.ones(nsamp_per_layer) * \
np.mean(self.discontinuities[iregion:iregion+2])
p[iregion, :] = self.get_elastic_parameter(
param, x[iregion, :], centroid)
if depth:
xx = (1 - x.flatten()) * self.scale / 1e3
else:
xx = x.flatten() * self.scale / 1e3
ax.plot(p.flatten() / 1e3, xx, label='%s' % (param,),
color=colormap[param])
if crust_zoom_depth_km:
axins.plot(p.flatten() / 1e3, xx, color=colormap[param])
ax.legend(loc='best')
ax.set_xlabel('velocity / [km / s]')
ax.set_title(title if title is not None else self.name)
if crust_zoom_depth_km:
axins.set_xlim(*vlim_crust)
axins.set_ylim(0, crust_zoom_depth_km)
if depth:
axins.invert_yaxis()
if depth:
ax.set_ylim(0., self.scale / 1e3)
ax.invert_yaxis()
ax.set_ylabel('Depth / km')
else:
ax.set_ylim(0., self.scale / 1e3 * 1.01)
ax.set_ylabel('Radius / km')
if show: # pragma: no cover
plt.show()
else:
return figure
开发者ID:SalvusHub,项目名称:salvus_mesher,代码行数:60,代码来源:models_1D.py
示例8: chickling_pd_zoom
def chickling_pd_zoom(shotno, date=time.strftime("%Y%m%d")):
fname, data = file_finder(shotno,date)
data_1550 = data[0]['phasediff_co2'][100:]
plot_time = np.linspace(0,1,data_1550.size)
fig, ax = plt.subplots()
ax.plot(plot_time, data_1550)
ax.set_ybound(max(data_1550)+0.6, min(data_1550)-0.01)
plt.title("Phase Difference for shot " + str(shotno) + " Date " + str(date))
plt.xlabel("Time, s")
plt.ylabel("Phase Difference, Radians")
x_zoom_bot = int(data_1550.size*(10/100))
x_zoom_top = int(data_1550.size*(15/100))
x1, x2, y1, y2 = 0.1, 0.15, max(data_1550[x_zoom_bot:x_zoom_top])+0.01, min(data_1550[x_zoom_bot:x_zoom_top])-0.01
axins = inset_axes(ax, 4.3,1, loc=9)
axins.plot(plot_time[x_zoom_bot:x_zoom_top], data_1550[x_zoom_bot:x_zoom_top])
axins.set_xlim(x1, x2)
if y1 < y2:
axins.set_ylim(y1, y2)
else:
axins.set_ylim(y2, y1)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5",lw=2)
plt.show()
开发者ID:chickling1994,项目名称:Diss-05-05-2018,代码行数:34,代码来源:chickling_additions_2.py
示例9: QQplot
def QQplot(obs, Q, pos, color=None, ax=None, axins=True):
if not color:
color='blue'
if ax is None:
ax = plt.gca()
mean = np.mean(obs, axis=0)
# obs = np.random.multivariate_normal(mean, S, 3000)
md2 = np.diag(np.dot(np.dot(obs - mean, Q), (obs -mean).T))
sorted_md2 = np.sort(md2)
v = (np.arange(1, obs.shape[0] + 1) - 0.375) / (obs.shape[0] + 0.25)
quantiles = scipy.stats.chi2.ppf(v, df=obs.shape[1])
# axins = inset_axes(ax, width="60%", height=1., loc=2)
if axins:
axins = inset_axes(ax, width="60%", height=1., loc=2)
axins.axis(pos)
axins.get_xaxis().tick_bottom()
axins.get_yaxis().tick_left()
# Remove the tick marks; they are unnecessary with the tick lines we just plotted.
axins.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="off", left="off", right="off", labelleft="off")
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
axins.xaxis.set_major_locator(MaxNLocator(nbins=1, prune='lower'))
axins.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3)
axins.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5)
ax.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3)
ax.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5)
_clean_axes(ax)
开发者ID:jcasademont,项目名称:datacenter,代码行数:33,代码来源:plot.py
示例10: lax
def lax(self):
"""
Returns the legend axes, creating it only on demand by creating a 2"
by 2" inset axes that has no grid, ticks, spines or face frame (e.g
is mostly invisible). The legend can then be drawn on this axes.
"""
if inset_locator is None:
raise YellowbrickValueError((
"intercluster distance map legend requires matplotlib 2.0.2 or greater "
"please upgrade matplotlib or set legend=False on the visualizer"
))
lax = inset_locator.inset_axes(
self.ax, width=self.legend_size, height=self.legend_size, loc=self.legend_loc
)
lax.set_frame_on(False)
lax.set_facecolor("none")
lax.grid(False)
lax.set_xlim(-1.4,1.4)
lax.set_ylim(-1.4,1.4)
lax.set_xticks([])
lax.set_yticks([])
for name in lax.spines:
lax.spines[name].set_visible(False)
return lax
开发者ID:DistrictDataLabs,项目名称:yellowbrick,代码行数:28,代码来源:icdm.py
示例11: pl_inset_title_box
def pl_inset_title_box(ax,title,bwidth="20%",location=1):
"""
Function that puts title of subplot in a box
:ax: Name of matplotlib axis to add inset title text box too
:title: 'string to put inside text box'
:returns: @todo
"""
import matplotlib.pyplot as plt
#for inset axes
#hacked from:
#http://matplotlib.org/examples/axes_grid/inset_locator_demo.html
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
axins = inset_axes(ax,
width=bwidth, # width = 30% of parent_bbox
height=.30, # height : 1 inch
loc=location)
plt.setp(axins.get_xticklabels(), visible=False)
plt.setp(axins.get_yticklabels(), visible=False)
axins.set_xticks([])
axins.set_yticks([])
axins.text(0.5,0.3,title,
horizontalalignment='center',
transform=axins.transAxes,size=10)
开发者ID:chrisb13,项目名称:mkmov,代码行数:28,代码来源:scf.py
示例12: plot_some_profile
def plot_some_profile(self, data_attr, integration,
spatial=None, ax=None, scale=False,
log=False, spa_average=False, title=None,
**kwargs):
plot_hist = kwargs.pop('plot_hist', False)
savename = kwargs.pop('savename', False)
spec = self.get_integration(data_attr, integration)
if 'dark' in data_attr:
nints = self.n_darks
else:
nints = self.n_integrations
if scale:
spec = spec / self.scaling_factor
if spatial is None:
# if no spatial bin given, take the middle one
spatial = self.spatial_size // 2
if title is None:
if not spa_average:
title = ("Profile of {} at spatial: {}, integration {} of {}"
.format(data_attr, spatial, integration, nints))
else:
title = ("Profile of {}, spatial mean. Integration {} of {}"
.format(data_attr, integration, nints))
if ax is None:
fig, ax = plt.subplots()
fig.suptitle(self.plottitle, fontsize=12)
if log:
func = ax.semilogy
else:
func = ax.plot
if spa_average:
data = spec.mean(axis=0)
else:
data = spec[spatial]
func(self.wavelengths[spatial], data, **kwargs)
ax.set_xlim((self.wavelengths[spatial][0],
self.wavelengths[spatial][-1]))
ax.set_title(title, fontsize=11)
ax.set_xlabel("Wavelength [nm]")
if log:
ax.set_ylabel("log(DN/s)")
else:
ax.set_ylabel('DN/s')
if plot_hist:
in_axes = inset_axes(ax, width="20%", height="20%",
loc=2)
in_axes.hist(spec.ravel(), bins=20, normed=True, log=True)
plt.setp(in_axes.get_xticklabels(), visible=False)
plt.setp(in_axes.get_yticklabels(), visible=False)
in_axes.grid('off')
if savename:
ax.get_figure().savefig(savename, dpi=100)
return ax
开发者ID:gitter-badger,项目名称:iuvs,代码行数:60,代码来源:io.py
示例13: plot_hist
def plot_hist(ax, spec):
in_axes = inset_axes(ax, width="20%", height="20%",
loc=2)
in_axes.hist(spec.ravel(), bins=20, normed=True)
plt.setp(in_axes.get_xticklabels(), visible=False)
plt.setp(in_axes.get_yticklabels(), visible=False)
in_axes.grid('off')
开发者ID:gitter-badger,项目名称:iuvs,代码行数:7,代码来源:io.py
示例14: compare_matrices
def compare_matrices(matrix1, matrix2, logplot=False):
"""Make a plot comparing two matrices"""
fig = plt.figure(1, [6, 3])
# first subplot
subplot1 = fig.add_subplot(121)
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
axins1 = inset_axes(subplot1,
width="50%",
height="5%",
loc=1)
if (logplot == True):
image1 = subplot1.imshow(np.log10(matrix1))
else:
image1 = subplot1.imshow(matrix1)
plt.colorbar(image1, cax=axins1, orientation="horizontal",
ticks=[1, 2, 3])
axins1.xaxis.set_ticks_position("bottom")
# second subplot
subplot2 = fig.add_subplot(122)
axins = inset_axes(subplot2,
width="5%",
height="50%",
loc=3,
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=subplot2.transAxes,
borderpad=0,
)
# Controlling the placement of the inset axes is basically same as that
# of the legend. you may want to play with the borderpad value and
# the bbox_to_anchor coordinate.
if (logplot == True):
image2 = subplot2.imshow(np.log10(matrix2))
else:
image2 = subplot2.imshow(matrix2)
plt.colorbar(image2, cax=axins, ticks=[1, 2, 3])
plt.draw()
plt.show()
开发者ID:eric-switzer,项目名称:bayes_flux,代码行数:46,代码来源:utilities.py
示例15: plotBinned
def plotBinned(cls_in,dcls_in,l_out,bins,output_prefix,title=None,theory=None,dtheory=None,delta=None,cosmic=None):
fig=plt.figure(1)
plt.clf()
ax=fig.add_subplot(111)
good_l=np.logical_and( l_out > 25 , l_out <= 250)
if not (theory is None) :
ax.plot(l_out,theory,'r-')
if not (cosmic is None) :
ax.fill_between(l_out,(theory-cosmic),(theory+cosmic),alpha=.5,facecolor='red')
#plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red')
if not (dtheory is None) :
ax.errorbar(l_out,theory,yerr=dtheory,color='red')
ax.errorbar(l_out,cls_in,yerr=dcls_in,color='black',fmt='k.',linestyle='None')
if not (delta is None) :
ax.fill_between(l_out,cls_in-delta,cls_in+delta,color='gray',alpha=0.5)
#plt.xlim([0,np.max(l_out+bins)])
#plt.ylim([np.min(b_cl['llcl']-b_dcl['llcl']),np.max(b_cl['llcl']+b_dcl['llcl'])])
ax.set_xlabel('$\ell$')
ax.set_ylabel('$\\frac{\ell(\ell+1)}{2\pi}C_{\ell}\ \\frac{\mu K^{2}}{m^{4}}$')
#ax.set_xlim([0,np.max(l_out+bins)])
# ax.autoscale(axis='y',tight=True)
if title:
ax.set_title(title)
else:
ax.set_title('Binned Cls {:02d}'.format(bins))
axins = inset_axes(ax,width="50%",height="30%",loc=9)
if not (theory is None) :
axins.plot(l_out[good_l],theory[good_l],'r-')
if not (cosmic is None) :
axins.fill_between(l_out[good_l],(theory-cosmic)[good_l],(theory+cosmic)[good_l],alpha=.5,facecolor='red')
#plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red')
if not (dtheory is None) :
axins.errorbar(l_out[good_l],theory[good_l],yerr=dtheory[good_l],color='red')
axins.errorbar(l_out[good_l],cls_in[good_l],yerr=dcls_in[good_l],color='black',fmt='k.',linestyle='None')
if not (delta is None) :
axins.fill_between(l_out[good_l],(cls_in-delta)[good_l],(cls_in+delta)[good_l],color='gray',alpha=0.5)
axins.set_xlim(25,255)
axins.set_yscale('log')
#axins.set_ylim(ymax=1e5)
#axins.set_ylim(-1e5,1e5)
mark_inset(ax,axins,loc1=2,loc2=4,fc='none',ec='0.1')
#axins.set_xlim([25,250])
axins.autoscale('y',tight=True)
plt.draw()
#plt.show(block=True)
fig.savefig(output_prefix+'_linear_{:02d}.eps'.format(bins),format='eps')
fig.savefig(output_prefix+'_linear_{:02d}.png'.format(bins),format='png')
ax.set_yscale('log')
fig.savefig(output_prefix+'_log_{:02d}.eps'.format(bins),format='eps')
fig.savefig(output_prefix+'_log_{:02d}.png'.format(bins),format='png')
开发者ID:mkolopanis,项目名称:python,代码行数:57,代码来源:plot_binned.py
示例16: reliability_diagram
def reliability_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability",
ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, inset_size=1.5,
title="Reliability Diagram", legend_params=None, bootstrap_sets=None, ci=(2.5, 97.5)):
"""
Plot reliability curves against a 1:1 diagonal to determine if probability forecasts are consistent with their
observed relative frequency.
Args:
rel_objs (list): List of DistributedReliability objects.
obj_labels (list): List of labels describing the forecast model associated with each curve.
colors (list): List of colors for each line
markers (list): List of line markers
filename (str): Where to save the figure.
figsize (tuple): (Width, height) of the figure in inches.
xlabel (str): X-axis label
ylabel (str): Y-axis label
ticks (array): Tick value labels for the x and y axes.
dpi (int): resolution of the saved figure in dots per inch.
inset_size (float): Size of inset
title (str): Title of figure
legend_params (dict): Keyword arguments for the plot legend.
bootstrap_sets (list): A list of arrays of bootstrapped DistributedROC objects. If not None,
confidence regions will be plotted.
ci (tuple): tuple of bootstrap confidence interval percentiles
"""
if legend_params is None:
legend_params = dict(loc=4, fontsize=10, framealpha=1, frameon=True)
fig, ax = plt.subplots(figsize=figsize)
plt.plot(ticks, ticks, "k--")
inset_hist = inset_axes(ax, width=inset_size, height=inset_size, loc=2)
if bootstrap_sets is not None:
for b, b_set in enumerate(bootstrap_sets):
brel_curves = np.dstack([b_rel.reliability_curve().values for b_rel in b_set])
bin_range = np.percentile(brel_curves[:,0], ci, axis=1)
rel_range = np.percentile(brel_curves[:, 3], ci, axis=1)
bin_poly = np.concatenate((bin_range[1], bin_range[0, ::-1]))
rel_poly = np.concatenate((rel_range[1], rel_range[0, ::-1]))
bin_poly[np.isnan(bin_poly)] = 0
rel_poly[np.isnan(rel_poly)] = 0
plt.fill(bin_poly, rel_poly, alpha=0.5, color=colors[b])
for r, rel_obj in enumerate(rel_objs):
rel_curve = rel_obj.reliability_curve()
ax.plot(rel_curve["Bin_Start"], rel_curve["Positive_Relative_Freq"], color=colors[r], marker=markers[r],
label=obj_labels[r])
inset_hist.semilogy(rel_curve["Bin_Start"], rel_curve["Total_Relative_Freq"], color=colors[r],
marker=markers[r])
inset_hist.set_xlabel("Forecast Probability")
inset_hist.set_ylabel("Forecast Relative Frequency")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.legend(**legend_params)
ax.set_title(title)
plt.savefig(filename, dpi=dpi, bbox_inches="tight")
plt.close()
开发者ID:djgagne,项目名称:hagelslag,代码行数:56,代码来源:MetricPlotter.py
示例17: plot_sounding
def plot_sounding(date, station):
p, T, Td, u, v, windspeed = get_sounding_data(date, station)
lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td)
parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')
# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(8, 8))
skew = SkewT(fig)
# Plot the data
temperature_line, = skew.plot(p, T, color='tab:red')
dewpoint_line, = skew.plot(p, Td, color='blue')
cursor = mplcursors.cursor([temperature_line, dewpoint_line])
# Plot thermodynamic parameters and parcel path
skew.plot(p, parcel_path, color='black')
if lcl_pressure:
skew.ax.axhline(lcl_pressure, color='black')
if lfc_pressure:
skew.ax.axhline(lfc_pressure, color='0.7')
# Add the relevant special lines
skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()
# Shade areas representing CAPE and CIN
skew.shade_cin(p, T, parcel_path)
skew.shade_cape(p, T, parcel_path)
# Add wind barbs
skew.plot_barbs(p, u, v)
# Add an axes to the plot
ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3)
# Plot the hodograph
h = Hodograph(ax_hod, component_range=100.)
# Grid the hodograph
h.add_grid(increment=20)
# Plot the data on the hodograph
mask = (p >= 100 * units.mbar)
h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed
# Set some sensible axis limits
skew.ax.set_ylim(1000, 100)
skew.ax.set_xlim(-40, 60)
return fig, skew
开发者ID:Unidata,项目名称:unidata-python-workshop,代码行数:56,代码来源:skewt.py
示例18: plot
def plot(subplot, data, title='', *args, **kwargs):
mgr = plt.get_current_fig_manager()
a,b = 0.75, 1.0
chessboard = np.array(([a,b]*16 + [b,a]*16)*16)
chessboard.shape = 32,32
if isinstance(data, Group):
group = data #.base
data = data[data.keys[0]]
else:
group = data
data = data
plt.imshow(chessboard, cmap=plt.cm.gray, interpolation='nearest',
extent=[0,group.shape[1],0,group.shape[0]],
vmin=0, vmax=1)
plt.hold(True)
if hasattr(group, 'mask'):
D = np.where(group.mask,data,np.NaN)
else:
D = data
axis = plt.imshow(D, interpolation='nearest',
#cmap=plt.cm.bone,
#cmap= plt.cm.PuOr_r,
#vmin=-1, vmax=1,
origin='lower',
extent=[0,group.shape[1],0,group.shape[0]],
*args, **kwargs)
subplot.format_coord = partial(format_coord, axis)
subplot.group = group
plt.xticks([]), plt.yticks([])
x,y,w,h = axis.get_axes().bbox.bounds
dw = 0*float(group.shape[1]-1)/w
dh = 0*float(group.shape[0]-1)/h
plt.axis([-dw,group.shape[1]+dw,-dh,group.shape[0]+dh])
if title:
t = plt.title(title, position=(0,1.01),
verticalalignment = 'baseline',
horizontalalignment = 'left')
axins = inset_axes(subplot, width="35%", height="2.5%", loc=2,
bbox_to_anchor=(0.65, 0.05, 1, 1),
bbox_transform=subplot.transAxes, borderpad = 0)
cb = plt.colorbar(axis, cax=axins, orientation="horizontal", format='%.2f', ticks=[])
vmin,vmax = cb.get_clim()
cb.set_ticks([vmin,vmax])
cb.original_cmap = cb.get_cmap()
cb.original_clim = vmin,vmax
axins.xaxis.set_ticks_position('top')
for label in cb.ax.get_xticklabels():
label.set_fontsize('x-small')
if not hasattr(mgr, 'subplots'):
mgr.subplots = []
mgr.subplots.append((axis,group,data,cb,subplot))
开发者ID:B-Rich,项目名称:dana,代码行数:54,代码来源:display.py
示例19: graph
def graph(data_, j_size, title=None):
fig, ax = plt.subplots()
data = pd.read_csv(data_, index_col = 0)
jitter_ = jitter(-j_size, j_size, len(list(data.iterrows())[0][1]))
max_1 = 0
max_2 = 0
for i, d in enumerate(data.iterrows()):
if max(list(d[1])) > max_1 and i > 2:
max_1 = max(list(d[1]))
elif max(list(d[1])) > max_2 and i < 3:
max_2 = max(list(d[1]))
plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1]))
plt.xlim(-0.1, 5.1) # apply the x-limits
c1 = 1
while max_1/(c1*10) > 1:
c1 *= 10
c2 = 1
while max_2/(c2*10) > 1:
c2 *= 10
cb = max(c1,c2)
cs = min(c1,c2)
max1 = max(max_1, max_2)
max2 = min(max_1, max_2)
plt.ylim(-cb, (max1/cb+2)*cb)
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
if c2 > c1:
axins = inset_axes(ax, 4,3, loc=5)
else:
axins = inset_axes(ax, 4,3, loc=6)
axins.yaxis.tick_right()
for i, d in enumerate(data.iterrows()):
plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1]))
if c2 > c1:
axins.set_xlim(2.9, 5.1) # apply the x-limits
else:
axins.set_xlim(-0.1, 2.1)
plt.ylim(-cs, (max2/cs+2)*cs)
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.show()
开发者ID:cpenalobel,项目名称:schoolwork,代码行数:40,代码来源:kk.py
示例20: test_inset_axes_without_transform_should_use_parent_axes
def test_inset_axes_without_transform_should_use_parent_axes():
# creating our figure
fig = plt.figure(dpi=150)
# gca method gets current axes of the figure
ax = plt.gca()
ax.plot([0.0, 0.25, 0.50, 1.0], [0.1, 0.2, 0.4, 0.9], color='b')
# creating our inset_axes. without a bbox_transform parameter
ax_ins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1))
ax_ins.plot([0.0, 0.25, 0.50, 1.0], [0.9, 0.4, 0.2, 0.1], color='r')
assert ax.transAxes == ax_ins.transAxes
开发者ID:vapier,项目名称:matplotlib,代码行数:13,代码来源:test_axes_grid1.py
注:本文中的mpl_toolkits.axes_grid1.inset_locator.inset_axes函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论