def plotimagewcs(fits_image, fig, location=[0, 1, 0, 1], vmin=0, vmax=4, haflag=0): rfits = fits.open(fits_image) im = rfits[0].data.copy() wcs = WCS(rfits[0].header) rfits.close() ax = WCSAxes(fig, location, wcs=wcs) fig.add_axes(ax) axis('equal') if haflag: ny, nx = im.shape #imshow((im[int(.25*nx):int(.75*nx),int(.25*ny):int(.75*ny)]),interpolation='nearest',origin='upper',cmap='binary',vmin=vmin,vmax=vmax) ax.imshow((im), interpolation='nearest', cmap=cm.gray_r, vmin=vmin, vmax=vmax, origin='lower') else: ax.imshow((im), interpolation='nearest', cmap=cm.gray_r, vmin=vmin, vmax=vmax, origin='lower')
def test_direct_init(self, generate): s = DistanceToLonLat(R=6378.273) coord_meta = {} coord_meta['type'] = ('longitude', 'latitude') coord_meta['wrap'] = (360., None) coord_meta['unit'] = (u.deg, u.deg) coord_meta['name'] = 'lon', 'lat' fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], transform=s, coord_meta=coord_meta) fig.add_axes(ax) ax.coords['lon'].grid(color='red', linestyle='solid', alpha=0.3) ax.coords['lat'].grid(color='blue', linestyle='solid', alpha=0.3) ax.coords['lon'].set_ticklabel(size=7) ax.coords['lat'].set_ticklabel(size=7) ax.coords['lon'].set_ticklabel_position('brtl') ax.coords['lat'].set_ticklabel_position('brtl') ax.coords['lon'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True) ax.coords['lat'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True) ax.set_xlim(-400., 500.) ax.set_ylim(-300., 400.) self.generate_or_test(generate, fig, 'direct_init.png')
def integrated_map_axes_lb(fig, ax_limits, datacube, wcs_object, integration_limits, cmap=dame_cmap): """ Hackish way of exporting the above behavior to an ax object. But it's actually on-the-sky. """ ax = WCSAxes(fig, ax_limits, wcs=wcs_object, slices=('x', 'y', 0)) fig.add_axes(ax) min_v_px, max_v_px = velocity_world2pix(wcs_object, integration_limits) min_v_px, max_v_px = sanitize_integration_limits((min_v_px, max_v_px), datacube, axis=0) array_lb = np.nansum(datacube[min_v_px:max_v_px, :, :], axis=0) array_lb[(array_lb < 0) | np.isinf(array_lb) | np.isnan(array_lb)] = 0 ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km / u.s image_lb = ax.imshow(np.log10(array_lb + 1), origin='lower', interpolation='nearest', cmap=cmap, aspect=1) return ax
def query_time_series(): data = np.loadtxt("dataserver_queries.csv", comments='#', delimiter=',', usecols=(1, 2)) dates = [] with open('dataserver_queries.csv') as cvsfile: for row in csv.reader(cvsfile): if row[0][0] == "#": continue dates.append(datetime.datetime.strptime(row[0], "%Y-%m-%d")) FERMI_5YEAR_IMAGE = os.path.join(os.environ['GSSC_REFDATA'], \ 'Fermi_All_Sky_5year_GC.fits') fig = pt.figure(figsize=(10, 5)) hdu = fits.open(fits_file)[0] # Setup the axes ax = WCSAxes(fig, [0.0, 0.0, 1.0, 1.0], wcs=WCS(hdu.header)) fig.add_axes(ax) ax.set_xlim(-0.5, hdu.data.shape[1] - 0.5) ax.set_ylim(-0.5, hdu.data.shape[0] - 0.5) # Increase the default number of latitude grid lines. ax.coords[0].set_ticks(number=6) # Read in and scale the image. ax.imshow(hdu.data, origin='lower', cmap=pt.cm.CMRmap) # Add a coordinate grid. ax.grid(True, color='white', linestyle='solid', alpha=0.5)
def test_image_plot(self, generate): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(self.msx_header), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) ax.coords[0].set_ticks([-0.30, 0., 0.20] * u.degree, size=5, width=1) self.generate_or_test(generate, fig, 'image_plot.png')
def __init__(self, pw): try: # Attempt import from the old WCSAxes package first from wcsaxes import WCSAxes issue_deprecation_warning("Support for the standalone 'wcsaxes' " "package is deprecated since its" "functionality has been merged into" "AstroPy, and will be removed in a " "future release. It is recommended to " "use the version bundled with AstroPy " ">= 1.3.") except ImportError: # Try to use the AstroPy version WCSAxes = _astropy.wcsaxes.WCSAxes if pw.oblique: raise NotImplementedError( "WCS axes are not implemented for oblique plots.") if not hasattr(pw.ds, "wcs_2d"): raise NotImplementedError( "WCS axes are not implemented for this dataset.") if pw.data_source.axis != pw.ds.spec_axis: raise NotImplementedError( "WCS axes are not implemented for this axis.") self.plots = {} self.pw = pw for f in pw.plots: rect = pw.plots[f]._get_best_layout()[1] fig = pw.plots[f].figure ax = fig.axes[0] wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False) fig.add_axes(wcs_ax) wcs = pw.ds.wcs_2d.wcs xax = pw.ds.coordinates.x_axis[pw.data_source.axis] yax = pw.ds.coordinates.y_axis[pw.data_source.axis] xlabel = "%s (%s)" % (wcs.ctype[xax].split("-")[0], wcs.cunit[xax]) ylabel = "%s (%s)" % (wcs.ctype[yax].split("-")[0], wcs.cunit[yax]) fp = pw._font_properties wcs_ax.coords[0].set_axislabel(xlabel, fontproperties=fp, minpad=0.5) wcs_ax.coords[1].set_axislabel(ylabel, fontproperties=fp, minpad=0.4) wcs_ax.coords[0].ticklabels.set_fontproperties(fp) wcs_ax.coords[1].ticklabels.set_fontproperties(fp) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value) wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value) wcs_ax.coords.frame._update_cache = [] ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) self.plots[f] = fig
def time_basic_plot(self): fig = Figure() canvas = FigureCanvas(fig) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header)) fig.add_axes(ax) ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) canvas.draw()
def time_basic_plot_with_grid(self): fig = Figure() canvas = FigureCanvas(fig) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header)) fig.add_axes(ax) ax.grid(color='red', alpha=0.5, linestyle='solid') ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) canvas.draw()
def test_set_coord_type(self, generate): fig = plt.figure(figsize=(3, 3)) ax = WCSAxes(fig, [0.2, 0.2, 0.6, 0.6], wcs=WCS(self.msx_header), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) ax.coords[0].set_coord_type('scalar') ax.coords[1].set_coord_type('scalar') ax.coords[0].set_major_formatter('x.xxx') ax.coords[1].set_major_formatter('x.xxx') ax.coords[0].set_ticks(exclude_overlapping=True) ax.coords[1].set_ticks(exclude_overlapping=True) self.generate_or_test(generate, fig, 'set_coord_type.png')
def test_changed_axis_units(self, generate): w = WCS(self.cube_header) fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[2].set_major_formatter('x.xx') ax.coords[2].set_format_unit(u.km / u.s) ax.coords[2].set_axislabel('Velocity km/s') ax.coords[1].set_ticks(width=1, exclude_overlapping=True) ax.coords[2].set_ticks(width=1, exclude_overlapping=True) self.generate_or_test(generate, fig, 'changed_axis_units.png')
def test_minor_ticks(self, generate): w = WCS(self.cube_header) fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[2].set_ticks(exclude_overlapping=True) ax.coords[1].set_ticks(exclude_overlapping=True) ax.coords[2].display_minor_ticks(True) ax.coords[1].display_minor_ticks(True) ax.coords[2].set_minor_frequency(3) ax.coords[1].set_minor_frequency(10) self.generate_or_test(generate, fig, 'minor_ticks_image.png')
def test_cube_slice_image(self, generate): w = WCS(self.cube_header) fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], w, slices=(50, 'y', 'x'), aspect='equal') fig.add_axes(ax) ax.grid(grid_type='contours') ax.set_xlim(-0.5, 52.5) ax.set_ylim(-0.5, 106.5) ax.coords[2].set_axislabel('Velocity m/s') ax.coords[1].set_ticks(width=1, exclude_overlapping=True) ax.coords[2].set_ticks(width=1, exclude_overlapping=True) ax.grid(grid_type='contours', color='red') ax.grid(grid_type='contours', linestyle='solid') self.generate_or_test(generate, fig, 'cube_slice_image.png')
def test_contour_overlay(self, generate): hdu_msx = datasets.msx_hdu() wcs_msx = WCS(self.msx_header) fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.15, 0.15, 0.8, 0.8], wcs=WCS(self.twoMASS_k_header), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 720.5) ax.set_ylim(-0.5, 720.5) # Overplot contour ax.contour(hdu_msx.data, transform=ax.get_transform(wcs_msx), colors='orange', levels=[2.5e-5, 5e-5, 1.e-4]) ax.coords[0].set_ticks(size=5, width=1) ax.coords[1].set_ticks(size=5, width=1) ax.set_xlim(0., 720.) ax.set_ylim(0., 720.) self.generate_or_test(generate, fig, 'contour_overlay.png')
def test_tick_angles_non_square_axes(self, generate): w = WCS() w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] w.wcs.crval = [90, 70] w.wcs.cdelt = [16, 16] w.wcs.crpix = [1, 1] w.wcs.radesys = 'ICRS' w.wcs.equinox = 2000.0 fig = plt.figure(figsize=(6, 3)) ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=w) fig.add_axes(ax) ax.set_xlim(1, -1) ax.set_ylim(-1, 1) ax.grid(color='gray', alpha=0.5, linestyle='solid') ax.coords['ra'].set_ticks(color='red', size=20) ax.coords['dec'].set_ticks(color='red', size=20) self.generate_or_test(generate, fig, 'tick_angles_non_square_axes.png')
def test_curvilinear_grid_patches_image(self, generate): fig = plt.figure(figsize=(8, 8)) ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=WCS(self.rosat_header), aspect='equal') fig.add_axes(ax) ax.set_xlim(-0.5, 479.5) ax.set_ylim(-0.5, 239.5) ax.grid(color='black', alpha=1.0, lw=1, linestyle='dashed') p = Circle((300, 100), radius=40, ec='yellow', fc='none') ax.add_patch(p) p = Circle((30., 20.), radius=20., ec='orange', fc='none', transform=ax.get_transform('world')) ax.add_patch(p) p = Circle((60., 50.), radius=20., ec='red', fc='none', transform=ax.get_transform('fk5')) ax.add_patch(p) p = Circle((40., 60.), radius=20., ec='green', fc='none', transform=ax.get_transform('galactic')) ax.add_patch(p) self.generate_or_test(generate, fig, 'curvlinear_grid_patches_image.png')
def test_coords_overlay(self, generate): # Set up a simple WCS that maps pixels to non-projected distances wcs = WCS(naxis=2) wcs.wcs.ctype = ['x', 'y'] wcs.wcs.cunit = ['km', 'km'] wcs.wcs.crpix = [614.5, 856.5] wcs.wcs.cdelt = [6.25, 6.25] wcs.wcs.crval = [0., 0.] fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs) fig.add_axes(ax) s = DistanceToLonLat(R=6378.273) ax.coords['x'].set_ticklabel_position('') ax.coords['y'].set_ticklabel_position('') coord_meta = {} coord_meta['type'] = ('longitude', 'latitude') coord_meta['wrap'] = (360., None) coord_meta['unit'] = (u.deg, u.deg) coord_meta['name'] = 'lon', 'lat' overlay = ax.get_coords_overlay(s, coord_meta=coord_meta) overlay.grid(color='red') overlay['lon'].grid(color='red', linestyle='solid', alpha=0.3) overlay['lat'].grid(color='blue', linestyle='solid', alpha=0.3) overlay['lon'].set_ticklabel(size=7) overlay['lat'].set_ticklabel(size=7) overlay['lon'].set_ticklabel_position('brtl') overlay['lat'].set_ticklabel_position('brtl') overlay['lon'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True) overlay['lat'].set_ticks(spacing=10. * u.deg, exclude_overlapping=True) ax.set_xlim(-0.5, 1215.5) ax.set_ylim(-0.5, 1791.5) self.generate_or_test(generate, fig, 'coords_overlay.png')
def test_rcparams(self, generate): with rc_context({ 'xtick.color': 'red', 'xtick.major.size': 20, 'xtick.major.width': 2, 'grid.color': 'blue', 'grid.linestle': ':.', 'grid.linewidth': 1, 'grid.alpha': 0.5}): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None) fig.add_axes(ax) ax.set_xlim(-0.5, 2) ax.set_ylim(-0.5, 2) ax.grid() ax.coords[0].set_ticks(exclude_overlapping=True) ax.coords[1].set_ticks(exclude_overlapping=True) self.generate_or_test(generate, fig, 'rcparams.png')
def test_ticks_labels(self, generate): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.1, 0.1, 0.7, 0.7], wcs=None) fig.add_axes(ax) ax.set_xlim(-0.5, 2) ax.set_ylim(-0.5, 2) ax.coords[0].set_ticks(size=10, color='blue', alpha=0.2, width=1) ax.coords[1].set_ticks(size=20, color='red', alpha=0.9, width=1) ax.coords[0].set_ticks_position('all') ax.coords[1].set_ticks_position('all') ax.coords[0].set_axislabel('X-axis', size=20) ax.coords[1].set_axislabel('Y-axis', color='green', size=25, weight='regular', style='normal', family='monospace') ax.coords[0].set_axislabel_position('t') ax.coords[1].set_axislabel_position('r') ax.coords[0].set_ticklabel(color='purple', size=15, alpha=1, weight='light', style='normal', family='sans-serif') ax.coords[1].set_ticklabel(color='black', size=18, alpha=0.9, weight='bold', family='serif') ax.coords[0].set_ticklabel_position('all') ax.coords[1].set_ticklabel_position('r') self.generate_or_test(generate, fig, 'ticks_labels.png', bbox_inches='tight')
def __init__(self, pw): from wcsaxes import WCSAxes if pw.oblique: raise NotImplementedError( "WCS axes are not implemented for oblique plots.") if not hasattr(pw.ds, "wcs_2d"): raise NotImplementedError( "WCS axes are not implemented for this dataset.") if pw.data_source.axis != pw.ds.spec_axis: raise NotImplementedError( "WCS axes are not implemented for this axis.") self.plots = {} self.pw = pw for f in pw.plots: rect = pw.plots[f]._get_best_layout()[1] fig = pw.plots[f].figure ax = fig.axes[0] wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False) fig.add_axes(wcs_ax) wcs = pw.ds.wcs_2d.wcs xax = pw.ds.coordinates.x_axis[pw.data_source.axis] yax = pw.ds.coordinates.y_axis[pw.data_source.axis] xlabel = "%s (%s)" % (wcs.ctype[xax].split("-")[0], wcs.cunit[xax]) ylabel = "%s (%s)" % (wcs.ctype[yax].split("-")[0], wcs.cunit[yax]) fp = pw._font_properties wcs_ax.coords[0].set_axislabel(xlabel, fontproperties=fp, minpad=0.5) wcs_ax.coords[1].set_axislabel(ylabel, fontproperties=fp, minpad=0.4) wcs_ax.coords[0].ticklabels.set_fontproperties(fp) wcs_ax.coords[1].ticklabels.set_fontproperties(fp) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value) wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value) wcs_ax.coords.frame._update_cache = [] ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) self.plots[f] = fig
def test_coords_overlay_auto_coord_meta(self, generate): fig = plt.figure(figsize=(4, 4)) ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header)) fig.add_axes(ax) ax.grid(color='red', alpha=0.5, linestyle='solid') overlay = ax.get_coords_overlay('fk5') # automatically sets coord_meta overlay.grid(color='black', alpha=0.5, linestyle='solid') overlay['ra'].set_ticks(color='black') overlay['dec'].set_ticks(color='black') ax.set_xlim(-0.5, 148.5) ax.set_ylim(-0.5, 148.5) self.generate_or_test(generate, fig, 'coords_overlay_auto_coord_meta.png')
def integrated_map_axes_lv(fig, ax_limits, datacube, wcs_object, integration_limits, aspect_in_units=5 * (u.km / u.s) / u.deg, latitude_px_override=None, cmap=dame_cmap): """ Hackish way of exporting the above behavior to an ax object. """ ax = WCSAxes(fig, ax_limits, wcs=wcs_object, slices=('x', 0, 'y')) fig.add_axes(ax) if latitude_px_override is None: min_b_px, max_b_px = latitude_world2pix(wcs_object, integration_limits) min_b_px, max_b_px = sanitize_integration_limits((min_b_px, max_b_px), datacube, axis=1) else: min_b_px, max_b_px = latitude_px_override array_lv = np.nansum(datacube[:, min_b_px:max_b_px, :], axis=1) array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0 ax.spatial_scale = np.abs(wcs_object.wcs.cdelt[0]) * u.deg ax.velocity_scale = np.abs(wcs_object.wcs.cdelt[2]) * u.km / u.s ax.aspect_px = (ax.velocity_scale / ax.spatial_scale) / aspect_in_units image_lv = ax.imshow(np.log10(array_lv + 1), origin='lower', interpolation='nearest', cmap=cmap, aspect=ax.aspect_px) return ax
def test_overlay_features_image(self, generate): fig = plt.figure(figsize=(6, 6)) ax = WCSAxes(fig, [0.25, 0.25, 0.65, 0.65], wcs=WCS(self.msx_header), aspect='equal') fig.add_axes(ax) # Change the format of the ticks ax.coords[0].set_major_formatter('dd:mm:ss') ax.coords[1].set_major_formatter('dd:mm:ss.ssss') # Overlay grid on image ax.grid(color='red', alpha=1.0, lw=1, linestyle='dashed') # Set the spacing of ticks on the 'glon' axis to 4 arcsec ax.coords['glon'].set_ticks(spacing=4 * u.arcsec, size=5, width=1) # Set the number of ticks on the 'glat' axis to 9 ax.coords['glat'].set_ticks(number=9, size=5, width=1) # Set labels on axes ax.coords['glon'].set_axislabel('Galactic Longitude', minpad=1.6) ax.coords['glat'].set_axislabel('Galactic Latitude', minpad=-0.75) # Change the frame linewidth and color ax.coords.frame.set_color('red') ax.coords.frame.set_linewidth(2) self.generate_or_test(generate, fig, 'overlay_features_image.png')
def __init__(self, datacube, wcs_object, aspect_in_units=5 * (u.km / u.s) / u.deg, cmap=dame_cmap, integration_limits=(-1, 1), figsize=(10, 9), vmin=None, vmax=None): self.datacube = datacube self.wcs = wcs_object self.fig = plt.figure(figsize=figsize) self.cmap = cmap self.vmin = vmin self.vmax = vmax ax = WCSAxes(self.fig, [0.1, 0.1, 0.8, 0.8], wcs=self.wcs, slices=('x', 0, 'y')) self.ax = self.fig.add_axes(ax) min_b_px, max_b_px = latitude_world2pix(self.wcs, integration_limits) array_lv = np.nansum(self.datacube[:, min_b_px:max_b_px, :], axis=1) array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0 self.array_lv = array_lv self.spatial_scale = np.abs(self.wcs.wcs.cdelt[0]) * u.deg self.velocity_scale = np.abs(self.wcs.wcs.cdelt[2]) * u.km / u.s self.aspect_px = (self.velocity_scale / self.spatial_scale) / aspect_in_units self._draw_plot()
def plotFluxRatioSky(predFlux, measFlux, x, y, RA, Dec, midRA, midDec, labels, outDir, name1, name2, format): """ Makes sky plot of measured-to-predicted flux ratio """ import os import numpy as np from ..operations_lib import calculateSeparation, makeWCS try: from astropy.stats.funcs import sigma_clip except ImportError: from astropy.stats import sigma_clip try: import matplotlib if matplotlib.get_backend() is not 'Agg': matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.colors as colors from matplotlib.ticker import FuncFormatter except Exception as e: raise ImportError('PyPlot could not be imported. Plotting is not ' 'available: {0}'.format(e.message)) try: from wcsaxes import WCSAxes hasWCSaxes = True except: hasWCSaxes = False if name1 is None: name1 = 'Model 1' if name2 is None: name2 = 'Model 2' ratio = measFlux / predFlux fig = plt.figure(figsize=(7.0, 5.0)) if hasWCSaxes: wcs = makeWCS(midRA, midDec) ax1 = WCSAxes(fig, [0.12, 0.12, 0.8, 0.8], wcs=wcs) fig.add_axes(ax1) else: ax1 = plt.gca() plt.title('Flux Density Ratios ({0} / {1})'.format(name1, name2)) # Set symbol color by ratio vmin = np.min(ratio) - 0.1 vmax = np.max(ratio) + 0.1 sm = plt.cm.ScalarMappable(cmap=plt.cm.jet, norm=colors.Normalize(vmin=vmin, vmax=vmax)) sm.set_array(ratio) sm._A = [] c = [] for r in ratio: c.append(sm.to_rgba(r)) if hasWCSaxes: ax1.set_xlim(np.min(x) - 20, np.max(x) + 20) ax1.set_ylim(np.min(y) - 20, np.max(y) + 20) plot = plt.scatter(x, y, c=c) cbar = plt.colorbar(sm) # Set axis labels, etc. if hasWCSaxes: RAAxis = ax1.coords['ra'] DecAxis = ax1.coords['dec'] RAAxis.set_axislabel('RA') DecAxis.set_axislabel('Dec') ax1.coords.grid(color='black', alpha=0.5, linestyle='solid') else: plt.xlabel("RA (arb. units)") plt.ylabel("Dec (arb. units)") if labels is not None: xls = x yls = y for label, xl, yl in zip(labels, xls, yls): plt.annotate(label, xy=(xl, yl), xytext=(-2, 2), textcoords='offset points', ha='right', va='bottom') plt.savefig(outDir + 'flux_ratio_sky.{}'.format(format), format=format)
import matplotlib.pyplot as plt import matplotlib.cm as cm import pyregion from astropy.io import fits # read in the image xray_name = "pspc_skyview.fits" f_xray = fits.open(xray_name) try: from astropy.wcs import WCS from wcsaxes import WCSAxes wcs = WCS(f_xray[0].header) fig = plt.figure() ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs) fig.add_axes(ax) except ImportError: ax = plt.subplot(111) ax.imshow(f_xray[0].data, cmap=cm.gray, vmin=0., vmax=0.00038, origin="lower") reg_name = "test.reg" r = pyregion.open(reg_name).as_imagecoord(f_xray[0].header) patch_list, text_list = r.get_mpl_patches_texts() for p in patch_list: ax.add_patch(p) for t in text_list: ax.add_artist(t)
def __init__(self, dendrogram, hub, alignment='horizontal', cmap=plt.cm.gray, clip_velocity=None, aspect=2.5, linewidths=0.9, figsize=None): if dendrogram.data.ndim != 3: raise ValueError( "Only 3-dimensional arrays are supported") if not hasattr(hub, 'select_subtree'): raise NotImplementedError("astrodendro does not have scatter_picker enabled") self.hub = hub self.datacube = dendrogram.data self.dendrogram = dendrogram self.selected_contours = {} # selection_id -> (contour, contour) tuple if alignment == 'horizontal': figsize = figsize or (10, 4.4) ax_lb_limits = [0.1, 0.05, 0.8, 0.4] ax_lv_limits = [0.1, 0.5, 0.8, 0.5] elif alignment == 'vertical': figsize = figsize or (8, 6) ax_lb_limits = [0.1, 0.1, 0.375, 0.8] ax_lv_limits = [0.55, 0.1, 0.375, 0.8] elif alignment == 'pp' or alignment == 'lb': figsize = figsize or (10, 4) ax_lb_limits = [0.1, 0.1, 0.8, 0.8] ax_lv_limits = [0,0,0.01,0.01] elif alignment == 'pv' or alignment == 'lv': figsize = figsize or (10, 4) ax_lb_limits = [0.5, 0.5, 0.01, 0.01] ax_lv_limits = [0.1, 0.1, 0.8, 0.8] else: raise ValueError("`alignment` must be 'horizontal' or 'vertical'") self.fig = plt.figure(figsize=figsize) self.cmap = cmap if self.dendrogram.wcs is not None: ax_lb = WCSAxes(self.fig, ax_lb_limits, wcs=self.dendrogram.wcs, slices=('x', 'y', 0)) self.ax_lb = self.fig.add_axes(ax_lb) ax_lv = WCSAxes(self.fig, ax_lv_limits, wcs=self.dendrogram.wcs, slices=('x', 0, 'y')) self.ax_lv = self.fig.add_axes(ax_lv) else: self.ax_lb = self.fig.add_axes(ax_lb_limits) self.ax_lv = self.fig.add_axes(ax_lv_limits) array_lb = np.nansum(self.datacube, axis=0) array_lb[(array_lb < 0) | np.isinf(array_lb) | np.isnan(array_lb)] = 0 self.array_lb = array_lb array_lv = np.nansum(self.datacube, axis=1) array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0 self.array_lv = array_lv if clip_velocity is None: if np.shape(array_lv)[0]*2.5 > np.shape(array_lb)[0]: self.clip_velocity = True else: self.clip_velocity = False else: self.clip_velocity = clip_velocity self.aspect = aspect self.linewidths = linewidths self._draw_plot() self.hub.add_callback(self.update_selection) self.fig.canvas.mpl_connect('button_press_event', self.select_from_map) # If things are already selected in the hub, go select them! for selection_id in self.hub.selections: self.update_selection(selection_id)
def plot_state(directions_list, trim_names=True): """ Plots the facets of a run """ global midRA, midDec, fig, at, selected_direction selected_direction = None # Set up coordinate system and figure points, midRA, midDec = factor.directions.getxy(directions_list) fig = plt.figure(1, figsize=(10, 9)) if hasWCSaxes: wcs = factor.directions.makeWCS(midRA, midDec) ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs) fig.add_axes(ax) else: ax = plt.gca() field_x = min(points[0]) field_y = max(points[1]) adjust_xy = True while adjust_xy: adjust_xy = False for xy in points: dist = np.sqrt((xy[0] - field_x)**2 + (xy[1] - field_y)**2) if dist < 10.0: field_x -= 1 field_y += 1 adjust_xy = True break field_ra, field_dec = factor.directions.xy2radec([field_x], [field_y], refRA=midRA, refDec=midDec) field = Direction('field', field_ra[0], field_dec[0], factor_working_dir=directions_list[0].working_dir) directions_list.append(field) ax.set_title('Overview of FACTOR run in\n{}'.format( directions_list[0].working_dir)) # Plot facets markers = [] for direction in directions_list: if direction.name != 'field': vertices = read_vertices(direction.vertices_file) RAverts = vertices[0] Decverts = vertices[1] xverts, yverts = factor.directions.radec2xy(RAverts, Decverts, refRA=midRA, refDec=midDec) xyverts = [np.array([xp, yp]) for xp, yp in zip(xverts, yverts)] mpl_poly = Polygon(np.array(xyverts), edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) else: xverts = [field_x] yverts = [field_y] mpl_poly = Circle((field_x, field_y), radius=5.0, edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) mpl_poly.facet_name = direction.name mpl_poly.completed_ops = get_completed_ops(direction) mpl_poly.started_ops = get_started_ops(direction) mpl_poly.current_op = get_current_op(direction) set_patch_color(mpl_poly, direction) ax.add_patch(mpl_poly) # Add facet names if direction.name != 'field': poly_tuple = tuple([(xp, yp) for xp, yp in zip(xverts, yverts)]) xmid = SPolygon(poly_tuple).centroid.x ymid = SPolygon(poly_tuple).centroid.y else: xmid = field_x ymid = field_y if trim_names: name = direction.name.split('_')[-1] else: name = direction.name marker = ax.text(xmid, ymid, name, color='k', clip_on=True, clip_box=ax.bbox, ha='center', va='bottom') marker.set_zorder(1001) markers.append(marker) # Add info box at = AnchoredText("Selected direction: None", prop=dict(size=12), frameon=True, loc=3) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") at.set_zorder(1002) ax.add_artist(at) ax.relim() ax.autoscale() ax.set_aspect('equal') if hasWCSaxes: RAAxis = ax.coords['ra'] RAAxis.set_axislabel('RA', minpad=0.75) RAAxis.set_major_formatter('hh:mm:ss') DecAxis = ax.coords['dec'] DecAxis.set_axislabel('Dec', minpad=0.75) DecAxis.set_major_formatter('dd:mm:ss') ax.coords.grid(color='black', alpha=0.5, linestyle='solid') else: plt.xlabel("RA (arb. units)") plt.ylabel("Dec (arb. units)") # Define coodinate formater to show RA and Dec under mouse pointer ax.format_coord = formatCoord # Show legend not_processed_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F2F2', linewidth=2) processing_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F5A9', linewidth=2) selfcal_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#A9F5A9', linewidth=2) selfcal_not_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F5A9A9', linewidth=2) l = ax.legend([ not_processed_patch, processing_patch, selfcal_ok_patch, selfcal_not_ok_patch ], ['Unprocessed', 'Processing', 'Completed', 'Failed']) l.set_zorder(1002) # Add check for mouse clicks and key presses fig.canvas.mpl_connect('pick_event', on_pick) fig.canvas.mpl_connect('key_press_event', on_press) # Add timer to update the plot every 60 seconds timer = fig.canvas.new_timer(interval=60000) timer.add_callback(update_plot) timer.start() # Show plot plt.show() plt.close(fig) # Clean up any temp pyrap images if os.path.exists('/tmp/tempimage'): shutil.rmtree('/tmp/tempimage')
from __future__ import division import os.path import matplotlib.pyplot as plt from astropy import wcs from astropy.io.fits import getdata from wcsaxes import WCSAxes from demo import downsample_and_transpose_data_and_header data_path = os.path.expanduser("~/Dropbox/College/Astro99/DATA/") data_file = 'COGAL_local_mom.fits' datacube, datacube_header = getdata(data_path+data_file, memmap=True, header=True) datacube_dt, datacube_dt_header = \ downsample_and_transpose_data_and_header(datacube, datacube_header, 1, (2,0,1), resample=False, recenter=True) datacube_dt_wcs = wcs.wcs.WCS(datacube_dt_header) datacube_dt_wcs.wcs.bounds_check(pix2world=False, world2pix=False) fig = plt.figure(figsize=(13,3.5)) ax_image_limits = [0.1, 0.1, 0.8, 0.8] ax_image = fig.add_axes(WCSAxes(fig, ax_image_limits, wcs=datacube_dt_wcs, slices=('x','y', 0))) image = ax_image.imshow(datacube_dt[50, :,:], origin='lower', interpolation='nearest', cmap=plt.cm.gray) fig.show()
def __init__(self, dendrogram, hub, alignment='latitude', cmap=plt.cm.gray, clip_velocity=None): if dendrogram.data.ndim != 3: raise ValueError("Only 3-dimensional arrays are supported") if not hasattr(hub, 'select_subtree'): raise NotImplementedError( "astrodendro does not have scatter_picker enabled") self.hub = hub self.datacube = dendrogram.data self.dendrogram = dendrogram self.wcs = dendrogram.wcs self.plotter = DendrogramPlotter(dendrogram) self.plotter.sort(reverse=True) # Get the lines as individual elements, and the mapping from line to structure self.lines = self.plotter.get_lines(edgecolor='k') self.selected_lines = {} self.selected_contours = {} # selection_id -> (contour, contour) tuple if alignment == 'latitude': figsize = (15, 9) ax_integrated_limits = [0.025, 0.05, 0.6, 0.5] ax_cartoon_limits = [0.025, 0.55, 0.6, 0.5] slices = ('x', 'y', 0) self.sum_axis = 0 self.overlay_cartoon = overlay_lb_cartoon self.aspect = 1 elif alignment == 'velocity': figsize = (15, 9) ax_integrated_limits = [0.025, 0.05, 0.6, 0.5] ax_cartoon_limits = [0.025, 0.55, 0.6, 0.5] slices = ('x', 0, 'y') self.sum_axis = 1 self.overlay_cartoon = overlay_lv_cartoon self.aspect = 2.5 # elif alignment == 'pp' or alignment == 'lb': # figsize = (10, 4) # ax_integrated_limits = [0.1, 0.1, 0.8, 0.8] # ax_cartoon_limits = [0,0,0.01,0.01] else: raise ValueError("`alignment` must be 'latitude' or 'velocity'") self.alignment = alignment self.fig = plt.figure(figsize=figsize) self.cmap = cmap if self.dendrogram.wcs is not None: ax_integrated = WCSAxes(self.fig, ax_integrated_limits, wcs=self.dendrogram.wcs, slices=slices) self.ax_integrated = self.fig.add_axes(ax_integrated) ax_cartoon = WCSAxes(self.fig, ax_cartoon_limits, wcs=self.dendrogram.wcs, slices=slices, sharex=ax_integrated, sharey=ax_integrated) self.ax_cartoon = self.fig.add_axes(ax_cartoon) else: self.ax_integrated = self.fig.add_axes(ax_integrated_limits) self.ax_cartoon = self.fig.add_axes(ax_cartoon_limits, sharex=ax_integrated, sharey=ax_integrated) array_summed = np.nansum(self.datacube, axis=self.sum_axis) array_summed[(array_summed < 0) | np.isinf(array_summed) | np.isnan(array_summed)] = 0 self.array_summed = array_summed # all stolen from astrodendro.viewer self.ax_dendrogram = self.fig.add_axes([0.65, 0.1, 0.35, 0.6]) self.ax_dendrogram.add_collection(self.lines) self.selected_label = {} # map selection IDs -> text objects self.selected_label[1] = self.fig.text(0.75, 0.9, "No structure selected", fontsize=18, color=self.hub.colors[1]) self.selected_label[2] = self.fig.text(0.75, 0.85, "No structure selected", fontsize=18, color=self.hub.colors[2]) self.selected_label[3] = self.fig.text(0.75, 0.8, "No structure selected", fontsize=18, color=self.hub.colors[3]) x = [p.vertices[:, 0] for p in self.lines.get_paths()] y = [p.vertices[:, 1] for p in self.lines.get_paths()] xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) self.lines.set_picker(2.) self.lines.set_zorder(0) dx = xmax - xmin self.ax_dendrogram.set_xlim(xmin - dx * 0.1, xmax + dx * 0.1) self.ax_dendrogram.set_ylim(ymin * 0.5, ymax * 2.0) self.ax_dendrogram.set_yscale('log') self.fig.canvas.mpl_connect('pick_event', self.line_picker) # array_lv = np.nansum(self.datacube, axis=1) # array_lv[(array_lv < 0) | np.isinf(array_lv) | np.isnan(array_lv)] = 0 # self.array_lv = array_lv # if clip_velocity is None: # if np.shape(array_lv)[0]*2.5 > np.shape(array_lb)[0]: # self.clip_velocity = True # else: # self.clip_velocity = False # else: # self.clip_velocity = clip_velocity self._draw_plot() self.hub.add_callback(self.update_selection) self.hub.add_callback(self._update_lines) self.fig.canvas.mpl_connect('button_press_event', self.select_from_map) # If things are already selected in the hub, go select them! for selection_id in self.hub.selections: self.update_selection(selection_id)
def __init__(self, dendrogram): if dendrogram.data.ndim not in [2, 3]: raise ValueError( "Only 2- and 3-dimensional arrays are supported at this time") self.hub = SelectionHub() self._connect_to_hub() self.array = dendrogram.data self.dendrogram = dendrogram self.plotter = DendrogramPlotter(dendrogram) self.plotter.sort(reverse=True) # Get the lines as individual elements, and the mapping from line to structure self.lines = self.plotter.get_lines(edgecolor='k') # Define the currently selected subtree self.selected_lines = {} self.selected_contour = {} # The keys in these dictionaries are event button IDs. # Initiate plot import matplotlib.pyplot as plt self.fig = plt.figure(figsize=(14, 8)) ax_image_limits = [0.1, 0.1, 0.4, 0.7] try: from wcsaxes import WCSAxes __wcaxes_imported = True except ImportError: __wcaxes_imported = False if self.dendrogram.wcs is not None: warnings.warn( "`WCSAxes` package required for wcs coordinate display.") if self.dendrogram.wcs is not None and __wcaxes_imported: if self.array.ndim == 2: slices = ('x', 'y') else: slices = ('x', 'y', 1) ax_image = WCSAxes(self.fig, ax_image_limits, wcs=self.dendrogram.wcs, slices=slices) self.ax_image = self.fig.add_axes(ax_image) else: self.ax_image = self.fig.add_axes(ax_image_limits) from matplotlib.widgets import Slider self._clim = (np.min(self.array[~np.isnan(self.array) & ~np.isinf(self.array)]), np.max(self.array[~np.isnan(self.array) & ~np.isinf(self.array)])) if self.array.ndim == 2: self.slice = None self.image = self.ax_image.imshow(self.array, origin='lower', interpolation='nearest', vmin=self._clim[0], vmax=self._clim[1], cmap=plt.cm.gray) self.slice_slider = None else: if self.array.shape[0] > 1: self.slice = int(round(self.array.shape[0] / 2.)) self.slice_slider_ax = self.fig.add_axes( [0.1, 0.95, 0.4, 0.03]) self.slice_slider_ax.set_xticklabels("") self.slice_slider_ax.set_yticklabels("") self.slice_slider = Slider(self.slice_slider_ax, "3-d slice", 0, self.array.shape[0], valinit=self.slice, valfmt="%i") self.slice_slider.on_changed(self.update_slice) self.slice_slider.drawon = False else: self.slice = 0 self.slice_slider = None self.image = self.ax_image.imshow(self.array[self.slice, :, :], origin='lower', interpolation='nearest', vmin=self._clim[0], vmax=self._clim[1], cmap=plt.cm.gray) self.vmin_slider_ax = self.fig.add_axes([0.1, 0.90, 0.4, 0.03]) self.vmin_slider_ax.set_xticklabels("") self.vmin_slider_ax.set_yticklabels("") self.vmin_slider = Slider(self.vmin_slider_ax, "vmin", self._clim[0], self._clim[1], valinit=self._clim[0]) self.vmin_slider.on_changed(self.update_vmin) self.vmin_slider.drawon = False self.vmax_slider_ax = self.fig.add_axes([0.1, 0.85, 0.4, 0.03]) self.vmax_slider_ax.set_xticklabels("") self.vmax_slider_ax.set_yticklabels("") self.vmax_slider = Slider(self.vmax_slider_ax, "vmax", self._clim[0], self._clim[1], valinit=self._clim[1]) self.vmax_slider.on_changed(self.update_vmax) self.vmax_slider.drawon = False self.ax_dendrogram = self.fig.add_axes([0.6, 0.3, 0.35, 0.4]) self.ax_dendrogram.add_collection(self.lines) self.selected_label = {} # map selection IDs -> text objects self.selected_label[1] = self.fig.text(0.6, 0.85, "No structure selected", fontsize=18, color=self.hub.colors[1]) self.selected_label[2] = self.fig.text(0.6, 0.8, "No structure selected", fontsize=18, color=self.hub.colors[2]) self.selected_label[3] = self.fig.text(0.6, 0.75, "No structure selected", fontsize=18, color=self.hub.colors[3]) x = [p.vertices[:, 0] for p in self.lines.get_paths()] y = [p.vertices[:, 1] for p in self.lines.get_paths()] xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) self.lines.set_picker(2.) self.lines.set_zorder(0) dx = xmax - xmin self.ax_dendrogram.set_xlim(xmin - dx * 0.1, xmax + dx * 0.1) self.ax_dendrogram.set_ylim(ymin * 0.5, ymax * 2.0) self.ax_dendrogram.set_yscale('log') self.fig.canvas.mpl_connect('pick_event', self.line_picker) self.fig.canvas.mpl_connect('button_press_event', self.select_from_map)