astropy:docs

APLpy documentation

This is the documentation for APLpy. The APLpy homepage is located at http://aplpy.github.com

Using APLpy

Beginner Tutorial

The following tutorial will take you, step by step, through the main features of APLpy. You will need to download the following file.

First, unpack the example files and go to the tutorial directory:

tar -xvzf tutorial.tar.gz
cd tutorial

Now, start up ipython:

   ipython --pylab

and import the ``aplpy`` module as follows::

   import aplpy

To start off, use the FITSfigure class to create a canvas to where your data will be plotted:

gc = aplpy.FITSFigure('fits/2MASS_k.fits')

and display the image using a grayscale stretch:

gc.show_grayscale()

Check out the buttons at the top or bottom of the canvas (depending on the version of matplotlib). You will see seven buttons:

_images/buttons.png

The first five are of interest to us here. The button with the magnifying glass will allow you to select an area on the plot and zoom in. To zoom out you can click on the home button (first one on the left). When you’re zoomed in you can pan around by clicking on the button with the arrows (fourth button from the left).

Use the following command to show a colorscale image instead:

gc.show_colorscale()

The colormap used for the colorscale image can be changed. Try the following:

gc.show_colorscale(cmap='gist_heat')

to show the image showing a ‘heat’ map. You can find more information in the show_grayscale() and show_colorscale() documentation. For example, you can control the minimum and maximum pixel values to show and the stretch function to use.

It is possible to use APLpy to show 3-color images. To do this, you need a FITS file with the image - this is used for the information relating to the coordinates - and a PNG file containing the 3-color image. Both files need to have exactly the same dimensions and the pixels from the PNG file have to match those from the FITS file. An example is provided in the tutorial files. Try the following:

gc.show_rgb('graphics/2MASS_arcsinh_color.png')

It is very easy to modify the font properties of the various labels. For example, in this case, we can change the font size of the tick labels to be smaller than the default:

gc.tick_labels.set_font(size='small')

APLpy can be used to overlay contours onto a grayscale/colorscale/3-color image. Try typing the following command:

gc.show_contour('fits/mips_24micron.fits', colors='white')

There are a number of arguments that can be passed to show_contour() to control the appearance of the contours as well as the number of levels to show. For more information, see the see the show_contour() documentation.

Display a coordinate grid using:

gc.add_grid()

and hide it again using:

gc.remove_grid()

Let’s overplot positions from a source list. Here we will use loadtxt to read in the coordinates from a file, but in general you can pass any pair of lists or numpy arrays that are already defined:

import numpy
data = numpy.loadtxt('data/yso_wcs_only.txt')
ra, dec = data[:, 0], data[:, 1]
gc.show_markers(ra, dec, edgecolor='green', facecolor='none',
                marker='o', s=10, alpha=0.5)

For more information, see the show_markers() documentation.

It’s often the case that you might want to change the look of a contour or markers, but if you run show_contour() or show_markers() a second time, it will overplot rather than replacing. To solve this problem APLpy has ‘layers’ which can be manipulated in a basic way. Type:

gc.list_layers()

which will print out something like this:

There are 2 layers in this figure:

-> contour_set_1
-> marker_set_1

You can use remove_layer(), hide_layer(), and show_layer() to manipulate the layers, and you can also specify the layer=name argument to show_contour() or show_markers(). Using the latter forces APLpy to name the layer you are creating with the name provided, and can also be used to replace an existing layer. For example, let’s change the color of the markers from green to red:

gc.show_markers(ra, dec, layer='marker_set_1', edgecolor='red',
                facecolor='none', marker='o', s=10, alpha=0.5)

Note the presence of the layer='marker_set_1' which means that the current markers plot will be replaced. To view active layers, you can use the list_layers() documentation.

To wrap up this tutorial, we will save the plot to a file. Type the following:

gc.save('myfirstplot.png')

This will produce the following file:

_images/myfirstplot.png

You can of course save it as a PS/EPS, PDF, or SVG file instead. The EPS output is suitable for publication.

To summarize, the above plot was made using the following commands:

import aplpy
import numpy

gc = aplpy.FITSFigure('fits/2MASS_k.fits')
gc.show_rgb('graphics/2MASS_arcsinh_color.png')

gc.tick_labels.set_font(size='small')

gc.show_contour('fits/mips_24micron.fits', colors='white')

data = numpy.loadtxt('data/yso_wcs_only.txt')
ra, dec = data[:, 0], data[:, 1]

