def mollview(map=None,fig=None,plot=False,filenme=None, rot=None,coord=None,unit='', xsize=800,title='Mollweide view',nest=False, min=None,max=None,flip='astro', remove_dip=False,remove_mono=False, gal_cut=0, format='%g',format2='%g', cbar=True,cmap=None, notext=False, norm=None,hold=False,margins=None,sub=None, return_projected_map=False): """Plot an healpix map (given as an array) in Mollweide projection. Requires the healpy package. This function is taken from the Healpy package and slightly modified. Parameters ---------- map : float, array-like or None An array containing the map, supports masked maps, see the `ma` function. If None, will display a blank map, useful for overplotting. fig : figure object or None, optional The figure to use. Default: create a new figure plot : bool (default: False) if True the image is plotted filename : string (default: None) Filename to be written to (if a filename is specified) rot : scalar or sequence, optional Describe the rotation to apply. In the form (lon, lat, psi) (unit: degrees) : the point at longitude *lon* and latitude *lat* will be at the center. An additional rotation of angle *psi* around this direction is applied. coord : sequence of character, optional Either one of 'G', 'E' or 'C' to describe the coordinate system of the map, or a sequence of 2 of these to rotate the map from the first to the second coordinate system. unit : str, optional A text describing the unit of the data. Default: '' xsize : int, optional The size of the image. Default: 800 title : str, optional The title of the plot. Default: 'Mollweide view' nest : bool, optional If True, ordering scheme is NESTED. Default: False (RING) min : float, optional The minimum range value max : float, optional The maximum range value flip : {'astro', 'geo'}, optional Defines the convention of projection : 'astro' (default, east towards left, west towards right) or 'geo' (east towards right, west towards left) remove_dip : bool, optional If :const:`True`, remove the dipole+monopole remove_mono : bool, optional If :const:`True`, remove the monopole gal_cut : float, scalar, optional Symmetric galactic cut for the dipole/monopole fit. Removes points in latitude range [-gal_cut, +gal_cut] format : str, optional The format of the scale label. Default: '%g' format2 : str, optional Format of the pixel value under mouse. Default: '%g' cbar : bool, optional Display the colorbar. Default: True notext : bool, optional If True, no text is printed around the map norm : {'hist', 'log', None} Color normalization, hist= histogram equalized color mapping, log= logarithmic color mapping, default: None (linear color mapping) hold : bool, optional If True, replace the current Axes by a MollweideAxes. use this if you want to have multiple maps on the same figure. Default: False sub : int, scalar or sequence, optional Use only a zone of the current figure (same syntax as subplot). Default: None margins : None or sequence, optional Either None, or a sequence (left,bottom,right,top) giving the margins on left,bottom,right and top of the axes. Values are relative to figure (0-1). Default: None return_projected_map : bool if True returns the projected map in a 2d numpy array See Also -------- gnomview, cartview, orthview, azeqview """ try: from healpy import projaxes as PA from healpy import pixelfunc except ImportError: warnings.warn( "Could not load healpy package. If you want to use this feature, " "plaese install the healpy package from here: http://healpy.readthedocs.io/en/latest/" "or via pip or conda.", RuntimeWarning) return # Create the figure if not (hold or sub): if fig == None: f=plt.figure(figsize=(8.5,5.4)) extent = (0.02,0.05,0.96,0.9) else: f=fig extent = (0.02,0.05,0.96,0.9) elif hold: f=plt.gcf() left,bottom,right,top = np.array(f.gca().get_position()).ravel() extent = (left,bottom,right-left,top-bottom) f.delaxes(f.gca()) else: # using subplot syntax f=plt.gcf() if hasattr(sub,'__len__'): nrows, ncols, idx = sub else: nrows, ncols, idx = sub//100, (sub%100)//10, (sub%10) if idx < 1 or idx > ncols*nrows: raise ValueError('Wrong values for sub: %d, %d, %d'%(nrows, ncols, idx)) c,r = (idx-1)%ncols,(idx-1)//ncols if not margins: margins = (0.01,0.0,0.0,0.02) extent = (c*1./ncols+margins[0], 1.-(r+1)*1./nrows+margins[1], 1./ncols-margins[2]-margins[0], 1./nrows-margins[3]-margins[1]) extent = (extent[0]+margins[0], extent[1]+margins[1], extent[2]-margins[2]-margins[0], extent[3]-margins[3]-margins[1]) # Starting to draw : turn interactive off wasinteractive = plt.isinteractive() plt.ioff() try: if map is None: map = np.zeros(12)+np.inf cbar=False map = pixelfunc.ma_to_array(map) ax=PA.HpxMollweideAxes(f,extent,coord=coord,rot=rot, format=format2,flipconv=flip) f.add_axes(ax) if remove_dip: map=pixelfunc.remove_dipole(map,gal_cut=gal_cut, nest=nest,copy=True, verbose=True) elif remove_mono: map=pixelfunc.remove_monopole(map,gal_cut=gal_cut,nest=nest, copy=True,verbose=True) img = ax.projmap(map,nest=nest,xsize=xsize,coord=coord,vmin=min,vmax=max, cmap=cmap,norm=norm) if cbar: im = ax.get_images()[0] b = im.norm.inverse(np.linspace(0,1,im.cmap.N+1)) v = np.linspace(im.norm.vmin,im.norm.vmax,im.cmap.N) if matplotlib.__version__ >= '0.91.0': cb=f.colorbar(im,ax=ax, orientation='horizontal', shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(), pad=0.05,fraction=0.1,boundaries=b,values=v, format=format) else: # for older matplotlib versions, no ax kwarg cb=f.colorbar(im,orientation='horizontal', shrink=0.5,aspect=25,ticks=PA.BoundaryLocator(), pad=0.05,fraction=0.1,boundaries=b,values=v, format=format) cb.solids.set_rasterized(True) ax.set_title(title) if not notext: ax.text(0.86,0.05,ax.proj.coordsysstr,fontsize=14, fontweight='bold',transform=ax.transAxes) if cbar: cb.ax.text(0.5,-1.0,unit,fontsize=14, transform=cb.ax.transAxes,ha='center',va='center') f.sca(ax) finally: if plot: plt.draw() if wasinteractive: plt.ion() #plt.show() if return_projected_map: return img
def plot(self, **kwargs): kwargs_imshow = {'norm': None, 'vmin': None, 'vmax': None} zscale_power = kwargs.get('zscale_power', 2.0) zscale = kwargs.get('zscale', None) cbar = kwargs.get('cbar', True) cbar_label = kwargs.get('cbar_label', '') title = kwargs.get('title', '') levels = kwargs.get('levels', None) kwargs_imshow['vmin'] = kwargs.get('vmin', None) kwargs_imshow['vmax'] = kwargs.get('vmax', None) cmap = mpl.cm.get_cmap(kwargs.get('cmap', 'jet')) cmap.set_under('white') kwargs_imshow['cmap'] = cmap if zscale == 'pow': vmed = np.median(self.counts) vmax = max(self.counts) vmin = min(1.1 * self.counts[self.counts > 0]) # vmin = max(vmed*(vmed/vmax),min(self.counts[self.counts>0])) kwargs_imshow['norm'] = PowerNorm(gamma=1. / zscale_power, clip=True) elif zscale == 'log': kwargs_imshow['norm'] = LogNorm() else: kwargs_imshow['norm'] = Normalize(clip=True) from healpy import projaxes as PA fig = plt.gcf() extent = (0.02, 0.05, 0.96, 0.9) ax = PA.HpxMollweideAxes(fig, extent, coord=None, rot=None, format='%g', flipconv='astro') ax.set_title(title) fig.add_axes(ax) img0 = ax.projmap(self.counts, nest=self.nest, xsize=1600, coord='C', **kwargs_imshow) if levels: cs = ax.contour(img0, extent=ax.proj.get_extent(), levels=levels, colors=['k'], interpolation='nearest') hp.visufunc.graticule(verbose=False, lw=0.5, color='k') if cbar: im = ax.get_images()[0] cb = fig.colorbar(im, orientation='horizontal', shrink=.8, pad=0.05, format='%.3g') #, ticks=[min, max]) cb.ax.xaxis.set_label_text(cbar_label) if zscale == 'pow': gamma = 1. / zscale_power print vmin, vmed, vmax ticks = np.linspace(vmin**gamma, vmax**gamma, 6)**(1. / gamma) print ticks cb.set_ticks(ticks) # cb.ax.xaxis.labelpad = -8 # workaround for issue with viewers, see colorbar docstring cb.solids.set_edgecolor("face")
def plot(self,**kwargs): kwargs_imshow = { 'norm' : None, 'vmin' : None, 'vmax' : None } gamma = kwargs.get('gamma',2.0) zscale = kwargs.get('zscale',None) cbar = kwargs.get('cbar',None) cbar_label = kwargs.get('cbar_label','') title = kwargs.get('title','') levels = kwargs.get('levels',None) rot = kwargs.get('rot',None) kwargs_imshow['vmin'] = kwargs.get('vmin',None) kwargs_imshow['vmax'] = kwargs.get('vmax',None) cmap = mpl.cm.get_cmap(kwargs.get('cmap','jet')) cmap.set_under('white') kwargs_imshow['cmap'] = cmap if zscale == 'pow': vmed = np.median(self.counts) vmax = max(self.counts) vmin = min(1.1*self.counts[self.counts>0]) # vmin = max(vmed*(vmed/vmax),min(self.counts[self.counts>0])) kwargs_imshow['norm'] = PowerNorm(gamma=gamma,clip=True) elif zscale == 'log': kwargs_imshow['norm'] = LogNorm() else: kwargs_imshow['norm'] = Normalize(clip=True) from healpy import projaxes as PA fig = plt.gcf() if 'sub' in kwargs: sub = kwargs['sub'] nrows, ncols, idx = sub/100, (sub%100)/10, (sub%10) c,r = (idx-1)%ncols,(idx-1)/ncols # if not margins: margins = (0.01,0.0,0.0,0.02) extent = (c*1./ncols+margins[0], 1.-(r+1)*1./nrows+margins[1], 1./ncols-margins[2]-margins[0], 1./nrows-margins[3]-margins[1]) extent = (extent[0]+margins[0], extent[1]+margins[1], extent[2]-margins[2]-margins[0], extent[3]-margins[3]-margins[1]) else: extent = (0.02,0.05,0.96,0.9) ax=PA.HpxMollweideAxes(fig,extent,coord=None,rot=rot, format='%g',flipconv='astro') ax.set_title(title) fig.add_axes(ax) img0 = ax.projmap(self.counts,nest=self.nest,xsize=1600,coord='C', **kwargs_imshow) if levels: cs = ax.contour(img0,extent=ax.proj.get_extent(), levels=levels,colors=['k'], interpolation='nearest') hp.visufunc.graticule(verbose=False,lw=0.5,color='k') if cbar is not None: im = ax.get_images()[0] cb_kw = dict(orientation = 'vertical', shrink=.6, pad=0.05) cb_kw.update(cbar) cb = fig.colorbar(im, **cb_kw)#,format='%.3g') cb.set_label(cbar_label)
#print hdulist[1].data.field(0) hpm = hdulist[1].data.field(24) hpm = hp.sphtfunc.smoothing(np.array(hpm, copy=True), sigma=np.radians(0.3)) #hpm = hp.read_map('test.fits') print type(hpm) print hpm.shape fig = plt.figure() extent = (0.02, 0.05, 0.96, 0.9) ax = PA.HpxMollweideAxes(fig, extent, coord=None, rot=None, format='%g', flipconv='astro') fig.add_axes(ax) img0 = ax.projmap(hpm, nest=False, xsize=1600, coord=None) #hp.visufunc.graticule() # norm=PowerNormalize(power=2))#,#vmin=min,vmax=max, # cmap=cmap,norm=norm) #plt.figure() #hp.mollview(hpm) #plt.figure()