def plot_power_spectrum(image, title=None, filename_prefix=None, filename_suffix='.png', show=False, savedir='./'): ''' Plots power spectrum derived from a fourier transform of the image. ''' # import external modules import numpy as np from agpy import azimuthalAverage as radial_average from scipy import fftpack import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.axes_grid1 import axes from matplotlib import cm if 0: plt.close(); plt.clf() plt.imshow(image) plt.show() image[np.isnan(image)] = 1e10 # Determine power spectrum # ------------------------------------------------------------------------- # Take the fourier transform of the image. #F1 = fftpack.fft2(np.ma.array(image, mask=np.isnan(image))) F1 = fftpack.fft2(image) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack.fftshift(F1) # Calculate a 2D power spectrum psd2D = np.abs(F2)**2 if 0: plt.close(); plt.clf() plt.imshow(psd2D) plt.show() power_spectrum = radial_average(psd2D, interpnan=True) # Write frequency in arcmin freq = fftpack.fftfreq(len(power_spectrum)) freq *= 5.0 # Simulate power spectrum for white noise noise_image = np.random.normal(scale=0.1, size=image.shape) F1 = fftpack.fft2(noise_image) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack.fftshift(F1) # Calculate a 2D power spectrum psd2D_noise = np.abs(F2)**2 power_spectrum_noise = radial_average(psd2D_noise, interpnan=True) # Plot power spectrum 1D # ------------------------------------------------------------------------- # Set up plot aesthetics plt.clf() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 params = {#'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4.0, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': False, 'figure.figsize': (5, 5), #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() nrows = 1; ncols = 1; ngrids = 1; axes = axes(fig, (1,1,1), nrows_ncols=(nrows, ncols), ngrids=ngrids, axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) ax = axes[0] ax.plot(freq, power_spectrum / np.nanmax(power_spectrum), color='k', linestyle='-', linewidth=1.5, drawstyle='steps-mid', label='Data Residuals') ax.plot(freq, power_spectrum_noise / np.nanmax(power_spectrum_noise), color='r', linestyle='-', linewidth=0.4, drawstyle='steps-mid', label='White Noise Residuals') #ax.set_xscale('log') ax.legend(loc='best') #ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('Spatial Frequency [1/arcmin]') ax.set_ylabel('Normalized Power Spectrum') ax.set_xlim(0, 0.4) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename_prefix is not None: plt.savefig(savedir + filename_prefix + '_1D' + filename_suffix, bbox_inches='tight') if show: plt.show() # Plot power spectrum image # ------------------------- # Create figure instance fig = plt.figure() nrows = 1; ncols = 1; ngrids = 1; axes = axes(fig, (1,1,1), nrows_ncols=(nrows, ncols), ngrids=ngrids, axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) ax = axes[0] extent = [- image.shape[0] / 2.0, + image.shape[0] / 2.0, - image.shape[1] / 2.0, + image.shape[1] / 2.0] ax.imshow(psd2D, origin='lower', cmap=cm.gist_heat, norm=matplotlib.colors.LogNorm(), extent=extent ) #ax.set_xscale('log') #ax.legend(loc='center right') #ax.set_yscale('log') ax.set_xlabel('Spatial Frequency in Right Ascension') ax.set_ylabel('Spatial Frequency in Declination') ax.set_xlim(-20, 20) ax.set_ylim(-20, 20) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename_prefix is not None: plt.savefig(savedir + filename_prefix + '_2D' + filename_suffix, bbox_inches='tight') if show: plt.show()
def plot_avmod_vs_av(avmod_images, av_images, av_errors=None, limits=None, fit=True, savedir='./', filename=None, show=True, scale=('linear','linear'), title = '', gridsize=(100,100), std=None): # Import external modules import numpy as np import math import pyfits as fits import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.axes_grid1 import axes from myscience.krumholz09 import calc_T_cnm from matplotlib import cm n = int(np.ceil(len(av_images)**0.5)) if n**2 - n > len(av_images): nrows = n - 1 ncols = n y_scaling = 1.0 - 1.0 / n else: nrows, ncols = n, n y_scaling = 1.0 # Set up plot aesthetics plt.clf() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 params = {#'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4.0, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': True, 'figure.figsize': (5, 5 * y_scaling), #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() axes = axes(fig, (1,1,1), nrows_ncols=(nrows, ncols), ngrids=len(av_images), axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) # Cycle through lists for i in xrange(len(av_images)): av = av_images[i] avmod = avmod_images[i] av_error = av_errors[i] # Drop the NaNs from the images if type(av_error) is float: indices = np.where((av == av) &\ (avmod == avmod) ) if type(av_error) is np.ndarray or \ type(av_error) is np.ma.core.MaskedArray or \ type(avmod_error) is np.ndarray or \ type(avmod_error) is np.ma.core.MaskedArray: indices = np.where((av == av) &\ (avmod == avmod) &\ (av_error == av_error) ) av_nonans = av[indices] avmod_nonans = avmod[indices] # Fix error data types if type(av_error) is np.ndarray: av_error_nonans = av_error[indices] else: av_error_nonans = np.array(av_error[indices]) # Create plot ax = axes[i] if 1: image = ax.errorbar(av_nonans.ravel(), avmod_nonans.ravel(), xerr=(av_error_nonans.ravel()), alpha=0.2, color='k', marker='^', ecolor='k', linestyle='None', markersize=3 ) if 0: image = ax.hexbin(av_nonans.ravel(), avmod_nonans.ravel(), #norm=matplotlib.colors.LogNorm(), mincnt=1, yscale=scale[1], xscale=scale[0], gridsize=gridsize, cmap=cm.Greys, #cmap=cm.gist_stern, ) cb = ax.cax.colorbar(image,) # Write label to colorbar cb.set_label_text('Bin Counts',) # Plot sensitivies av_limit = np.median(av_errors[0]) ax.axvline(av_limit, color='k', linestyle='--') # Plot 1 to 1 pline ax.plot((0, 10), (0, 10), color='0.5', linewidth=3, alpha=0.5) if std is not None: ax.fill_between((-std, 10), (0, 10 + std), (-2*std, 10 - std), color='0.2', alpha=0.2, edgecolor='none' ) # Annotations anno_xpos = 0.95 ax.set_xscale(scale[0], nonposx = 'clip') ax.set_yscale(scale[1], nonposy = 'clip') if limits is not None: ax.set_xlim(limits[0],limits[1]) ax.set_ylim(limits[2],limits[3]) # Adjust asthetics ax.set_xlabel(r'$A_V$ Data (mag)') ax.set_ylabel(r'$A_V$ Model (mag)') #ax.set_title(core_names[i]) if title is not None: fig.suptitle(title, fontsize=font_scale*1.5) if filename is not None: plt.savefig(savedir + filename, bbox_inches='tight') if show: fig.show()
def plot_av_model(av_image=None, header=None, contour_image=None, av_model=None, hi_velocity_axis=None, vel_range=None, hi_spectrum=None, co_spectrum=None, co_velocity_axis=None, co_scaling=50, hi_limits=None, cores=None, results=None, title=None, limits=None, contours=None, boxes=False, savedir='./', filename=None, show=True, plot_residuals=True): # Import external modules import matplotlib.pyplot as plt import matplotlib import numpy as np from mpl_toolkits.axes_grid1 import axes import pyfits as fits import matplotlib.pyplot as plt import pywcsgrid2 as wcs import pywcs from pylab import cm # colormaps from matplotlib.patches import Polygon # Set up plot aesthetics plt.clf() plt.close() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 if plot_residuals: figsize = (17,8) else: figsize = (13,10) params = {#'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale*3/4, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': False, 'figure.figsize': figsize, 'figure.titlesize': font_scale #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() #========================================================================== # Av maps #========================================================================== if plot_residuals: nrows_ncols=(1,3) ngrids=3 else: nrows_ncols=(1,2) ngrids=2 axes = axes(fig, (2,1,1), nrows_ncols=nrows_ncols, ngrids=ngrids, cbar_mode='each', cbar_location='right', cbar_pad="2%", cbar_size='3%', axes_pad=0.4, axes_class=(wcs.Axes, dict(header=header)), aspect=True, label_mode='L', share_all=True) # ------------------ # Av model # ------------------ # create axes ax = axes[0] cmap = cm.Greys # colormap cmap = cm.gnuplot # colormap cmap.set_bad(color='w') # show the image vmax = np.max((np.max(av_image[av_image == av_image]), np.max(av_model[av_model == av_model]))) vmax = 1.4 im = ax.imshow(av_model, interpolation='nearest',origin='lower', cmap=cmap, vmin=0, vmax=vmax, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)',) ax.set_ylabel('Declination (J2000)',) ax.set_title(r'Model $A_V$') # colorbar cb = ax.cax.colorbar(im) # plot limits if limits is not None: ax.set_xlim(limits[0],limits[2]) ax.set_ylim(limits[1],limits[3]) # Plot Av contours if contour_image is not None: ax.contour(contour_image, levels=contours, colors='r') # Convert sky to pix coordinates wcs_header = pywcs.WCS(header) if type(cores) is dict: for core in cores: pix_coords = cores[core]['center_pixel'] anno_color = (0.3, 0.5, 1) ax.scatter(pix_coords[0],pix_coords[1], color=anno_color, s=200, marker='+', linewidths=2) ax.annotate(core, xy=[pix_coords[0], pix_coords[1]], xytext=(5,5), textcoords='offset points', color=anno_color) if boxes: rect = ax.add_patch(Polygon( cores[core]['box_vertices'][:, ::-1], facecolor='none', edgecolor=anno_color)) # ------------------ # Av image # ------------------ if av_image is not None: # create axes ax = axes[1] # show the image im = ax.imshow(av_image, interpolation='nearest',origin='lower', cmap=cmap, vmin=0, vmax=vmax, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)',) ax.set_ylabel('Declination (J2000)',) ax.set_title(r'Observed $A_V$') # colorbar cb = ax.cax.colorbar(im) #cmap.set_bad(color='c') # plot limits if limits is not None: ax.set_xlim(limits[0],limits[2]) ax.set_ylim(limits[1],limits[3]) # Plot Av contours if contour_image is not None: ax.contour(contour_image, levels=contours, colors='r') # Write label to colorbar #cb.set_label_text(r'$A_V$ (mag)',) # ------------------ # Av residuals # ------------------ if plot_residuals: ax = axes[2] #cmap = cm.Greys # colormap # show the image vmax = np.max((np.max(av_image[av_image == av_image]), np.max(av_model[av_model == av_model]))) vmax = 1.4 im = ax.imshow(av_image - av_model, interpolation='nearest',origin='lower', cmap=cmap, vmin=-0.25, vmax=0.5, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)',) ax.set_ylabel('Declination (J2000)',) ax.set_title(r'Residual $A_V$') # colorbar cb = ax.cax.colorbar(im) #cmap.set_bad(color='w') # plot limits if limits is not None: ax.set_xlim(limits[0],limits[2]) ax.set_ylim(limits[1],limits[3]) # ========================================================================== # HI Spectrum # ========================================================================== vel_range = np.asarray(results['hi_velocity_range'][:2]) # create axes ax = fig.add_subplot(2,1,2) ax.plot(hi_velocity_axis, hi_spectrum, color='k', drawstyle = 'steps-mid', label='HI', ) if co_spectrum is not None: ax.plot(co_velocity_axis, co_spectrum*co_scaling, color='r', drawstyle='steps-mid', label=r'CO x ' + str(co_scaling), ) ax.legend(loc='upper right') # Plot velocity range if vel_range.ndim == 1: ax.axvspan(vel_range[0], vel_range[1], color='k', alpha=0.3) elif vel_range.ndim == 2: for i in xrange(0, vel_range.shape[0]): ax.axvspan(vel_range[i, 0], vel_range[i, 1], color='k', alpha=0.3) # Plot center ax.axvline(results['co_center']['value'], color='k', linestyle='--', ) if hi_limits is not None: ax.set_xlim(hi_limits[0], hi_limits[1]) ax.set_ylim(hi_limits[2], hi_limits[3]) ax.set_xlabel('Velocity (km/s)') ax.set_ylabel(r'T$_b$ (K)') # Plot results if results is not None: av_thres = results['av_threshold']['value'] co_thres = results['co_threshold']['value'] if av_thres > 15: av_thres = None text = '' text += r'N$_{\rm pix}$ = ' + \ '{0:.0f}'.format(results['npix']) text += '\n' if av_thres is not None: text += r'$A_V$ threshold = ' + \ '{0:.1f} mag'.format(av_thres) else: text += r'$A_V$ threshold = ' + \ '{0:s}'.format(av_thres) text += '\n' text += r'CO threshold = ' + \ '{0:.1f} K km/s'.format(co_thres) text += '\n' text += r'DGR = {0:.2f} '.format(results['dust2gas_ratio']['value']) + \ r'$\times$ 10$^{-20}$ (cm$^2$ mag$^1$)' text += '\n' if vel_range.ndim == 1: text += r'Velocity range = ' + \ '{0:.1f} to {1:.1f} km/s'.format(vel_range[0], vel_range[1]) text += '\n' text += r'$\chi^2$ / $\nu$ = {0:.1f}'.format(results['chisq']) ax.annotate(text, xytext=(0.03, 0.95), xy=(0.03, 0.95), textcoords='axes fraction', xycoords='axes fraction', color='k', fontsize=font_scale*0.75, bbox=dict(boxstyle='round', facecolor='w', alpha=0.8), horizontalalignment='left', verticalalignment='top', ) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename is not None: plt.savefig(savedir + filename, bbox_inches='tight') if show: plt.show()
def plot_power_spectrum(image, title=None, filename_prefix=None, filename_suffix='.png', show=False, savedir='./'): ''' Plots power spectrum derived from a fourier transform of the image. ''' # import external modules import numpy as np from agpy import azimuthalAverage as radial_average from scipy import fftpack import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.axes_grid1 import axes from matplotlib import cm if 0: plt.close() plt.clf() plt.imshow(image) plt.show() image[np.isnan(image)] = 1e10 # Determine power spectrum # ------------------------------------------------------------------------- # Take the fourier transform of the image. #F1 = fftpack.fft2(np.ma.array(image, mask=np.isnan(image))) F1 = fftpack.fft2(image) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack.fftshift(F1) # Calculate a 2D power spectrum psd2D = np.abs(F2)**2 if 0: plt.close() plt.clf() plt.imshow(psd2D) plt.show() power_spectrum = radial_average(psd2D, interpnan=True) # Write frequency in arcmin freq = fftpack.fftfreq(len(power_spectrum)) freq *= 5.0 # Simulate power spectrum for white noise noise_image = np.random.normal(scale=0.1, size=image.shape) F1 = fftpack.fft2(noise_image) # Now shift the quadrants around so that low spatial frequencies are in # the center of the 2D fourier transformed image. F2 = fftpack.fftshift(F1) # Calculate a 2D power spectrum psd2D_noise = np.abs(F2)**2 power_spectrum_noise = radial_average(psd2D_noise, interpnan=True) # Plot power spectrum 1D # ------------------------------------------------------------------------- # Set up plot aesthetics plt.clf() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 params = { #'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4.0, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': False, 'figure.figsize': (5, 5), #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() nrows = 1 ncols = 1 ngrids = 1 axes = axes( fig, (1, 1, 1), nrows_ncols=(nrows, ncols), ngrids=ngrids, axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) ax = axes[0] ax.plot(freq, power_spectrum / np.nanmax(power_spectrum), color='k', linestyle='-', linewidth=1.5, drawstyle='steps-mid', label='Data Residuals') ax.plot(freq, power_spectrum_noise / np.nanmax(power_spectrum_noise), color='r', linestyle='-', linewidth=0.4, drawstyle='steps-mid', label='White Noise Residuals') #ax.set_xscale('log') ax.legend(loc='best') #ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('Spatial Frequency [1/arcmin]') ax.set_ylabel('Normalized Power Spectrum') ax.set_xlim(0, 0.4) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename_prefix is not None: plt.savefig(savedir + filename_prefix + '_1D' + filename_suffix, bbox_inches='tight') if show: plt.show() # Plot power spectrum image # ------------------------- # Create figure instance fig = plt.figure() nrows = 1 ncols = 1 ngrids = 1 axes = axes( fig, (1, 1, 1), nrows_ncols=(nrows, ncols), ngrids=ngrids, axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) ax = axes[0] extent = [ -image.shape[0] / 2.0, +image.shape[0] / 2.0, -image.shape[1] / 2.0, +image.shape[1] / 2.0 ] ax.imshow(psd2D, origin='lower', cmap=cm.gist_heat, norm=matplotlib.colors.LogNorm(), extent=extent) #ax.set_xscale('log') #ax.legend(loc='center right') #ax.set_yscale('log') ax.set_xlabel('Spatial Frequency in Right Ascension') ax.set_ylabel('Spatial Frequency in Declination') ax.set_xlim(-20, 20) ax.set_ylim(-20, 20) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename_prefix is not None: plt.savefig(savedir + filename_prefix + '_2D' + filename_suffix, bbox_inches='tight') if show: plt.show()
def plot_avmod_vs_av(avmod_images, av_images, av_errors=None, limits=None, fit=True, savedir='./', filename=None, show=True, scale=('linear', 'linear'), title='', gridsize=(100, 100), std=None): # Import external modules import numpy as np import math import pyfits as fits import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.axes_grid1 import axes from myscience.krumholz09 import calc_T_cnm from matplotlib import cm n = int(np.ceil(len(av_images)**0.5)) if n**2 - n > len(av_images): nrows = n - 1 ncols = n y_scaling = 1.0 - 1.0 / n else: nrows, ncols = n, n y_scaling = 1.0 # Set up plot aesthetics plt.clf() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 params = { #'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4.0, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': True, 'figure.figsize': (5, 5 * y_scaling), #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() axes = axes( fig, (1, 1, 1), nrows_ncols=(nrows, ncols), ngrids=len(av_images), axes_pad=0.25, aspect=False, label_mode='L', share_all=True, #cbar_mode='single', cbar_pad=0.1, cbar_size=0.2, ) # Cycle through lists for i in xrange(len(av_images)): av = av_images[i] avmod = avmod_images[i] av_error = av_errors[i] # Drop the NaNs from the images if type(av_error) is float: indices = np.where((av == av) &\ (avmod == avmod) ) if type(av_error) is np.ndarray or \ type(av_error) is np.ma.core.MaskedArray or \ type(avmod_error) is np.ndarray or \ type(avmod_error) is np.ma.core.MaskedArray: indices = np.where((av == av) &\ (avmod == avmod) &\ (av_error == av_error) ) av_nonans = av[indices] avmod_nonans = avmod[indices] # Fix error data types if type(av_error) is np.ndarray: av_error_nonans = av_error[indices] else: av_error_nonans = np.array(av_error[indices]) # Create plot ax = axes[i] if 1: image = ax.errorbar(av_nonans.ravel(), avmod_nonans.ravel(), xerr=(av_error_nonans.ravel()), alpha=0.2, color='k', marker='^', ecolor='k', linestyle='None', markersize=3) if 0: image = ax.hexbin( av_nonans.ravel(), avmod_nonans.ravel(), #norm=matplotlib.colors.LogNorm(), mincnt=1, yscale=scale[1], xscale=scale[0], gridsize=gridsize, cmap=cm.Greys, #cmap=cm.gist_stern, ) cb = ax.cax.colorbar(image, ) # Write label to colorbar cb.set_label_text('Bin Counts', ) # Plot sensitivies av_limit = np.median(av_errors[0]) ax.axvline(av_limit, color='k', linestyle='--') # Plot 1 to 1 pline ax.plot((0, 10), (0, 10), color='0.5', linewidth=3, alpha=0.5) if std is not None: ax.fill_between((-std, 10), (0, 10 + std), (-2 * std, 10 - std), color='0.2', alpha=0.2, edgecolor='none') # Annotations anno_xpos = 0.95 ax.set_xscale(scale[0], nonposx='clip') ax.set_yscale(scale[1], nonposy='clip') if limits is not None: ax.set_xlim(limits[0], limits[1]) ax.set_ylim(limits[2], limits[3]) # Adjust asthetics ax.set_xlabel(r'$A_V$ Data (mag)') ax.set_ylabel(r'$A_V$ Model (mag)') #ax.set_title(core_names[i]) if title is not None: fig.suptitle(title, fontsize=font_scale * 1.5) if filename is not None: plt.savefig(savedir + filename, bbox_inches='tight') if show: fig.show()
def plot_av_model(av_image=None, header=None, contour_image=None, av_model=None, hi_velocity_axis=None, vel_range=None, hi_spectrum=None, co_spectrum=None, co_velocity_axis=None, co_scaling=50, hi_limits=None, cores=None, results=None, title=None, limits=None, contours=None, boxes=False, savedir='./', filename=None, show=True, plot_residuals=True): # Import external modules import matplotlib.pyplot as plt import matplotlib import numpy as np from mpl_toolkits.axes_grid1 import axes import pyfits as fits import matplotlib.pyplot as plt import pywcsgrid2 as wcs import pywcs from pylab import cm # colormaps from matplotlib.patches import Polygon # Set up plot aesthetics plt.clf() plt.close() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 if plot_residuals: figsize = (17, 8) else: figsize = (13, 10) params = { #'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': False, 'figure.figsize': figsize, 'figure.titlesize': font_scale #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) # Create figure instance fig = plt.figure() #========================================================================== # Av maps #========================================================================== if plot_residuals: nrows_ncols = (1, 3) ngrids = 3 else: nrows_ncols = (1, 2) ngrids = 2 axes = axes(fig, (2, 1, 1), nrows_ncols=nrows_ncols, ngrids=ngrids, cbar_mode='each', cbar_location='right', cbar_pad="2%", cbar_size='3%', axes_pad=0.4, axes_class=(wcs.Axes, dict(header=header)), aspect=True, label_mode='L', share_all=True) # ------------------ # Av model # ------------------ # create axes ax = axes[0] cmap = cm.Greys # colormap cmap = cm.gnuplot # colormap cmap.set_bad(color='w') # show the image vmax = np.max((np.max(av_image[av_image == av_image]), np.max(av_model[av_model == av_model]))) vmax = 1.4 im = ax.imshow( av_model, interpolation='nearest', origin='lower', cmap=cmap, vmin=0, vmax=vmax, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)', ) ax.set_ylabel('Declination (J2000)', ) ax.set_title(r'Model $A_V$') # colorbar cb = ax.cax.colorbar(im) # plot limits if limits is not None: ax.set_xlim(limits[0], limits[2]) ax.set_ylim(limits[1], limits[3]) # Plot Av contours if contour_image is not None: ax.contour(contour_image, levels=contours, colors='r') # Convert sky to pix coordinates wcs_header = pywcs.WCS(header) if type(cores) is dict: for core in cores: pix_coords = cores[core]['center_pixel'] anno_color = (0.3, 0.5, 1) ax.scatter(pix_coords[0], pix_coords[1], color=anno_color, s=200, marker='+', linewidths=2) ax.annotate(core, xy=[pix_coords[0], pix_coords[1]], xytext=(5, 5), textcoords='offset points', color=anno_color) if boxes: rect = ax.add_patch( Polygon(cores[core]['box_vertices'][:, ::-1], facecolor='none', edgecolor=anno_color)) # ------------------ # Av image # ------------------ if av_image is not None: # create axes ax = axes[1] # show the image im = ax.imshow( av_image, interpolation='nearest', origin='lower', cmap=cmap, vmin=0, vmax=vmax, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)', ) ax.set_ylabel('Declination (J2000)', ) ax.set_title(r'Observed $A_V$') # colorbar cb = ax.cax.colorbar(im) #cmap.set_bad(color='c') # plot limits if limits is not None: ax.set_xlim(limits[0], limits[2]) ax.set_ylim(limits[1], limits[3]) # Plot Av contours if contour_image is not None: ax.contour(contour_image, levels=contours, colors='r') # Write label to colorbar #cb.set_label_text(r'$A_V$ (mag)',) # ------------------ # Av residuals # ------------------ if plot_residuals: ax = axes[2] #cmap = cm.Greys # colormap # show the image vmax = np.max((np.max(av_image[av_image == av_image]), np.max(av_model[av_model == av_model]))) vmax = 1.4 im = ax.imshow( av_image - av_model, interpolation='nearest', origin='lower', cmap=cmap, vmin=-0.25, vmax=0.5, #norm=matplotlib.colors.LogNorm() ) # Asthetics ax.set_display_coord_system("fk5") ax.set_ticklabel_type("hms", "dms") ax.set_xlabel('Right Ascension (J2000)', ) ax.set_ylabel('Declination (J2000)', ) ax.set_title(r'Residual $A_V$') # colorbar cb = ax.cax.colorbar(im) #cmap.set_bad(color='w') # plot limits if limits is not None: ax.set_xlim(limits[0], limits[2]) ax.set_ylim(limits[1], limits[3]) # ========================================================================== # HI Spectrum # ========================================================================== vel_range = np.asarray(results['hi_velocity_range'][:2]) # create axes ax = fig.add_subplot(2, 1, 2) ax.plot( hi_velocity_axis, hi_spectrum, color='k', drawstyle='steps-mid', label='HI', ) if co_spectrum is not None: ax.plot( co_velocity_axis, co_spectrum * co_scaling, color='r', drawstyle='steps-mid', label=r'CO x ' + str(co_scaling), ) ax.legend(loc='upper right') # Plot velocity range if vel_range.ndim == 1: ax.axvspan(vel_range[0], vel_range[1], color='k', alpha=0.3) elif vel_range.ndim == 2: for i in xrange(0, vel_range.shape[0]): ax.axvspan(vel_range[i, 0], vel_range[i, 1], color='k', alpha=0.3) # Plot center ax.axvline( results['co_center']['value'], color='k', linestyle='--', ) if hi_limits is not None: ax.set_xlim(hi_limits[0], hi_limits[1]) ax.set_ylim(hi_limits[2], hi_limits[3]) ax.set_xlabel('Velocity (km/s)') ax.set_ylabel(r'T$_b$ (K)') # Plot results if results is not None: av_thres = results['av_threshold']['value'] co_thres = results['co_threshold']['value'] if av_thres > 15: av_thres = None text = '' text += r'N$_{\rm pix}$ = ' + \ '{0:.0f}'.format(results['npix']) text += '\n' if av_thres is not None: text += r'$A_V$ threshold = ' + \ '{0:.1f} mag'.format(av_thres) else: text += r'$A_V$ threshold = ' + \ '{0:s}'.format(av_thres) text += '\n' text += r'CO threshold = ' + \ '{0:.1f} K km/s'.format(co_thres) text += '\n' text += r'DGR = {0:.2f} '.format(results['dust2gas_ratio']['value']) + \ r'$\times$ 10$^{-20}$ (cm$^2$ mag$^1$)' text += '\n' if vel_range.ndim == 1: text += r'Velocity range = ' + \ '{0:.1f} to {1:.1f} km/s'.format(vel_range[0], vel_range[1]) text += '\n' text += r'$\chi^2$ / $\nu$ = {0:.1f}'.format(results['chisq']) ax.annotate( text, xytext=(0.03, 0.95), xy=(0.03, 0.95), textcoords='axes fraction', xycoords='axes fraction', color='k', fontsize=font_scale * 0.75, bbox=dict(boxstyle='round', facecolor='w', alpha=0.8), horizontalalignment='left', verticalalignment='top', ) if title is not None: fig.suptitle(title, fontsize=font_scale) if filename is not None: plt.savefig(savedir + filename, bbox_inches='tight') if show: plt.show()