gc.show_markers(ra, dec, layer='marker_set_1', edgecolor='red',
                facecolor='none', marker='o', s=10, alpha=0.5)

gc.save('myfirstplot.png')

There are many more methods and options, from setting the tick spacing and format to controlling the label fonts. For more information, see the Quick reference Guide or the Reference/API.

Quick reference Guide

Note

Rather than showing the generic call signature for the methods on this page, these are given in the form of example values. In addition, not all of the optional keywords are mentioned here. For more information on a specific command and all the options available, type help followed by the method name, e.g. help fig.show_grayscale. When multiple optional arguments are given, this does not mean that all of them have to be specified, but just shows all the options available.

Introduction

To import APLpy:

import aplpy

To create a figure of a FITS file:

fig = aplpy.FITSFigure('myimage.fits')

Here and in the remainder of this reference guide, we use the variable name fig for the figure object, but any name can be used.

A grayscale or colorscale representation of the FITS image can be shown and hidden using the following methods:

fig.show_grayscale()
fig.hide_grayscale()
fig.show_colorscale()
fig.hide_colorscale()

To show a three-color image, use the following method, specifying the filename of the color image:

fig.show_rgb('m17.jpeg')

The figure can be interactively explored by zooming and panning. To recenter on a specific region programmatically, use the following method, specifying either a radius:

fig.recenter(33.23, 55.33, radius=0.3)  # degrees

or a separate width and height:

fig.recenter(33.23, 55.33, width=0.3, height=0.2)  # degrees

To overlay contours, use:

fig.show_contour('co_data.fits')

To save the current figure, use:

fig.save('myplot.eps')

Other formats such as PDF, PNG, etc. can be used.

Labels

Labels can be added either in world coordinates:

fig.add_label(34.455, 54.112, 'My favorite star')

or relative to the axes:

fig.add_label(0.1, 0.9, '(a)', relative=True)

Shapes

To overlay different shapes, the following methods are available:

fig.show_markers(x_world, y_world)
fig.show_circles(x_world, y_world, radius)
fig.show_ellipses(x_world, y_world, width, height)
fig.show_rectangles(x_world, y_world, width, height)
fig.show_arrows(x_world, y_world, dx, dy)

where x_world, y_world, radius, width, height, dx, and dy should be 1D arrays specified in degrees.

It is also possible to plot lines and polygons using:

fig.show_lines(line_list)
fig.show_polygons(polygon_list)

For these methods, line_list and polygon_list should be lists of 2xN Numpy arrays describing the coordinates of the vertices in degrees.

DS9 Regions

DS9 region files can be overlaid with:

fig.show_regions('myregions.reg')

Layers

Markers, shapes, regions and text labels are stored in layers. These layers can be listed using:

fig.list_layers()

Layers can be hidden and shown with the following methods:

fig.hide_layer('regions')
fig.show_layer('regions')

Any layer can be retrieved using:

layer = fig.get_layer('circles')

Finally, layers can be removed using:

fig.remove_layer('rectangles')

Coordinates

Two methods are provided to help transform coordinates between world and pixel coordinates. These accept either scalars or arrays in degrees:

x_pix, y_pix = fig.world2pixel(45.3332, 22.1932)
x_world, y_world = fig.pixel2world(np.array([1., 2., 3]), np.array([1., 3., 5.]))

Frame

To set the look of the frame around the figure, use:

fig.frame.set_linewidth(1)  # points
fig.frame.set_color('black')

Colorbar

A grid can be added and removed using the following commands:

fig.add_colorbar()
fig.remove_colorbar()

Once add_colorbar() has been called, the fig.colorbar object is created and the following methods are then available:

  • Show and hide the colorbar:

    fig.colorbar.show()
    fig.colorbar.hide()
    
  • Set where to place the colorbar:

    fig.colorbar.set_location('right')
    

    This can be one of left, right, bottom or top.

  • Set the width of the colorbar:

    fig.colorbar.set_width(0.1)  # arbitrary units, default is 0.2
    
  • Set the amount of padding between the colorbar and the parent axes:

    fig.colorbar.set_pad(0.03)  # arbitrary units, default is 0.05
    
  • Set the font properties of the labels:

    fig.colorbar.set_font(size='medium', weight='medium', \
                          stretch='normal', family='sans-serif', \
                          style='normal', variant='normal')
    
  • Add a colorbar label:

    f.colorbar.set_axis_label_text('Flux (Jy/beam)')
    
  • Set some of the colorbar label properties:

    f.colorbar.set_axis_label_font(size=12, weight='bold')
    
  • Set the padding between the colorbar and the label in points:

    f.colorbar.set_axis_label_pad(10)
    
  • Change the rotation of the colorbar label, in degrees:

    f.colorbar.set_axis_label_rotation(270)
    

