def plot_map(lat, lon, data, normalized=False): """Plots data on a Basemap. Arguments: lat: array of lat locations of data lon: array of lon locations of other axis of data data: 2D lat-lon grid of data to put on map Keyword Arguments: normalized: if True, show a 0:1 map of ratios of max value Returns: Nothing """ bm = Basemap(projection = 'mill', llcrnrlon=min(lon), llcrnrlat=min(lat), urcrnrlon=max(lon), urcrnrlat=max(lat)) lons, lats = np.meshgrid(lon, lat) x, y = bm(lons, lats) pl.figure(figsize=(18,14)) ax = pl.gca() bm.drawcoastlines(linewidth=1.25, color='white') bm.drawparallels(np.array([-70,-50,-30,-10,10,30,50,70]), labels=[1,0,0,0]) bm.drawmeridians(np.arange(min(lon),max(lon),60),labels=[0,0,0,1]) if normalized: bm.pcolor(x,y,data.T/np.abs(np.max(data))) else: bm.pcolor(x,y,data.T) if MAL: divider = mal(ax) cax = divider.append_axes("right", size='5%', pad=0.05) pl.colorbar(cax=cax) else: pl.colorbar() return
def summaryplot(f, plate=None, ifu=None, smearing=True, stellar=False, maxr=None, cen=True, fixcent=True, save=False, clobber=False, remotedir=None, gal=None, relative_pab=False): """ Make a summary plot for a `nirvana` output file with MaNGA velocity field. Shows the values for the global parameters of the galaxy, the rotation curves (with 1-sigma lower and upper bounds) for the different velocity components, then comparisons of the MaNGA data, the model, and the residuals for the rotational velocity and the velocity dispersion. Args: f (:obj:`str`, `dynesty.NestedSampler`_, `dynesty.results.Results`_): `.fits` file, sampler, results, `.nirv` file of dumped results from :func:`~nirvana.fitting.fit`. If this is in the regular format from the automatic outfile generator in :func:`~nirvana.scripts.nirvana.main` then it will fill in most of the rest of the parameters by itself. plate (:obj:`int`, optional): MaNGA plate number for desired galaxy. Can be auto filled by `f`. ifu (:obj:`int`, optional): MaNGA IFU number for desired galaxy. Can be auto filled by `f`. smearing (:obj:`bool`, optional): Whether or not to apply beam smearing to models. Can be auto filled by `f`. stellar (:obj:`bool`, optional): Whether or not to use stellar velocity data instead of gas. Can be auto filled by `f`. maxr (:obj:`float`, optional): Maximum radius to make edges go out to in units of effective radii. Can be auto filled by `f`. cen (:obj:`bool`, optional): Whether the position of the center was fit. Can be auto filled by `f`. fixcent (:obj:`bool`, optional): Whether the center velocity bin was held at 0 in the fit. Can be auto filled by `f`. save (:obj:`bool`, optional): Flag for whether to save the plot. Will save as a pdf in the same directory as `f` is in but inside a folder called `plots`. clobber (:obj:`bool`, optional): Flag to overwrite plot file if it already exists. Only matters if `save=True` remotedir (:obj:`str`, optional): Directory to load MaNGA data files from, or save them if they are not found and are remotely downloaded. gal (:class:`~nirvana.data.fitargs.FitArgs`, optional): Pre existing galaxy object to use instead of loading from scratch """ #check if plot file already exists if save and not clobber: path = f[:f.rfind('/') + 1] fname = f[f.rfind('/') + 1:-5] if os.path.isfile(f'{path}/plots/{fname}.pdf'): raise ValueError('Plot file already exists') #unpack input file into useful objects args, resdict = fileprep(f, plate, ifu, smearing, stellar, maxr, cen, fixcent, remotedir=remotedir, gal=gal) #generate velocity models velmodel, sigmodel = bisym_model(args, resdict, plot=True, relative_pab=relative_pab) vel_r = args.kin.remap('vel') sig_r = np.sqrt(args.kin.remap('sig_phys2')) if hasattr( args.kin, 'sig_phys2') else args.kin.remap('sig') if args.kin.vel_ivar is None: args.kin.vel_ivar = np.ones_like(args.kin.vel) if args.kin.sig_ivar is None: args.kin.sig_ivar = np.ones_like(args.kin.sig) #calculate chisq maps vel_ivar = args.kin.remap('vel_ivar') sig_ivar = args.kin.remap('sig_phys2_ivar')**.5 if args.scatter: vel_ivar = 1 / (1 / vel_ivar + resdict['vel_scatter']**2) sig_ivar = 1 / (1 / sig_ivar + resdict['sig_scatter']**2) velchisq = (vel_r - velmodel)**2 * vel_ivar sigchisq = (sig_r - sigmodel)**2 * sig_ivar #print global parameters on figure fig = plt.figure(figsize=(12, 9)) plt.subplot(3, 4, 1) ax = plt.gca() infobox(ax, resdict, args, cen, relative_pab) #image plt.subplot(3, 4, 2) if args.kin.image is not None: plt.imshow(args.kin.image) else: plt.text(.5, .5, 'No image found', horizontalalignment='center', transform=plt.gca().transAxes, size=14) plt.axis('off') #Radial velocity profiles plt.subplot(3, 4, 3) ls = [r'$V_t$', r'$V_{2t}$', r'$V_{2r}$'] for i, v in enumerate(['vt', 'v2t', 'v2r']): plt.plot(args.edges, resdict[v], label=ls[i]) errors = [[resdict['vtl'], resdict['vtu']], [resdict['v2tl'], resdict['v2tu']], [resdict['v2rl'], resdict['v2ru']]] for i, p in enumerate(errors): plt.fill_between(args.edges, p[0], p[1], alpha=.5) plt.ylim(bottom=0) plt.legend(loc=2) plt.xlabel('Radius (arcsec)') plt.ylabel(r'$v$ (km/s)') plt.title('Velocity Profiles') #dispersion profile plt.subplot(3, 4, 4) plt.plot(args.edges, resdict['sig']) plt.fill_between(args.edges, resdict['sigl'], resdict['sigu'], alpha=.5) plt.ylim(bottom=0) plt.title('Velocity Dispersion Profile') plt.xlabel('Radius (arcsec)') plt.ylabel(r'$v$ (km/s)') #MaNGA Ha velocity field plt.subplot(3, 4, 5) plt.title(f"{resdict['type']} Velocity Data") vmax = min(np.max(np.abs(vel_r)), 300) plt.imshow(vel_r, cmap='jet', origin='lower', vmin=-vmax, vmax=vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=-10) #Vel model from dynesty fit plt.subplot(3, 4, 6) plt.title('Velocity Model') plt.imshow(velmodel, 'jet', origin='lower', vmin=-vmax, vmax=vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) plt.colorbar(label='km/s', cax=cax) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=-10) #Residuals from vel fit plt.subplot(3, 4, 7) plt.title('Velocity Residuals') resid = vel_r - velmodel vmax = min(np.abs(vel_r - velmodel).max(), 50) plt.imshow(vel_r - velmodel, 'jet', origin='lower', vmin=-vmax, vmax=vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) plt.colorbar(label='km/s', cax=cax) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=-10) #Chisq from vel fit plt.subplot(3, 4, 8) plt.title('Velocity Chi Squared') plt.imshow(velchisq, 'jet', origin='lower', vmin=0, vmax=50) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) plt.colorbar(cax=cax) #MaNGA Ha velocity disp plt.subplot(3, 4, 9) plt.title(f"{resdict['type']} Dispersion Data") vmax = min(np.max(sig_r), 200) plt.imshow(sig_r, cmap='jet', origin='lower', vmax=vmax, vmin=0) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=0) #disp model from dynesty fit plt.subplot(3, 4, 10) plt.title('Dispersion Model') plt.imshow(sigmodel, 'jet', origin='lower', vmin=0, vmax=vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=0) #Residuals from disp fit plt.subplot(3, 4, 11) plt.title('Dispersion Residuals') resid = sig_r - sigmodel vmax = min(np.abs(sig_r - sigmodel).max(), 50) plt.imshow(sig_r - sigmodel, 'jet', origin='lower', vmin=-vmax, vmax=vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) cb = plt.colorbar(cax=cax) cb.set_label('km/s', labelpad=-10) #Chisq from sig fit plt.subplot(3, 4, 12) plt.title('Dispersion Chi Squared') plt.imshow(sigchisq, 'jet', origin='lower', vmin=0, vmax=50) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('right', size='5%', pad=.05) plt.colorbar(cax=cax) plt.tight_layout() if save: path = f[:f.rfind('/') + 1] fname = f[f.rfind('/') + 1:-5] plt.savefig(f'{path}plots/{fname}.pdf', format='pdf') plt.close() print(resdict) return fig
def separate_components(f, plate=None, ifu=None, smearing=True, stellar=False, maxr=None, cen=True, fixcent=True, save=False, clobber=False, remotedir=None, gal=None, relative_pab=False, cmap='RdBu'): """ Make a plot `nirvana` output file with the different velocity components searated. Plot the first order velocity component and the two second order velocity components next to each other along with the full model, data, image, and global parameters The created plot contains the global parameters of the galaxy, the image of the galaxy, and the data of the velocity field on the first row. The second row is the full model followed by the different components broken out with + and = signs between. Args: f (:class:`dynesty.NestedSampler`, :obj:`str`, :class:`dynesty.results.Results`): Sampler, results, or file of dumped results from `dynesty` fit. plate (:obj:`int`, optional): MaNGA plate number for desired galaxy. Must be specified if `auto=False`. ifu (:obj:`int`, optional): MaNGA IFU design number for desired galaxy. Must be specified if `auto=False`. smearing (:obj:`bool`, optional): Flag for whether or not to apply beam smearing to models. stellar (:obj:`bool`, optional): Flag for whether or not to use stellar velocity data instead of gas. cen (:obj:`bool`, optional): Flag for whether the position of the center was fit. """ args, resdict = fileprep(f, plate, ifu, smearing, stellar, maxr, cen, fixcent, remotedir=remotedir, gal=gal) z = np.zeros(len(resdict['vt'])) vtdict, v2tdict, v2rdict = [resdict.copy(), resdict.copy(), resdict.copy()] vtdict['v2t'] = z vtdict['v2r'] = z v2tdict['vt'] = z v2tdict['v2r'] = z v2rdict['vt'] = z v2rdict['v2t'] = z if maxr is not None: r, th = projected_polar(args.kin.x, args.kin.y, *np.radians((resdict['pa'], resdict['inc']))) rmask = r > maxr args.kin.vel_mask |= rmask args.kin.sig_mask |= rmask velmodel, sigmodel = bisym_model(args, resdict, plot=True) vtmodel, sigmodel = bisym_model(args, vtdict, plot=True) v2tmodel, sigmodel = bisym_model(args, v2tdict, plot=True) v2rmodel, sigmodel = bisym_model(args, v2rdict, plot=True) vel_r = args.kin.remap('vel') #must set all masked areas to 0 or else vmax calculations barf for v in [vel_r, velmodel, vtmodel, v2tmodel, v2rmodel]: v.data[v.mask] = 0 v -= resdict['vsys'] #recenter at 0 v2model = v2tmodel + v2rmodel v2model.data[v2model.mask] = 0 velresid = vel_r - velmodel vtresid = vel_r - v2tmodel - v2rmodel v2tresid = vel_r - vtmodel - v2rmodel v2rresid = vel_r - vtmodel - v2tmodel v2resid = vel_r - vtmodel datavmax = min(np.max(np.abs([vel_r, velmodel])), 300) velvmax = min(np.max(np.abs(velresid)), 300) vtvmax = min(np.max(np.abs([vtmodel, vtresid])), 300) v2tvmax = min(np.max(np.abs([v2tmodel, v2tresid])), 300) v2rvmax = min(np.max(np.abs([v2rmodel, v2rresid])), 300) v2vmax = min(np.max(np.abs([v2model, v2resid])), 300) plt.figure(figsize=(15, 9)) plt.subplot(3, 5, 1) ax = plt.gca() infobox(ax, resdict, args) #image plt.subplot(3, 5, 2) plt.imshow(args.kin.image) plt.axis('off') #MaNGA Ha velocity field plt.subplot(3, 5, 3) plt.title(r'Velocity Data') plt.imshow(vel_r, cmap=cmap, origin='lower', vmin=-datavmax, vmax=datavmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) #Radial velocity profiles plt.subplot(3, 5, 4) ls = [r'$V_t$', r'$V_{2t}$', r'$V_{2r}$'] for i, v in enumerate(['vt', 'v2t', 'v2r']): plt.plot(args.edges, resdict[v], label=ls[i]) errors = [[resdict['vtl'], resdict['vtu']], [resdict['v2tl'], resdict['v2tu']], [resdict['v2rl'], resdict['v2ru']]] for i, p in enumerate(errors): plt.fill_between(args.edges, p[0], p[1], alpha=.5) plt.ylim(bottom=0) plt.legend(loc=2) plt.xlabel('Radius (arcsec)', labelpad=-1) plt.ylabel(r'$v$ (km/s)') plt.title('Velocity Profiles') plt.gca().tick_params(direction='in') plt.subplot(3, 5, 6) plt.imshow(velmodel, cmap=cmap, origin='lower', vmin=-datavmax, vmax=datavmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) #plt.text(1.15,.5,'=', transform=plt.gca().transAxes, size=30) plt.title(r'Model', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 7) plt.imshow(vtmodel, cmap=cmap, origin='lower', vmin=-vtvmax, vmax=vtvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) #plt.text(1.15,.5,'+', transform=plt.gca().transAxes, size=30) plt.title(r'$V_t$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 8) plt.imshow(v2tmodel, cmap=cmap, origin='lower', vmin=-v2tvmax, vmax=v2tvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) #plt.text(1.15,.5,'+', transform=plt.gca().transAxes, size=30) plt.title(r'$V_{2t}$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 9) plt.imshow(v2rmodel, cmap=cmap, origin='lower', vmin=-v2rvmax, vmax=v2rvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'$V_{2r}$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 10) plt.imshow(v2model, cmap=cmap, origin='lower', vmin=-v2vmax, vmax=v2vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'$V_{2t} + V_{2r}$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 11) plt.imshow(velresid, cmap=cmap, origin='lower', vmin=-velvmax, vmax=velvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'Data $-$ Model', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 12) plt.imshow(vtresid, cmap=cmap, origin='lower', vmin=-vtvmax, vmax=vtvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'Data$- (V_{2t} + V_{2r})$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 13) plt.imshow(v2tresid, cmap=cmap, origin='lower', vmin=-v2tvmax, vmax=v2tvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'Data$- (V_t + V_{2r})$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 14) plt.imshow(v2rresid, cmap=cmap, origin='lower', vmin=-v2rvmax, vmax=v2rvmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'Data$- (V_t + V_{2t})$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.subplot(3, 5, 15) plt.imshow(v2resid, cmap=cmap, origin='lower', vmin=-v2vmax, vmax=v2vmax) plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) plt.title(r'Data$- V_t$', fontsize=16) cax = mal(plt.gca()).append_axes('bottom', size='5%', pad=0) cb = plt.colorbar(cax=cax, orientation='horizontal') cax.tick_params(direction='in') cb.set_label('km/s', labelpad=-2) plt.tight_layout(pad=-.025) if save: path = f[:f.rfind('/') + 1] fname = f[f.rfind('/') + 1:-5] plt.savefig(f'{path}plots/sepcomp_{fname}.pdf', format='pdf') plt.close()
def geosmap(lon, lat, data, proj = 'mill', colorticks=None, colormap='seismic', colortick_labels=None, colorbar_orientation='vertical', figsize=(18,14), latlines=None, lonlines=None, minlat=None, maxlat=None, minlon=None, maxlon=None, ortho0=None, colorlimits=None, coastlines=True, countries=False, states=False, title=None, titlefontsize=20., coastcolor='white', bordercolor='white', plottype='pcolor', fontname='Arial', savefig=False, outfile=None): """Plot data on map with lon-lat grid. Arguments: lon - array-like longitude points lat - array-like latitude points data - 2D array of points to plot on lon-lat grid Keyword Arguments: proj - type of projection to plot map on colormap - color scheme of color axis colorbar_orientation - vertical (default) or horizontal colorticks - points to label on color axis colortick_labels - labels for colorticks (list of strings) colorlimits - (min,max) tuple: saturation colors for color axis if None, use limits of colorticks latlines - latitudes at which to draw lines lonlines - longitudes at which to draw lines minlat - minimum latitude to map. If None, use min of given lat maxlat - maximum latitude to map. If None, use max of given lat minlon - minimum longitude to map. If None, use min of given lon maxlon - maximum longitude to map. If None, use max of given lon figsize - size of figure frame ortho0 - (lon,lat) point to center ortho projection on coastlines - whether to draw coastlines, default True countries - whether to draw country borders, default False states - whether to draw sub-country borders (NA only?), default False coastcolor - color to make drawn coastlines bordercolor - color to make drawn national and state borders title - title to put above plot (string) fontname - font name (use matplotlib font manager to check available fonts) savefig - whether or not to save output to file, default False outfile - name of output file if savefig is True """ # Set font name mpl.rcParams['font.family'] = fontname assert len(lon) in data.shape, 'lon mismatch with data to plot dimension' assert len(lat) in data.shape, 'lat mismatch with data to plot dimension' if colortick_labels: assert colorticks, 'Must specify colorticks if specifying labels' assert len(colorticks) == len(colortick_labels), 'colorticks and '\ 'colortick labels must be same size' # Set up projection parameters if not minlat: minlat = min(lat) if not maxlat: maxlat = max(lat) if not minlon: minlon = min(lon) if not maxlon: maxlon = max(lon) if proj == 'mill': bmargs = {'projection' : 'mill', 'llcrnrlon' : minlon, 'llcrnrlat' : minlat, 'urcrnrlon' : maxlon, 'urcrnrlat' : maxlat } elif proj == 'ortho': if ortho0: assert type(ortho0) in [list, tuple, np.array], 'wrong type for ortho0' assert len(ortho0) == 2, 'ortho0 must be in the form [lon0, lat0]' lon0 = ortho0[0] lat0 = ortho0[1] else: lon0 = lon[len(lon)/2] lat0 = lat[len(lat)/2] bmargs = {'projection' : 'ortho', 'lon_0' : lon0, 'lat_0' : lat0, } else: print "Projection not recognized" return #################### # General figure details bm = Basemap(**bmargs) lons, lats = np.meshgrid(lon, lat) x, y = bm(lons, lats) fig = pl.figure(figsize=figsize) ax = pl.gca() if coastlines: bm.drawcoastlines(linewidth=1.25, color=coastcolor) if countries: bm.drawcountries(linewidth=1, color=bordercolor) if states: bm.drawstates(linewidth=1, color=bordercolor) if latlines != None: parallels = latlines else: parallels = np.array([-60,-30,0,30,60]) if not proj in ['ortho']: bm.drawparallels(parallels, labels=[1,0,0,0], fontsize=20) if lonlines != None: meridians = lonlines else: meridians = np.arange(min(lon),max(lon),60) bm.drawmeridians(meridians, labels=[0,0,1,0], fontsize=20) #################### # Plotting and colorbar if colormap == 'WhGrYlRd': WhGrYlRd_scheme = np.genfromtxt('WhGrYlRd.txt',delimiter=' ') colormap = mpl.colors.ListedColormap(WhGrYlRd_scheme/255) if colorticks: tiks = colorticks else: tiks = np.linspace(np.min(data),np.max(data),10) if colorlimits: vmin, vmax = colorlimits else: vmin, vmax = min(tiks), max(tiks) if plottype == 'pcolor': bm.pcolor(x,y,data, cmap=colormap, vmin=vmin, vmax=vmax) elif plottype == 'contourf': bm.contourf(x,y,data, vmin=vmin, vmax=vmax, cmap=colormap) else: print "plottype not recognized" raise TypeError if title and (colorbar_orientation in ['horizontal','bottom']): fig.suptitle(title,fontsize=titlefontsize) elif title: fig.suptitle(title,fontsize=titlefontsize) divider = mal(ax) if not colortick_labels: tiklabs = ['%.2f'%ti for ti in tiks] else: tiklabs = colortick_labels if colorbar_orientation in ['vertical','right']: cax = divider.append_axes('right', size='5%', pad=0.05) cbar = pl.colorbar(orientation='vertical',cax=cax,ticks=tiks) cbar.ax.set_yticklabels(tiklabs, fontsize=20) elif colorbar_orientation in ['horizontal','bottom']: cax = divider.append_axes('bottom', size='10%', pad=0.1) cbar = pl.colorbar(orientation='horizontal',cax=cax,ticks=tiks) cbar.ax.set_xticklabels(tiklabs, fontsize=20) if savefig: if outfile !=None: fig.savefig(outfile) else: print "No outfile name given"
def geosmap(lon, lat, data, proj = 'mill', colorticks=None, colormap='seismic', colortick_labels=None, colorbar_orientation='vertical', figsize=(18,14), latlines=None, lonlines=None, minlat=None, maxlat=None, minlon=None, maxlon=None, ortho0=None, colorbins=None, colorlimits=None, coastlines=True, countries=False, states=False, title=None, titlefontsize=20., coastcolor='white', bordercolor='white', plottype='pcolor', fontname='sans-serif', savefig=False, outfile=None, subplot=False, subplot_position=None, subplot_title=None, fig=None, meridianlabels='bottom', parallellabels='left', hide_colorbar=False, tight=False, ): """Plot data on map with lon-lat grid. Arguments: lon - array-like longitude points lat - array-like latitude points data - 2D array of points to plot on lon-lat grid Keyword Arguments: proj - type of projection to plot map on colormap - color scheme of color axis colorbar_orientation - vertical (default) or horizontal colorticks - points to label on color axis colortick_labels - labels for colorticks (list of strings) colorlimits - (min,max) tuple: saturation colors for color axis if None, use limits of colorticks latlines - latitudes at which to draw lines lonlines - longitudes at which to draw lines minlat - minimum latitude to map. If None, use min of given lat maxlat - maximum latitude to map. If None, use max of given lat minlon - minimum longitude to map. If None, use min of given lon maxlon - maximum longitude to map. If None, use max of given lon figsize - size of figure frame ortho0 - (lon,lat) point to center ortho projection on coastlines - whether to draw coastlines, default True countries - whether to draw country borders, default False states - whether to draw sub-country borders (NA only?), default False coastcolor - color to make drawn coastlines bordercolor - color to make drawn national and state borders title - title to put above plot (string) titlefontsize - font size for color fontname - font name (use matplotlib font manager to check available fonts) savefig - whether or not to save output to file, default False outfile - name of output file if savefig is True subplot - whether to plot subplots, subplot_position - relative location of each subplot,[nrows,ncols,plot_number] fig - create a figure outside of geosplot when subplot is active tight - Flag for using the tight_layout call. default False hide_colorbar - Flag to supress drawing the colorbar. default False parallellabels - What side of the map to draw parallel labels on. default 'left' If not 'left' or 'right', will not draw labels. meridianlabels - What side of the map to draw meridian labels on. default 'top' If not 'top' or 'bottom', will not draw labels. """ # Set font name mpl.rcParams['font.family'] = fontname assert len(lon) in data.shape, 'lon mismatch with data to plot dimension' assert len(lat) in data.shape, 'lat mismatch with data to plot dimension' if colortick_labels: assert colorticks or colorbins, 'Must specify colorticks or colorbins '\ 'if specifying labels' if colorticks: assert len(colorticks) == len(colortick_labels), 'colorticks and '\ 'colortick labels must be same size' elif colorbins: assert len(colorbins) == len(colortick_labels) # Set up projection parameters if not minlat: minlat = min(lat) if not maxlat: maxlat = max(lat) if not minlon: minlon = min(lon) if not maxlon: maxlon = max(lon) if proj == 'mill': bmargs = {'projection' : 'mill', 'llcrnrlon' : minlon, 'llcrnrlat' : minlat, 'urcrnrlon' : maxlon, 'urcrnrlat' : maxlat } elif proj == 'ortho': if ortho0: assert type(ortho0) in [list, tuple, np.array], 'wrong type for ortho0' assert len(ortho0) == 2, 'ortho0 must be in the form [lon0, lat0]' lon0 = ortho0[0] lat0 = ortho0[1] else: lon0 = lon[len(lon)/2] lat0 = lat[len(lat)/2] bmargs = {'projection' : 'ortho', 'lon_0' : lon0, 'lat_0' : lat0, } else: print "Projection not recognized" return #################### # subplot arguments; figure need to be created outside of geosplot for the this to work if not fig: fig = pl.figure(figsize=figsize) if subplot: assert subplot_position is not None, "subplot_position not specified" nrows, ncols, plot_number = subplot_position axi = fig.add_subplot(nrows, ncols, plot_number) if subplot_title: axi.set_title(subplot_title) if tight: fig.tight_layout() ax = pl.gca() # General figure details bm = Basemap(**bmargs) lons, lats = np.meshgrid(lon, lat) x, y = bm(lons, lats) if coastlines: bm.drawcoastlines(linewidth=1.25, color=coastcolor) if countries: bm.drawcountries(linewidth=1, color=bordercolor) if states: bm.drawstates(linewidth=1, color=bordercolor) if latlines != None: parallels = latlines else: parallels = np.array([-60,-30,0,30,60]) if not proj in ['ortho']: if parallellabels == 'left': bm.drawparallels(parallels, labels=[1,0,0,0], fontsize=20) elif parallellabels == 'right': bm.drawparallels(parallels, labels=[0,1,0,0], fontsize=20) else: bm.drawparallels(parallels, labels=[0,0,0,0], fontsize=20) if lonlines != None: meridians = lonlines else: meridians = np.arange(min(lon),max(lon),60) if meridianlabels == 'bottom': bm.drawmeridians(meridians, labels=[0,0,0,1], fontsize=20) elif meridianlabels == 'top': bm.drawmeridians(meridians, labels=[0,0,1,0], fontsize=20) else: bm.drawmeridians(meridians, labels=[0,0,0,0]) #################### # Plotting and colorbar if colormap == 'WhGrYlRd': WhGrYlRd_scheme = np.genfromtxt('WhGrYlRd.txt',delimiter=' ') colormap = mpl.colors.ListedColormap(WhGrYlRd_scheme/255) NORM = None if colorbins: tiks = colorbins NORM = mpl.colors.BoundaryNorm(tiks,mpl.colors.Colormap(colormap).N) if colorticks: tiks = colorticks elif not colorbins: tiks = np.linspace(np.min(data),np.max(data),10) if colorlimits: vmin, vmax = colorlimits else: vmin, vmax = min(tiks), max(tiks) if plottype == 'pcolor': bm.pcolor(x,y,data, cmap=colormap, vmin=vmin, vmax=vmax, norm=NORM) elif plottype == 'contourf': bm.contourf(x,y,data, vmin=vmin, vmax=vmax, cmap=colormap, norm=NORM) else: print "plottype not recognized" raise TypeError if title and not (colorbar_orientation in ['top']): ax.set_title(title,fontsize=titlefontsize) elif title: pass #ax.set_title(title,fontsize=titlefontsize) divider = mal(ax) if not colortick_labels: strs = ['%.2G'%ti for ti in tiks] brks = [s.split('E') for s in strs] tiklabs = [] for br in brks: if len(br) > 1: t = '%s x10$ ^{%s} $'%(br[0],int(br[1])) else: t = br[0] tiklabs.append(t) else: tiklabs = colortick_labels if not hide_colorbar: if colorbar_orientation in ['vertical','right']: cax = divider.append_axes('right', size='5%', pad=0.05) cbar = pl.colorbar(orientation='vertical',cax=cax,ticks=tiks) cbar.ax.set_yticklabels(tiklabs, fontsize=20) elif colorbar_orientation in ['horizontal','bottom']: cax = divider.append_axes('bottom', size='10%', pad=0.1) cbar = pl.colorbar(orientation='horizontal',cax=cax,ticks=tiks) cbar.ax.set_xticklabels(tiklabs, fontsize=20) if savefig: if outfile !=None: fig.savefig(outfile) else: print "No outfile given: fig not saved" return fig