def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
'''
:param data:
:param outputname:
:param cmap:
'''
aspect_ratio = float(data.shape[1])/data.shape[0]
fig = pylab.figure()
Scale = 8
# add +1 to get axis text
fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
ax = pylab.gca()
#ax.set_axis_off()
#fig.add_axes(ax)
if cmap != None:
pylab.set_cmap(cmap)
#ax.imshow(data, interpolation='nearest', aspect = 'normal')
ax.imshow(data, interpolation='nearest')
if rangeXpx == None:
rangeXpx = (0, data.shape[1])
if rangeZpx == None:
rangeZpx = (0, data.shape[0])
modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
#plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
pylab.savefig(outputname, dpi = data.shape[0]/Scale)
pylab.close()
fig.clear()
python类gca()的实例源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
'''
:param data:
:param outputname:
:param cmap:
'''
aspect_ratio = float(data.shape[1])/data.shape[0]
fig = pylab.figure()
Scale = 8
# add +1 to get axis text
fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
ax = pylab.gca()
#ax.set_axis_off()
#fig.add_axes(ax)
if cmap != None:
pylab.set_cmap(cmap)
#ax.imshow(data, interpolation='nearest', aspect = 'normal')
ax.imshow(data, interpolation='nearest')
if rangeXpx == None:
rangeXpx = (0, data.shape[1])
if rangeZpx == None:
rangeZpx = (0, data.shape[0])
modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
#plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
pylab.savefig(outputname, dpi = data.shape[0]/Scale)
pylab.close()
fig.clear()
def theme(ax=None, minorticks=False):
""" update plot to make it nice and uniform """
from matplotlib.ticker import AutoMinorLocator
from pylab import rcParams, gca, tick_params
if minorticks:
if ax is None:
ax = gca()
ax.yaxis.set_minor_locator(AutoMinorLocator())
ax.xaxis.set_minor_locator(AutoMinorLocator())
tick_params(which='both', width=rcParams['lines.linewidth'])
def histplot(data, bins=10, range=None, normed=False, weights=None, density=None, ax=None, **kwargs):
""" plot an histogram of data `a la R`: only bottom and left axis, with
dots at the bottom to represent the sample
Example
-------
import numpy as np
x = np.random.normal(0, 1, 1e3)
histplot(x, bins=50, density=True, ls='steps-mid')
"""
h, b = np.histogram(data, bins, range, normed, weights, density)
if ax is None:
ax = plt.gca()
x = 0.5 * (b[:-1] + b[1:])
l = ax.plot(x, h, **kwargs)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
_w = ['top', 'right']
[ ax.spines[side].set_visible(False) for side in _w ]
for wk in ['bottom', 'left']:
ax.spines[wk].set_position(('outward', 10))
ylim = ax.get_ylim()
ax.plot(data, -0.02 * max(ylim) * np.ones(len(data)), '|', color=l[0].get_color())
ax.set_ylim(-0.02 * max(ylim), max(ylim))
def imshow(self, **kwargs):
defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
'interpolation':'nearest', 'aspect':'auto'}
defaults.update(**kwargs)
ax = kwargs.pop('ax', plt.gca())
return ax.imshow(self.im.T, extent=self.e, **defaults)
def contour(self, *args, **kwargs):
defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
'levels': np.sort(self.nice_levels())}
defaults.update(**kwargs)
ax = kwargs.pop('ax', plt.gca())
return ax.contour(self.im.T, *args, extent=self.e, **defaults)
def contourf(self, *args, **kwargs):
defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
'levels': self.nice_levels()}
defaults.update(**kwargs)
ax = kwargs.pop('ax', plt.gca())
return ax.contourf(self.im.T, *args, extent=self.e, **defaults)
def plot(self, ax=None, orientation='horizontal', cutoff=False, log=False,
cutoff_type='std', cutoff_val=1.5, pos=100, pos_marker='line',
pos_width=0.05, pos_kwargs={}, **kwargs):
if ax is None:
ax = plt.gca()
# Draw the violin.
if ('facecolor' not in kwargs) | ('fc' not in kwargs):
kwargs['facecolor'] = 'y'
if ('edgecolor' not in kwargs) | ('ec' not in kwargs):
kwargs['edgecolor'] = 'k'
if ('alpha' not in kwargs.keys()):
kwargs['alpha'] = 0.5
if 'color' in kwargs:
kwargs['edgecolor'] = kwargs['color']
kwargs['facecolor'] = kwargs['color']
# Kernel density estimate for data at this position.
violin, e = self.im, self.e
xvals = np.linspace(e[0], e[1], len(violin))
xvals = np.hstack(([xvals[0]], xvals, [xvals[-1]]))
violin = np.hstack(([0], violin, [0]))
if orientation == 'horizontal':
ax.fill(xvals, violin, **kwargs)
elif orientation == 'vertical':
ax.fill_betweenx(xvals, 0, violin, **kwargs)
plt.draw_if_interactive()
def cmPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd, type):
"""Color-magnitude plot"""
angsep = ugali.utils.projector.angsep(targ_ra, targ_dec, data['RA'], data['DEC'])
annulus = (angsep > g_radius) & (angsep < 1.)
mag_g = data[mag_g_dred_flag]
mag_r = data[mag_r_dred_flag]
if type == 'stars':
filter = star_filter(data)
plt.title('Stellar Color-Magnitude')
elif type == 'galaxies':
filter = galaxy_filter(data)
plt.title('Galactic Color-Magnitude')
iso_filter = (iso.separation(mag_g, mag_r) < 0.1)
# Plot background objects
plt.scatter(mag_g[filter & annulus] - mag_r[filter & annulus], mag_g[filter & annulus], c='k', alpha=0.1, edgecolor='none', s=1)
# Plot isochrone
ugali.utils.plotting.drawIsochrone(iso, lw=2, label='{} Gyr, z = {}'.format(iso.age, iso.metallicity))
# Plot objects in nbhd
plt.scatter(mag_g[filter & nbhd] - mag_r[filter & nbhd], mag_g[filter & nbhd], c='g', s=5, label='r < {:.3f}$^\circ$'.format(g_radius))
# Plot objects in nbhd and near isochrone
plt.scatter(mag_g[filter & nbhd & iso_filter] - mag_r[filter & nbhd & iso_filter], mag_g[filter & nbhd & iso_filter], c='r', s=5, label='$\Delta$CM < 0.1')
plt.axis([-0.5, 1, 16, 24])
plt.gca().invert_yaxis()
plt.gca().set_aspect(1./4.)
plt.legend(loc='upper left')
plt.xlabel('g-r (mag)')
plt.ylabel('g (mag)')
def drawHealpixMap(map, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs):
"""
Draw local projection of healpix map.
"""
ax = plt.gca()
x = np.linspace(-size,size,xsize)
y = np.linspace(-size,size,xsize)
xx, yy = np.meshgrid(x,y)
coord = coord.upper()
if coord == 'GC':
#Assumes map and (lon,lat) are Galactic, but plotting celestial
llon, llat = image2sphere(*gal2cel(lon,lat),x=xx.flat,y=yy.flat)
pix = ang2pix(healpy.get_nside(map),*cel2gal(llon,llat))
elif coord == 'CG':
#Assumes map and (lon,lat) are celestial, but plotting Galactic
llon, llat = image2sphere(*cel2gal(lon,lat),x=xx.flat,y=yy.flat)
pix = ang2pix(healpy.get_nside(map),*gal2cel(llon,llat))
else:
#Assumes plotting the native coordinates
llon, llat = image2sphere(lon,lat,xx.flat,yy.flat)
pix = ang2pix(healpy.get_nside(map),llon,llat)
values = map[pix].reshape(xx.shape)
zz = np.ma.array(values,mask=(values==healpy.UNSEEN),fill_value=np.nan)
return drawProjImage(xx,yy,zz,coord=coord,**kwargs)
def drawImage(self,ax=None,invert=True):
if not ax: ax = plt.gca()
if self.config['data']['survey']=='sdss':
# Optical Image
im = ugali.utils.plotting.getSDSSImage(**self.image_kwargs)
# Flipping JPEG:
# https://github.com/matplotlib/matplotlib/issues/101
im = im[::-1]
ax.annotate("SDSS Image",**self.label_kwargs)
else:
im = ugali.utils.plotting.getDSSImage(**self.image_kwargs)
im = im[::-1,::-1]
ax.annotate("DSS Image",**self.label_kwargs)
size=self.image_kwargs.get('radius',1.0)
# Celestial coordinates
x = np.linspace(-size,size,im.shape[0])
y = np.linspace(-size,size,im.shape[1])
xx, yy = np.meshgrid(x,y)
#kwargs = dict(cmap='gray',interpolation='none')
kwargs = dict(cmap='gray',coord='C')
im = drawProjImage(xx,yy,im,**kwargs)
try: plt.gcf().delaxes(ax.cax)
except AttributeError: pass
return im
def drawCatalog(self, ax=None):
if not ax: ax = plt.gca()
# Stellar Catalog
self._create_catalog()
healpy.projscatter(self.catalog.lon,self.catalog.lat,c='k',marker='.',lonlat=True,coord=self.gnom_kwargs['coord'])
ax.annotate("Stars",**self.label_kwargs)
def drawSpatial(self, ax=None):
if not ax: ax = plt.gca()
# Stellar Catalog
self._create_catalog()
cut = (self.catalog.color > 0) & (self.catalog.color < 1)
catalog = self.catalog.applyCut(cut)
ax.scatter(catalog.lon,catalog.lat,c='k',marker='.',s=1)
ax.set_xlim(self.glon-0.5,self.glon+0.5)
ax.set_ylim(self.glat-0.5,self.glat+0.5)
ax.set_xlabel('GLON (deg)')
ax.set_ylabel('GLAT (deg)')
def drawCMD(self, ax=None, radius=None, zidx=None):
if not ax: ax = plt.gca()
import ugali.isochrone
if zidx is not None:
filename = self.config.mergefile
logger.debug("Opening %s..."%filename)
f = pyfits.open(filename)
distance_modulus = f[2].data['DISTANCE_MODULUS'][zidx]
iso = ugali.isochrone.Padova(age=12,z=0.0002,mod=distance_modulus)
#drawIsochrone(iso,ls='',marker='.',ms=1,c='k')
drawIsochrone(iso)
# Stellar Catalog
self._create_catalog()
if radius is not None:
sep = ugali.utils.projector.angsep(self.glon,self.glat,self.catalog.lon,self.catalog.lat)
cut = (sep < radius)
catalog_cmd = self.catalog.applyCut(cut)
else:
catalog_cmd = self.catalog
ax.scatter(catalog_cmd.color, catalog_cmd.mag,color='b',marker='.',s=1)
ax.set_xlim(self.roi.bins_color[0],self.roi.bins_color[-1])
ax.set_ylim(self.roi.bins_mag[-1],self.roi.bins_mag[0])
ax.set_xlabel('Color (mag)')
ax.set_ylabel('Magnitude (mag)')
try: ax.cax.colorbar(im)
except: pass
ax.annotate("Stars",**self.label_kwargs)
def drawTS(self, filename=None, zidx=None):
ax = plt.gca()
if zidx is None: zidx = self.zidx
super(ObjectPlotter,self).drawTS(ax,filename,zidx)
def drawMembership(self, radius=None, zidx=None, mc_source_id=1):
ax = plt.gca()
if zidx is None: zidx = self.zidx
super(ObjectPlotter,self).drawMembership(ax,radius,zidx,mc_source_id)
def drawHessDiagram(self,catalog=None):
ax = plt.gca()
if not catalog: catalog = self.get_stars()
r_peak = self.kernel.extension
angsep = ugali.utils.projector.angsep(self.ra, self.dec, catalog.ra, catalog.dec)
cut_inner = (angsep < r_peak)
cut_annulus = (angsep > 0.5) & (angsep < 1.) # deg
mmin, mmax = 16., 24.
cmin, cmax = -0.5, 1.0
mbins = np.linspace(mmin, mmax, 150)
cbins = np.linspace(cmin, cmax, 150)
color = catalog.color[cut_annulus]
mag = catalog.mag[cut_annulus]
h, xbins, ybins = numpy.histogram2d(color, mag, bins=[cbins,mbins])
blur = nd.filters.gaussian_filter(h.T, 2)
kwargs = dict(extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],
cmap='gray_r', aspect='auto', origin='lower',
rasterized=True, interpolation='none')
ax.imshow(blur, **kwargs)
pylab.scatter(catalog.color[cut_inner], catalog.mag[cut_inner],
c='red', s=7, edgecolor='none')# label=r'$r < %.2f$ deg'%(r_peak))
ugali.utils.plotting.drawIsochrone(self.isochrone, c='b', zorder=10)
ax.set_xlim(-0.5, 1.)
ax.set_ylim(24., 16.)
plt.xlabel(r'$g - r$')
plt.ylabel(r'$g$')
plt.xticks([-0.5, 0., 0.5, 1.])
plt.yticks(numpy.arange(mmax - 1., mmin - 1., -1.))
radius_string = (r'${\rm r}<%.1f$ arcmin'%( 60 * r_peak))
pylab.text(0.05, 0.95, radius_string,
fontsize=10, ha='left', va='top', color='red',
transform=pylab.gca().transAxes,
bbox=dict(facecolor='white', alpha=1., edgecolor='none'))
def drawMembersSpatial(self,data):
ax = plt.gca()
if isinstance(data,basestring):
filename = data
data = pyfits.open(filename)[1].data
xmin, xmax = -0.25,0.25
ymin, ymax = -0.25,0.25
xx,yy = np.meshgrid(np.linspace(xmin,xmax),np.linspace(ymin,ymax))
x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC'])
sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax)
sel_prob = data['PROB'][sel] > 5.e-2
index_sort = numpy.argsort(data['PROB'][sel][sel_prob])
plt.scatter(x_prob[sel][~sel_prob], y_prob[sel][~sel_prob],
marker='o', s=2, c='0.75', edgecolor='none')
sc = plt.scatter(x_prob[sel][sel_prob][index_sort],
y_prob[sel][sel_prob][index_sort],
c=data['PROB'][sel][sel_prob][index_sort],
marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1.) # Spectral_r
drawProjImage(xx,yy,None,coord='C')
#ax.set_xlim(xmax, xmin)
#ax.set_ylim(ymin, ymax)
#plt.xlabel(r'$\Delta \alpha_{2000}\,(\deg)$')
#plt.ylabel(r'$\Delta \delta_{2000}\,(\deg)$')
plt.xticks([-0.2, 0., 0.2])
plt.yticks([-0.2, 0., 0.2])
divider = make_axes_locatable(ax)
ax_cb = divider.new_horizontal(size="7%", pad=0.1)
plt.gcf().add_axes(ax_cb)
pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability')
ax_cb.yaxis.tick_right()
def plot_time_freq(self, minlen=10):
part = [pp for pp in self.partial if len(pp.f) > minlen]
pl.figure()
pl.hold(True)
for pp in part:
pl.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f))
pl.hold(False)
pl.xlabel('Time (s)')
pl.ylabel('Frequency (Hz)')
# pl.show()
return pl.gca()
def save_weights_png(model):
print "HEY!"
for layer in model.layers:
weights = layer.get_weights()
print layer.name
pl.figure(figsize=(5, 5))
pl.title('conv1 weights')
nice_imshow(pl.gca(), make_mosaic(printable, 6, 6), cmap=cm.binary)