Coordinate Grid

A coordinate grid can be added and removed using the following commands:

fig.add_grid()
fig.remove_grid()

Once add_grid() has been called, the fig.grid object is created and the following methods are then available:

  • Show and hide the grid:

    fig.grid.show()
    fig.grid.hide()
    
  • Set the x and y spacing for the grid:

    fig.grid.set_xspacing(0.2)  # degrees
    fig.grid.set_yspacing(0.2)  # degrees
    
  • Set the color of the grid lines:

    fig.grid.set_color('white')
    
  • Set the transparency level of the grid lines:

    fig.grid.set_alpha(0.8)
    
  • Set the line style and width for the grid lines:

    fig.grid.set_linestyle('solid')
    fig.grid.set_linewidth(1)  # points
    

Scalebar

A scalebar can be added and removed using the following commands:

fig.add_scalebar()
fig.remove_scalebar()

Once add_scalebar() has been called, the fig.scalebar object is created and the following methods are then available:

  • Show and hide the scalebar:

    fig.scalebar.show(0.2)  # length in degrees
    fig.scalebar.hide()
    
  • Change the length of the scalebar:

    fig.scalebar.set_length(0.02)  # degrees
    
  • Specify the length of the scalebar in different units:

    from astropy import units as u
    fig.scalebar.set_length(72 * u.arcsecond)
    
  • Change the label of the scalebar:

    fig.scalebar.set_label('5 pc')
    
  • Change the corner that the beam is shown in:

    fig.scalebar.set_corner('top right')
    

    This can be one of top right, top left, bottom right, bottom left, left, right, bottom or top.

  • Set whether or not to show a frame around the beam:

    fig.scalebar.set_frame(False)
    
  • Set the transparency level of the scalebar and label:

    fig.scalebar.set_alpha(0.7)
    
  • Set the color of the scalebar and label:

    fig.scalebar.set_color('white')
    
  • Set the font properties of the label:

    fig.scalebar.set_font(size='medium', weight='medium', \
                          stretch='normal', family='sans-serif', \
                          style='normal', variant='normal')
    
  • Set the line style and width for the scalebar:

    fig.scalebar.set_linestyle('solid')
    fig.scalebar.set_linewidth(3)  # points
    
  • Set multiple properties at once:

    fig.scalebar.set(linestyle='solid', color='red', ...)
    

Beam

A beam can be added and removed using the following commands:

fig.add_beam()
fig.remove_beam()

Once add_beam() has been called, the fig.beam object is created and the following methods are then available:

  • Show and hide the beam:

    fig.beam.show()
    fig.beam.hide()
    
  • Change the major and minor axes, and the position angle:

    fig.beam.set_major(0.03)  # degrees
    fig.beam.set_minor(0.02)  # degrees
    fig.beam.set_angle(45.)  # degrees
    
  • Specify the major and minor axes, and the position angle, in explicit units:

    from astropy import units as u
    fig.beam.set_major(108 * u.arcsecond)
    fig.beam.set_minor(349 * u.microradian)
    fig.beam.set_angle(45 * u.degree)
    
  • Change the corner that the beam is shown in:

    fig.beam.set_corner('top left')
    

    This can be one of top right, top left, bottom right, bottom left, left, right, bottom or top.

  • Set whether or not to show a frame around the beam:

    fig.beam.set_frame(False)
    
  • Set the transparency level of the beam:

    fig.beam.set_alpha(0.5)
    
  • Set the color of the whole beam, or the edge and face color individually:

    fig.beam.set_color('white')
    fig.beam.set_edgecolor('white')
    fig.beam.set_facecolor('green')
    
  • Set the line style and width for the edge of the beam:

    fig.beam.set_linestyle('dashed')
    fig.beam.set_linewidth(2)  # points
    
  • Set the hatch style of the beam:

    fig.beam.set_hatch('/')
    
  • Set multiple properties at once:

    fig.beam.set(facecolor='red', linestyle='dashed', ...)
    

Coordinate types

APLpy supports three types of coordinates: longitudes (in the range 0 to 360 with wrap-around), latitudes (in the range -90 to 90), and scalars (any arbitrary value). APLpy tries to guess the correct type of coordinate for each axis, but it is possible to override this:

fig.set_xaxis_coord_type('scalar')
fig.set_yaxis_coord_type('longitude')

Valid options are longitude, latitude, and scalar.

Axis labels

The methods to control the x- and y- axis labels are the following

  • Show/hide both axis labels:

    fig.axis_labels.show()
    fig.axis_labels.hide()
    
  • Show/hide the x-axis label:

    fig.axis_labels.show_x()
    fig.axis_labels.hide_x()
    
  • Show/hide the y-axis label:

    fig.axis_labels.show_y()
    fig.axis_labels.hide_y()
    
  • Set the text for the x- and y-axis labels:

    fig.axis_labels.set_xtext('Right Ascension (J2000)')
    fig.axis_labels.set_ytext('Declination (J2000)')
    
  • Set the displacement of the x- and y-axis labels from the x- and y-axis respectively:

    fig.axis_labels.set_xpad(...)
    fig.axis_labels.set_ypad(...)
    
  • Set where to place the x-axis label:

    fig.axis_labels.set_xposition('bottom')
    
  • Set where to place the y-axis label:

    fig.axis_labels.set_yposition('right')
    
  • Set the font properties of the labels:

    fig.axis_labels.set_font(size='medium', weight='medium', \
                             stretch='normal', family='sans-serif', \
                             style='normal', variant='normal')
    

Tick labels

The methods to control the numerical labels below each tick are the following

  • Show/hide all tick labels:

    fig.tick_labels.show()
    fig.tick_labels.hide()
    
  • Show/hide the x-axis labels:

    fig.tick_labels.show_x()
    fig.tick_labels.hide_x()
    
  • Show/hide the y-axis labels:

    fig.tick_labels.show_y()
    fig.tick_labels.hide_y()
    
  • Set the format for the x-axis labels (e.g hh:mm, hh:mm:ss.s, etc.):

    fig.tick_labels.set_xformat('hh:mm:ss.ss')
    
  • Set the format for the y-axis labels (e.g dd:mm, dd:mm:ss.s, etc.):

    fig.tick_labels.set_yformat('dd:mm:ss.s')
    
  • Set where to place the x-axis tick labels:

    fig.tick_labels.set_xposition('top')
    
  • Set where to place the y-axis tick labels:

    fig.tick_labels.set_yposition('left')
    
  • Set the style of the labels (‘colons’ or ‘plain’):

    fig.tick_labels.set_style('colons')
    
  • Set the font properties of the labels:

    fig.tick_labels.set_font(size='medium', weight='medium', \
                             stretch='normal', family='sans-serif', \
                             style='normal', variant='normal')
    

Ticks

The methods to control properties relating to the tick marks are the following:

  • Show/hide all ticks:

    fig.ticks.show()
    fig.ticks.hide()
    
  • Show/hide the x-axis ticks:

    fig.ticks.show_x()
    fig.ticks.hide_x()
    
  • Show/hide the y-axis ticks:

    fig.ticks.show_y()
    fig.ticks.hide_y()
    
  • Change the tick spacing for the x- and y-axis:

    fig.ticks.set_xspacing(0.04)  # degrees
    fig.ticks.set_yspacing(0.03)  # degrees
    
  • Change the length of the ticks:

    fig.ticks.set_length(10)  # points
    
  • Change the color of the ticks:

    fig.ticks.set_color('black')
    
  • Set the line width for the ticks:

    fig.ticks.set_linewidth(2)  # points
    
  • Set the number of minor ticks per major tick:

    fig.ticks.set_minor_frequency(5)
    

    Set this to 1 to get rid of minor ticks

Advanced

To control whether to refresh the display after each command, use the following method:

fig.set_auto_refresh(False)

To force a refresh, use:

fig.refresh()

To use the system LaTeX instead of the matplotlib LaTeX, use:

fig.set_system_latex(True)

The color for NaN values can be controlled using the following method:

fig.set_nan_color('black')

Finally, to change the look of the plot using pre-set themes, use:

fig.set_theme('publication')

Arbitrary coordinate systems

Coordinate type

In addition to standard longitude/latitude coordinates, APLpy supports any valid quantities for coordinates (e.g. velocity, frequency, ...) as long as the WCS header information is valid. To differentiate between longitudes, latitudes, and arbitrary scalar values, APLpy keeps track of the axis coordinate ‘type’ for each axis, and will try and guess these based on the header. However, it is possible to explicitly specify the coordinate type with the set_xaxis_coord_type() and set_yaxis_coord_type() methods in the FITSFigure object:

f = FITSFigure('2MASS_k.fits')
f.set_xaxis_coord_type('scalar')
f.set_xaxis_coord_type('latitude')

Valid coordinate types are longitude, latitude, and scalar. Longitudes are forced to be in the 0 to 360 degree range, latitudes are forced to be in the -90 to 90 degree range, and scalars are not constrained.

Label formatting

How label formats are specified depends on the coordinate type. If the coordinate is a longitude or latitude, then the label format is specified using a special syntax which describes whether the label should be decimal or sexagesimal, in hours or degrees, and indicates the number of decimal places. For example:

  • ddd.ddddd means decimal degrees, where the number of decimal places can be varied
  • hh or dd means hours (or degrees)
  • hh:mm or dd:mm means hours and minutes (or degrees and arcminutes)
  • hh:mm:ss or dd:mm:ss means hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
  • hh:mm:ss.ss or dd:mm:ss.ss means hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

If the coordinate type is scalar, then the format should be specified as a valid Python format. For example, %g is the default Python format, %10.3f means decimal notation with three decimal places, etc. For more information, see String Formatting Operations.

In both cases, the default label format can be overridden:

f.tick_labels.set_xformat('dd.ddddd')
f.tick_labels.set_yformat('%11.3f')

Aspect ratio

When plotting images in sky coordinates, APLpy makes pixel square by default, but it is possible to change this, which can be useful for non-sky coordinates. When calling show_grayscale() or show_colorscale(), simply add aspect='auto' which will override the aspect='equal' default.

Slicing multi-dimensional data cubes

How to slice data cubes

APLpy supports extracting a slice from n-dimensional FITS cubes, and re-ordering dimensions. The two key arguments to FITSFigure to control this are dimensions and slices. These arguments can also be passed to show_contour().

The dimensions argument is used to specify which dimensions should be used for the x- and y-axis respectively (zero based). The default values are [0, 1] which means that the x-axis should use the first dimension in the FITS cube, and the y-axis should use the second dimension. For a 2-dimensional FITS file, this means that one can use [1, 0] to flip the axes. For a FITS cube with R.A., Declination, and Velocity, [0, 2] would make a R.A.-Velocity plot.

The slices argument gives the pixels slice to extract from the remaining dimensions, skipping the dimensions used, so slices should be a list with length n-2 where n is the number of dimensions in the FITS file. For example, if one has a FITS file with R.A., Declination, Velocity, and Time (in that order), then:

  • dimensions=[0, 1] means the plot will be an R.A-Declination plot, and slices=[33, 56] means that pixel slices 33 and 56 will be used in Velocity and Time respectively (in this case, dimensions does not need to be specified since it defaults to [0, 1])
  • dimensions=[0, 2] means the plot will be an R.A-Velocity plot, and slices=[22, 56] means that pixel slices 22 and 56 will be used in Declination and Time respectively.
  • dimensions=[3, 2] means the plot will be a Time-Velocity plot, and slices=[10, 22] means that pixel slices 10 and 22 will be used in R.A and Declination respectively.

See Arbitrary coordinate systems for information on formatting the labels when non-longitude/latitude coordinates are used.

Aspect ratio

When plotting images in sky coordinates, APLpy makes pixel square by default, but it is possible to change this. When calling show_grayscale() or show_colorscale(), simply add aspect='auto' which will override the aspect='equal' default. The aspect='auto' is demonstrated below.

Example

The following script demonstrates this functionality in use:

import matplotlib
matplotlib.use('Agg')

import aplpy

f = aplpy.FITSFigure('L1448_13CO.fits.gz', slices=[222],
                     figsize=(5,5))
f.show_colorscale()
f.add_grid()
f.tick_labels.set_font(size='xx-small')
f.axis_labels.set_font(size='x-small')
f.save('slicing_1.png')
_images/slicing_1.png
f = aplpy.FITSFigure('L1448_13CO.fits.gz', slices=[222],
                     dimensions=[1, 0], figsize=(5,5))
f.show_colorscale()
f.add_grid()
f.tick_labels.set_font(size='xx-small')
f.axis_labels.set_font(size='x-small')
f.save('slicing_2.png')
_images/slicing_2.png
f = aplpy.FITSFigure('L1448_13CO.fits.gz', dimensions=[2, 1],
                     slices=[50], figsize=(5,5))
f.show_colorscale(aspect='auto')
f.add_grid()
f.tick_labels.set_font(size='xx-small')
f.axis_labels.set_font(size='x-small')
f.tick_labels.set_xformat('%.1f')
f.save('slicing_3.png')
_images/slicing_3.png

HOWTOs

APLpy in non-interactive mode

While APLpy can be easily used to interactively make plots, it is also possible to make plots without opening up a display. This can be useful to run APLpy remotely, or to write non-interactive scripts to plot one or many FITS files.

Running APLpy in non-interactive mode

To run APLpy in non-interactive mode, you will need to change the ‘backend’ used by matplotlib from an interactive (e.g. WxAgg, TkAgg, MacOS X) to a non-interactive (e.g. Agg, Cairo, PS, PDF) backend. The default backend is typically set in your .matplotlibrc file (or if you do not have such a file, an interactive backend is usually chosen by default). The easiest way to change the backend temporarily is to use the matplotlib.use() function:

import matplotlib
matplotlib.use('Agg')

It is important to change the backend via matplotlib.use before the aplpy module is imported. Once the backend has been changed, any call to FITSFigure() will no longer make a figure window appear. The following script can be used to make a PNG plot:

import matplotlib
matplotlib.use('Agg')

import aplpy

f = aplpy.FITSFigure('mips_24micron.fits')
f.show_grayscale()
f.save('mips_24.png')
Pan/Zoom in non-interactive mode

One of the advantages of using APLpy in interactive mode is the ability to zoom in on a given region of interest. To replicate this functionality in non-interactive mode, the FITSFigure.recenter() method can be used. This method takes a central position, and either a radius (to make a square plot) or a width/height (to make a rectangular plot). This is illustrated in the following example:

import matplotlib
matplotlib.use('Agg')

import aplpy

f = aplpy.FITSFigure('mips_24micron.fits')
f.show_grayscale()
f.recenter(266.2142,-29.1832,width=0.5,height=0.3)
f.save('mips_24_zoomin.png')
Batch scripting

Using APLpy non-interactively can be useful for making plots of many FITS files. Given a directory fits/ containing FITS files, the following code will generate on plot for each .fits file:

import matplotlib
matplotlib.use('Agg')

import aplpy

import glob
import os

for fits_file in glob.glob(os.path.join('fits/','*.fits')):

    f = aplpy.FITSFigure(fits_file)
    f.show_grayscale()
    f.save(fits_file.replace('.fits','.png'))
    f.close()

Installing Montage

Montage is a package developed by IPAC designed to handle the reprojection of FITS files. APLpy relies on Montage for several functions, such as make_rgb_cube() or the north=True argument in FITSFigure. To use these features, Montage needs to be installed.

Obtaining and installing Montage

Montage can be downloaded from http://montage.ipac.caltech.edu/docs/download.html

Installation instructions are provided at http://montage.ipac.caltech.edu/docs/build.html

Once Montage is correctly installed, you are ready to use the Montage-dependent features of APLpy!

Making RGB images

While the APLpy show_rgb() can be used to display an RGB image with the same projection as a given FITS file, it is also possible to use the make_rgb_cube() and make_rgb_image() to generate RGB images from scratch, even for files with initially different projections/resolutions.

Reprojecting three images to the same projection

If you are starting from three images with different projections/resolutions, the first step is to reproject these to a common projection/resolution. The following code shows how this can be done using the make_rgb_cube() function:

aplpy.make_rgb_cube(['2mass_k.fits', '2mass_h.fits',
                     '2mass_j.fits'], '2mass_cube.fits')

This method makes use of Montage to reproject the images to a common projection. For more information on installing Montage, see here. The above example produces a FITS cube named 2mass_cube.fits which contains the three channels in the same projection. This can be used to then produce an RGB image (see next section)

Producing an RGB image from images in a common projection

The make_rgb_image() function can be used to produce an RGB image from either three FITS files in the exact same projection, or a FITS cube containing the three channels (such as that output by make_rgb_cube()). The following example illustrates how to do this:

aplpy.make_rgb_image('2mass_cube.fits','2mass_rgb.png')

In the above example, APLpy will automatically adjust the stretch of the different channels to try and produce a reasonable image, but it is of course possible to specify one or more of the lower/upper limits of the scale to use for each channel. For each lower/upper scale limit, this can be done in two ways. The first is to use the vmin_r/g/b or vmax_r/g/b argument which specifies the pixel value to use for the lower or upper end of the scale respectively. The alternative is to use the pmin_r/g/b or pmax_r/g/b arguments, which specify the percentile value to use instead of an absolute value. The two can of course be mixed, such as in the following example:

aplpy.make_rgb_image('2mass_cube.fits', '2mass_rgb.png',
                      vmin_r=0., pmax_g=90.)
Plotting the resulting RGB image

If PyAVM is installed (which is recommended but not required), then if you produce a JPEG or PNG image, you can plot it directly with:

f = aplpy.FITSFigure('2mass_rgb.png')
f.show_rgb()

For more information, see AVM tagging.

On the other hand, if you are not able to use PyAVM, or need to use a format other than JPEG or PNG, then you need to instantiate the FITSFigure class with a FITS file with exactly the same dimensions and WCS as the RGB image. The make_rgb_cube() function will in fact produce a file with the same name as the main output, but including a _2d suffix, and this can be used to instantiate FITSFigure:

# Reproject the images to a common projection - this will also produce
# ``2mass_cube_2d.fits``
aplpy.make_rgb_cube(['2mass_k.fits', '2mass_h.fits',
                     '2mass_j.fits'], '2mass_cube.fits')

# Make an RGB image
aplpy.make_rgb_image('2mass_cube.fits', '2mass_rgb.png')

# Plot the RGB image using the 2d image to indicate the projection
f = aplpy.FITSFigure('2mass_cube_2d.fits')
f.show_rgb('2mass_rgb.png')

AVM tagging

The latest developer version of APLpy has support for reading/writing AVM tags from/to RGB images (via PyAVM). To make a plot with an AVM-tagged RGB image, say ‘example.jpg’, you can use:

import aplpy
f = aplpy.FITSFigure('example.jpg')
f.show_rgb()

Note that no filename is required for show_rgb() in this case.

If PyAVM is installed, make_rgb_image() can embed AVM meta-data into RGB images it creates, although only JPEG and PNG files support this:

import aplpy
aplpy.make_rgb_image('2mass_cube.fits', '2mass_rgb.jpg')

If PyAVM 0.9.1 or later is installed, the above file 2mass_rgb.jpg will include AVM meta-data and can then be plotted with:

import aplpy
f = aplpy.FITSFigure('2mass_rgb.jpg')
f.show_rgb()

In other words, this means that when creating an RGB image with APLpy, it is no longer necessary to initialize FITSFigure with a FITS file and then use show_rgb() with the RGB image filename - instead, FITSFigure can be directly initialized with the AVM-tagged image.

To disable the embedding of AVM tags, you can use the embed_avm_tags=False option for make_rgb_image().

These features require PyAVM 0.9.1 or later. Please report any issues you encounter here.

Creating subplots

By default, FITSFigure creates a figure with a single subplot that occupies the entire figure. However, APLpy can be used to place a subplot in an existing matplotlib figure instance. To do this, FITSFigure should be called with the figure= argument as follows:

import aplpy
import matplotlib.pyplot as mpl

 fig = mpl.figure()
 f = aplpy.FITSFigure('some_image.fits', figure=fig)

The above will place a subplot inside the fig figure instance. The f object can be used as normal to control the FITS figure inside the subplot. The above however is not very interesting compared to just creating a FITSFigure instance from scratch. What this is useful for is only using sub-regions of the figure to display the FITS data, to leave place for other subplots, whether histograms, scatter, or other matplotlib plots, or another FITS Figure. This can be done using the subplot argument. From the docstring for FITSFigure:

*subplot*: [ list of four floats ]
    If specified, a subplot will be added at this position. The list
    should contain [xmin, ymin, dx, dy] where xmin and ymin are the
    position of the bottom left corner of the subplot, and dx and dy are
    the width and height of the subplot respectively. These should all be
    given in units of the figure width and height. For example, [0.1, 0.1,
    0.8, 0.8] will almost fill the entire figure, leaving a 10 percent
    margin on all sides.

The following code outline illustrates how to create a rectangular figure with two FITS images:

import aplpy
import matplotlib.pyplot as mpl

fig = mpl.figure(figsize=(15, 7))

f1 = aplpy.FITSFigure('image_1.fits', figure=fig, subplot=[0.1,0.1,0.35,0.8])
f1.set_tick_labels_font(size='x-small')
f1.set_axis_labels_font(size='small')
f1.show_grayscale()

f2 = aplpy.FITSFigure('image_2.fits', figure=fig, subplot=[0.5,0.1,0.35,0.8])
f2.set_tick_labels_font(size='x-small')
f2.set_axis_labels_font(size='small')
f2.show_grayscale()

f2.hide_yaxis_label()
f2.hide_ytick_labels()

fig.canvas.draw()

The hide methods shown above are especially useful when working with subplots, as in some cases there is no need to repeat the tick labels. Alternatively figures can be constructed from both APLpy figures and normal matplotlib axes:

import aplpy
import matplotlib.pyplot as mpl

fig = mpl.figure(figsize=(15, 7))

f1 = aplpy.FITSFigure('image_1.fits', figure=fig, subplot=[0.1,0.1,0.35,0.8])
f1.set_tick_labels_font(size='x-small')
f1.set_axis_labels_font(size='small')
f1.show_grayscale()

ax2 = fig.add_axes([0.5,0.1,0.35,0.8])

# some code here with ax2

fig.canvas.draw()

APLpy Normalizations

APLpy uses a different set of normalization techniques than other image display tools. The default options available for the stretch argument are linear, sqrt, power, log, and arcsinh.

In all cases, the transformations below map the values from the image onto a scale from 0 to 1 which then corresponds to the endpoints of the colormap being used.

Log Scale

APLpy defines the log scale with a vmid parameter such that

y = \frac{\log_{10}(x \cdot (m-1) + 1)}{\log_{10}(m)}

where:

m = \frac{v_{\rm max} - v_{\rm mid}}{v_{\rm min}-v_{\rm mid}}

and:

x=\frac{v-v_{\rm min}}{v_{\rm max}-v_{\rm min}}

and v is the image pixel values. Note that v_{\rm mid} should be smaller than v_{\rm min}, which means that m will always be larger than one. By default, v_{\rm mid}=0 and v_{\rm min} is therefore required to be positive (but negative values of v_{\rm min} are allowed if v_{\rm mid} is specified).

For reference, in the FITS display program ds9, the log scale is defined by

y = \frac{\log_{10}(ax+1)}{\log_{10}(a)}

where a defaults to 1000 and recommended values are from 100-10000 (see here).

The two stretches are nearly (but not completely) identical for m
\approx a+1. If you want to convert from the ds9 a parameter to APLpy’s v_{\rm mid}, you can use this formula:

v_{\rm mid} = \frac{m \cdot v_{\rm min}-v_{\rm max}}{m-1} \approx \frac{(a+1) \cdot v_{\rm min} - v_{\rm max}}{a}

Arcsinh Scale

The arcsinh scale is defined by

y = \frac{\textrm{asinh}(x/m)}{\textrm{asinh}(1/m)}

where

m = \frac{v_{\rm mid} - v_{\rm min}}{v_{\rm max}-v_{\rm min}}

By default, v_{\rm mid} is chosen such that 1/m=-30.

For reference, the ds9 definition is simply

y = \frac{\textrm{asinh}(10x)}{3}

Linear Scale

The linear scale is only concerned with the vmin and vmax keywords:

y=\frac{x-v_{\rm min}}{v_{\rm max}-v_{\rm min}}

Square Root Scale

The square root scale is given by

y=\sqrt{\frac{x-v_{\rm min}}{v_{\rm max}-v_{\rm min}}}

Power Scale

The power root scale is

y=\left[\frac{x-v_{\rm min}}{v_{\rm max}-v_{\rm min}}\right]^a

where a is passed in as the exponent keyword.

Reference/API

aplpy Module

APLpy : Astronomical Plotting Library in Python

Functions

make_rgb_cube(files, output[, north, ...]) Make an RGB data cube from a list of three FITS images.
make_rgb_image(data, output[, indices, ...]) Make an RGB image from a FITS RGB cube or from three FITS files.
test([package, test_path, args, plugins, ...]) Run the tests using py.test.

Classes

AxisLabels(parent)
Beam(parent)
Colorbar(parent)
FITSFigure(data[, hdu, figure, subplot, ...]) A class for plotting FITS files.
Frame(parent)
Grid(parent)
Scalebar(parent)
TickLabels(parent)
Ticks(parent)