Module wcsgrat

A graticule is a system of crossing lines on a map representing positions of which one coordinate is constant. For a spatial map it consists of parallels of latitude and meridians of longitude as defined by a given projection.

This module is used to set up such graticules and labels for the selected world coordinate system. It plots the results with plotting library Matplotlib.

Besides spatial axes, it supports also spectral axes and a mix of both (e.g. position-velocity diagrams). It deals with data dimensions > 2 by allowing arbitrary selections of two axes. The transformations between pixel coordinates and world coordinates are based on module wcs which is a Python binding for Mark R. Calabretta’s library WCSLIB. >From WCSLIB we use only the core transformation routines. Header parsing is done with module wcs.

Axes types that are not recognized by this software is treated as being linear. The axes types correspond with keywords CTYPEn in a FITS file. The information from a FITS file is retrieved by module PyFITS

See also

Tutorial material with code examples:

  • Tutorial maputils module which contains many examples with source code, see Tutorial maputils module.
  • Figure gallery ‘all sky plots’ with many examples of Graticule constructors, see All Sky plots.

Module level data

left, bottom, right, top
The variables left, bottom, right and top are equivalent to the strings “left”, “bottom”, “right” and “top” and are used as identifiers for plot axes.
native, notnative, bothticks, noticks

The variables native, notnative, bothticks, noticks correspond to the numbers 0, 1, 2 and 3 and represent modes to make ticks along an axis visible or invisible. Ticks along an axis can represent both world coordinate types (e.g. when a map is rotated). Sometimes one wants to allow this and sometimes not.

Tick mode Description
native Show only ticks that are native to the coordinate axis. Do not allow ticks that correspond to the axis for which a constant value applies. So, for example, in a RA-DEC map which is rotated 45 degrees we want only Right Ascensions along the x-axis.
notnative Plot the ticks that are not native to the coordinate axis. So, for example, in a RA-DEC map which is rotated 45 degrees we want only Declinations along the x-axis.
bothticks Allow both type of ticks along a plot axis
noticks Do not allow any tick to be plotted.

Functions

kapteyn.wcsgrat.gethmsdms(a, prec, axtype, skysys, eqlon=None)[source]

Given a number in degrees and an axis type in axtype equal to ‘longitude’ or ‘latitude’, calculate and return the parts of its sexagesimal representation, i.e. hours or degrees, minutes and seconds. Also return the fractional seconds and the sign if the input was a value at negative latitude. The value for skysys sets the formatting to hours/minutes/seconds if it represents an equatorial system.

Parameters:
  • a (Floating point) – The longitude or latitude in degrees.
  • prec (Integer) – The number of decimals in the seconds
  • axtype (String) – One of ‘longitude’ or ‘latitude’
  • skysys (Integer) – The sky system
Returns:

tuple: (Ihours, Ideg, Imin, Isec, Fsec, sign) which represent Integer values for the hours, degrees, minutes and seconds. Fsec is the fractional part of the seconds. Element sign is -1 for negative latitudes and +1 for positive latitudes.

kapteyn.wcsgrat.makelabel(hmsdms, Hlab, Dlab, Mlab, Slab, prec, fmt, tex)[source]

From the output of function gethmsdms and some Booleans, this function creates a label in plain text or in TeX. The Booleans set a flag whether a field (hours, degrees, minutes or seconds) should be printed or not. The fmt parameter is used if it does not contain the percentage character (%) but instead contains characters from the set HDMS. A capital overules the corresponding Boolean value, so if fmt=’HMS’, the values for Hlab, Mlab and Slab are all set to True.

Parameters:
  • hmsdms (Tuple with integer and floating point numbers) – The output of function gethmsdms()
  • Hlab – If False, there is no need to print the hours
  • Dlab – If False, there is no need to print the degrees
  • Mlab – If False, there is no need to print the minutes
  • Slab – If False, there is no need to print the seconds
  • fmt (String) – String containing a combination of the characters [‘H’, ‘D’, ‘M’, ‘S’, ‘.’, ‘h’, ‘d’, ‘m’, ‘s’] A capital sets the corresponding input Boolean (Hlab, Dlab, etc.) to True. A dot starts to set the precision. The number of characters after the dot set the precision itself. A character that is not a capital sets the corresponding input Boolean (Hlab, Dlab, etc.) to False. This is a bit dangerous because with this option one can suppress fields to be printed that contain a value unequal to zero. It is applied if you want to suppress e.g. seconds if all the seconds in your label are 0.0. The suppression of printing minutes is overruled if hours (or degrees) and seconds are required. Otherwise we could end up with non standard labels (e.g. 2h30s).
  • tex (Boolean) – If True, then format the labels in LaTeX.
Returns:

lab, a label in either hms or dms in plain text or in LaTeX format.

Examples:
>>> # Set the format in Hours, minutes and seconds with a precision
>>> # of three. The suppression of minutes will not work here:
>>> grat.setp_tick(wcsaxis=0, fmt="HmS.SSS")
>>> # The same effect is obtained with:
>>> grat.setp_tick(wcsaxis=0, fmt="HmS.###")
>>> # Let the system determine whether seconds are printed
>>> # but make sure that degrees and minutes are included:
>>> grat.setp_tick(wcsaxis=1, fmt="DM")
>>> # If we know that all minutes and seconds in our labels are 0.0
>>> # and we want only the hours to be printed, then use:
>>> grat.setp_tick(wcsaxis=0, fmt="Hms")
>>> grat.setp_tick(wcsaxis=0, fmt="Dms")
>>> # Plot labels in Degrees even if the axis is an equatorial longitude.

Class Graticule

class kapteyn.wcsgrat.Graticule(header=None, graticuledata=None, axnum=None, wcstypes=None, pxlim=None, pylim=None, mixpix=None, spectrans=None, skyout=None, alter='', wxlim=None, wylim=None, boxsamples=5000, startx=None, starty=None, deltax=None, deltay=None, skipx=False, skipy=False, gridsamples=1000, labelsintex=True, offsetx=None, offsety=None, unitsx=None, unitsy=None)[source]

Creates an object that defines a graticule A (spatial) graticule consists of parallels and meridians. We extend this to a general grid so we can cover every type of map (e.g. position velocity maps).

Parameters:
  • header (Python dictionary or FITS header object (pyfits.NP_pyfits.HDUList)) – Is a Python dictionary or dictionary-like object containing FITS-style keys and values, e.g. a header object from PyFITS. Python dictionaries are used for debugging, or plotting experiments or when you need to define a projection system from scratch.
  • graticuledata (Object with some required attributes) –

    This is a helper object. It can be any object as long it has attributes:

    • header
    • axnum
    • pxlim
    • pylim
    • mixpix
    • spectrans

    Software that interfaces with a user to get data and relevant properties could/should produce objects which have at least values for the attributes listed above. Then these objects could be used as a shortcut parameter.

  • axnum (None, Integer or sequence of Integers) – This parameter sets which FITS axis corresponds to the x-axis of your graticule plot rectangle and which one corresponds to the y-axis (see also description at pxlim and pylim). The first axis in a FITS file is axis 1. If axnum set to None then the default FITS axes will be 1 and 2. With a sequence you can set different FITS axes like axnum=(1,3) Then the input is a tuple or a list.
  • wcstypes (List of strings) – List with the type of the used axes. These types are derived from the projection object axis types (attribute wcstype) but are translated into a string: The strings are ‘lo’ for a longitude axis, ‘la’ for a latitude axis, ‘sp; for a spectral axis and ‘li_xxx’ for a linear axis where ‘xxx’ is the ctype for that axis.
  • pxlim (None or exactly 2 Integers) – The values of this parameter together with the values in pylim define a rectangular frame. The intersections of graticule lines with this frame are the positions where want to plot a tick mark and write a label that gives the position as a formatted string. Further, the limits in pixels are used to set the step size when a graticule line is sampled. This step size then is used to distinguish a valid step from a jump (e.g. from 180-delta degrees to 180+delta degrees which can jump from one side in the plot to the other side). To prevent a jump in a plot, the graticule line is splitted into line pieces without jumps. The default of pxlim is copied from the header value. FITS data starts to address the pixels with 1 and the last pixel is given by FITS keyword NAXISn. Note that internally the enclosing rectangle in pixels is enlarged with 0.5 pixel in all directions. This enables a correct overlay on an image where the pixels have a size.
  • pylim (None or exactly 2 Integers) – See description at pxlim. The range is along the y-axis.
  • mixpix (None or 1 Integer) – For maps with only 1 spatial coordinate we need to define the pixel that sets the spatial value on the matching spatial axis. If its value is None then the value of CRPIXn of the matching axis from the header is taken as default.
  • spectrans (String) – The spectral translation. For spectral axes it is usually possible to convert to another representation. For instance one can ‘translate’ a frequency into a velocity which is one of the types: VOPT-F2W, VRAD, VELO-F2V (for optical, radio and radial velocities). See also the article Representations of spectral coordinates in FITS by Greisen, Calabretta, Valdes & Allen. Module maputils from the Kapteyn Package provides a method that creates a list with possible spectral translations given an arbitrary header. The spectral translation should be followed by a code (e.g. as in ‘VOPT-F2W’) which sets the conversion algorithm. If you don’t know this beforehand, you can either append the string ‘-???’ or try your translation without this coding. Then this module tries to find the appropriate code itself.
  • skyout (None, one Integer or a tuple with a sky definition) –

    A single number or a tuple which specifies the celestial system. The tuple is laid out as follows: (sky system, equinox, reference system, epoch of observation). Predefined are the systems:

    • wcs.equatorial
    • wcs.ecliptic,
    • wcs.galactic
    • wcs.supergalactic

    or the minimal matched string versions of these values.

    Predefined reference systems are:

    • wcs.fk4,
    • wcs.fk4_no_e,
    • wcs.fk5,
    • wcs.icrs,
    • wcs.j2000

    or the minimal matched string versions of these values.

    Prefixes for epoch data are:

    Prefix Description Example
    B Besselian epoch ’B 1950’, ‘b1950’, ‘B1983.5’, ‘-B1100
    J Julian epoch ’j2000.7’, ‘J 2000’, ‘-j100.0’
    JD Julian Date ’JD2450123.7’
    MJD Modified Julian Day ’mJD 24034’, ‘MJD50123.2’
    RJD Reduced Julian Day ’rJD50123.2’, ‘Rjd 23433’
    F DD/MM/YY (old FITS) ’F29/11/57’
    F YYYY-MM-DD ’F2000-01-01’
    F YYYY-MM-DDTHH:MM:SS ’F2002-04-04T09:42:42.1’

    See the documentation of module celestial for more details. Example of a sky definition:

    skyout = (wcs.equatorial, wcs.fk4_no_e, 'B1950')
    
  • alter (Character) – A character from ‘A’ through ‘Z’, indicating an alternative WCS axis description from a FITS header.
  • wxlim (None or exactly two floating point numbers) – Two numbers in units of the x-axis. For spatial axes this is usually in degrees. The numbers are the limits of an interval for which graticules will be calculated. If these values are omitted, defaults will be calculated. Then random positions in pixels are converted to world coordinates and the greatest gap in these coordinates is calculated. The end- and start point of the gap are the start- and end point of the range(s) in world coordinates. It is not enough to transform only the limits in pixels because a maximum or minimum in world coordinates could be located on arbitrary pixel positions depending on the projection.
  • wylim (None or exactly two floating point numbers) – See wxlim, but now applied for the y-axis
  • boxsamples (Integer) – Number of random pixel positions within a box with limits pxlim and pylim for which world coordinates are calculated to get an estimate of the range in world coordinates (see description at wxlim). The default is listed in the argument list of this method. If speed is essential one can try smaller numbers than the default.
  • startx (None or 1 floating point number or a sequence of floating point numbers or a string.) –

    If one value is given then this is the first graticule line that has a constant x world coordinate equal to startx. The other values will be calculated, either with distance deltax between them or with a default distance calculated by this method. If None is set, then a suitable value will be calculated. The input can also be a string which is parsed by the positions module. This enables the use of units etc. Examples (see also module positions:

    • For a frequency axis: startx=”linspace(1.4240,1.4250,4) Ghz”
    • For a frequency axis: startx=”arange(1.4240,1.4250,0.0005) Ghz”
    • For a spectral translation to WAVE: startx=“‘0.2105, 0.2104’ m”
    • Two labels on a longitude axis: startx=”3h00m20s 3h00m30s”
  • starty (None or 1 floating point number or a sequence of floating point numbers or a string.) – [None, one value, sequence] Same for the graticule line with constant y world coordinate equal to starty.
  • deltax (None or a floating point number or a string) –

    Step in world coordinates along the x-axis between two subsequent graticule lines. It can also be a string with an expression and optionally a unit. Note that the expression cannot contain any spaces. Example:

    • deltax = 5*6/6 dmsmin
  • deltay (None or a floating point number or a string.) – Same as deltax but now as step in y direction. It can also be a string with an expression and optionally a unit.
  • skipx (Boolean) – Do not calculate the graticule lines with the constant world coordinate that is associated with the x-axis.
  • skipy (Boolean) – The same as skipx but now associated with the y-axis.
  • gridsamples (Integer) – Number of positions on a graticule line for which a pixel position is calculated and stored as part of the graticule line. If None is set then the default is used (see the argument list of this method).
  • labelsintex (Boolean) –

    The default is that all tick labels are formatted for LaTeX. These are not the axes labels. If you want to format these in LaTeX then you need to set them explicitly as in:

    >>> grat.setp_axislabel("bottom",
        label=r"$\mathrm{Right\ Ascension\ (2000)}$",
        fontsize=14)``
    

    Printing your axis labels in LaTeX limits the number of Matplotlib properties that one can set.

  • offsetx (None or Boolean) – Change the default mode which sets either plotting the labels for the given -or calculated world coordinates or plotting labels which represent constant offsets with respect to a given starting point. The offset mode is default for plots with mixed axes, i.e. with only one spatial axis. In spatial maps this offset mode is not very useful to plot the graticule lines because these lines are plotted at a constant world coordinate and do not know about offsets. The offset axes correspond to the pixel positions of start- and endpoint of the left and bottom axes and the default start point of the offsets (value 0) is at the centre of the axis. One can change this start point with startx, starty.
  • offsety (None or Boolean) – Same as offsetx but now for the left plot axis.
  • unitsx (String) – Units for first axis. Applies both to regular and offset axes. If this parameter sets a unit other than the default, then a conversion function will be used to display the labels in the new units. The unit in the default axis label will be replaced by the new units.
  • unitsy (String) – Units for second axis.
Raises:
ValueError Could not find enough (>1) valid world coordinates in this map!

User wanted to let the constructor estimate what the ranges in world coordinates are for this header, but only zero or one coordinate could be found.

ValueError Need data with at least two axes

The header describes zero or one axes. For a graticule plot we need at least two axes.

ValueError Need two axis numbers to create a graticule

The axnum parameter needs exactly two values.

ValueError Need two different axis numbers

A user/programmer entered two identical axis numbers. Graticules need two different axes.

ValueError pxlim needs to be of type tuple or list

Check type.

ValueError pxlim must have two elements

Number must be exactly 2.

ValueError pylim needs to be of type tuple or list

Check type.

ValueError pylim must have two elements

Number must be exactly 2.

ValueError Could not find a grid for the missing spatial axis

The specification in axnum corresponds to a map with only one spatial axis. If parameter mixpix is omitted then the constructor tries to find a suitable value from the (FITS) header. It reads CRPIXn where n is the appropriate axis number. If nothing could be found in the header then this exception will be raised.

ValueError Could not find a matching spatial axis pair

The specification in axnum corresponds to a map with only one spatial axis. A We need the missing spatial axis to find a matching world coordinate, but a matching axis could not be found in the header.

ValueError wxlim needs to be of type tuple or list

Check type.

ValueError wxlim must have two elements

Number must be exactly 2.

ValueError wylim needs to be of type tuple or list

Check type.

ValueError wylim must have two elements

Number must be exactly 2.

ValueError boxsamples < 2: Need at least two samples to find limits

There is a minimum number of random positions we have to calculate to get an impression of the axis limits in world coordinates.

ValueError Number of samples along graticule line must be >= 2 to avoid a step size of zero

The value of parameter gridsamples is too low. Low values give distorted graticule lines. Higher values (like the default) give smooth results.

Returns:

A graticule object. This object contains the line pieces needed to draw the graticule and the ticks (positions, text and axis number). The basis method to reveal this data (necessary if you want to make a plot yourself) is described in the following example:

graticule = wcsgrat.Graticule(header)
for gridline in graticule:
print("\nThis gridline belongs to axis", gridline.wcsaxis)
print("Axis type: %s.  Sky system %s:" % (gridline.axtype, gridline.skysys))
for t in gridline.ticks:
   print("tick x,y:", t.x, t.y)
   print("tick label:", t.labval)
   print("tick on axis:", t.axisnr)
for line in gridline.linepieces:
   print("line piece has %d elements" % len(line[0]))

Note

A Graticule object has a string representation and can therefore be easily inspected with Python’s print statement.

Attributes:

axes

Read the PLOTaxis class documentation. Four PLOTaxis instances, one for each axis of the rectangular frame in pixels set by xplim and pylim If your graticule object is called grat then the four axes are accessed with:

  • grat.axes[wcsgrat.left]
  • grat.axes[wcsgrat.bottom]
  • grat.axes[wcsgrat.right]
  • grat.axes[wcsgrat.top]

Usually these attributes are set with method setp_plotaxis().

Examples:

grat.axes[wcsgrat.left].mode = 1
grat.axes[wcsgrat.bottom].label = 'Longitude / Latitude'
grat.axes[wcsgrat.bottom].mode = 2
grat.axes[wcsgrat.right].mode = 0
PLOTaxis modes are:

0: ticks native to axis type only
1: Only the tick that is not native to axis type
2: both types of ticks (map could be rotated)
3: no ticks

The default values depend on how many ticks, native to the plot axis, are found. If this is < 2 then we allow both native and not native ticks along all plot axes.

pxlim

The limits of the map in pixels along the x-axis. This value is either set in the constructor or calculated. The default is [1,NAXISn]. The attribute is meant as a read-only attribute.

pylim:

Same for the y-axis.

wxlim

The limits of the map in world coordinates for the x-axis either set in the constructor or calculated (i.e. estimated) by this method. The attribute is meant as a read-only attribute.

wylim

Same for the y-axis

xaxnum

The (FITS) axis number associated with the x-axis Note that axis numbers in FITS start with 1. If these numbers are not given as argument for the constructor then xaxnum=1 is assumed. The attribute is meant as a read-only attribute.

yaxnum

Same for the y-axis. Default: yaxnum=2

wcstypes

List with strings that represent the wcs axis type of the axes.

gmap

The wcs projection object for this graticule. See the wcs module document for more information.

mixpix

The pixel on the matching spatial axis for maps with only one spatial axis. This attribute is meant as a read-only attribute.

xstarts

World coordinates associated with the x-axis which set the constant value of a graticule line as calculated when the object is initialized. This attribute is meant as a read-only attribute.

ystarts

Same for the y-axis

skyout

Unformatted copy of input parameter skyout

spectrans

Unformatted copy of input parameter spectrans

Examples:

Example to show how to use a custom made header to create a graticule object. Usually one uses this option to create all sky plots. It is also a useful tool for experiments.:

#1. A minimal header for an all sky plot
header = {'NAXIS' : 2, 'NAXIS1': 100, 'NAXIS2': 80,
          'CTYPE1' : 'RA---AZP', 'CRVAL1' :0, 
          'CRPIX1' : 50, 'CUNIT1' : 'deg', 'CDELT1' : -5.0,
          'CTYPE2' : 'DEC--AZP',
          'CRVAL2' : dec0, 'CRPIX2' : 40, 'CUNIT2' : 'deg',
          'CDELT2' : 5.0,
          'PV2_1'  : mu, 'PV2_2'  : gamma,
         }
grat = wcsgrat.Graticule(header)

Use module PyFITS to read a header from a FITS file:

#2. A header from a FITS file 'test.fits'
import pyfits
hdulist = pyfits.open('test.fits')
header = hdulist[0].header
grat = wcsgrat.Graticule(header)

Select the axes for the graticules. Note that the order of the axes should be the same as the order of axes in the image where you want to plot the graticule. If necessary one can swap the graticule plot axes with input parameter axnum:

#3. Swap x and y- axis in a FITS file
grat = wcsgrat.Graticule(header, axnum= (2,1))

For data with more than two axes, one can select the axes with input parameter axnum:

#4. For a FITS file with axes (RA,DEC,FREQ) 
#  create a graticule for the FREQ,RA axes:
grat = wcsgrat.Graticule(header, axnum=(3,1))

Use sexagesimal numbers for startx/starty:

#5. Sexagesimal input
grat = wcsgrat.Graticule(...., startx="7h59m30s", starty="-10d0m30s')

Methods which set (plot) attributes:

setp_tick(wcsaxis=None, plotaxis=None, position=None, tol=1e-12, fmt=None, fun=None, tex=None, texsexa=None, markerdict={}, **kwargs)[source]

Set (plot) attributes for a wcs tick label. A tick is identified by the type of grid line it belongs to, and/or the plot axis for which it defines an intersection and/or a position which corresponds to the constant value of the graticule line. All these parameters are valid with none, one or a sequence of values.

Warning

If no value for wcsaxis, plotaxis or position is entered then this method applies the parameter setting on all the wcs axes.

Parameters:
  • wcsaxis (None, 0, 1 or tuple with both) – Values are 0 or 1, corresponding to the first and second world coordinate types. Note that wcsaxis=0 corresponds to the first element in the axis permutation array given in parameter axnum.
  • plotaxis (One or more integers between 0 and 3.) – Accepted values are ‘None’, 0, 1, 2, 3 or a sequence of these numbers, to represent the left, bottom, right and top axis of the enclosing rectangle that represents the limits in pixel coordinates.
  • position (None or one or a sequence of floating point numbers) – Accepted are None, or one or more values representing the constant value of the graticule line in world coordinates. These positions are used to identify individual graticule lines so that each line can have its own properties. The input can also be a string that represents a sexagesimal number.
  • tol (Floating point number) – If a value > 0 is given, the gridline with the constant value closest to a given position within distance ‘tol’ gets updated attributes.
  • fmt (String) – A string that formats the tick value e.g. fmt="%10.5f" in the Python way, or a string that contains no percentage character (%) but a format to set the output of sexagesimal numbers e.g. fmt=’HMs’. The characters in the format either force (uppercase) a field to be printed, or it suppresses (lowercase) a field to be printed. See also the examples at makelabel(). To create labels with an exponential, use a second format in the same format string. The syntax is %nne where nn is an integer. This integer, which can be negative, sets the number in the exponential. The number before the exponential is formatted in the usual way e.g. fmt=’%.3f%-3e’.
  • fun (Python function or Lambda expression) – An external function which will be used to convert the tick value e.g. to convert velocities from m/s to km/s. See also example 2 below.
  • tex (Boolean) – Interpret the format in fmt as a TeX label. The default is set to None to indicate it has not been set (to True or False) so that it is possible to distinguish between global and local settings of this property.
  • texsexa – If False and parameter tex is True, then format the tick label without superscripts for sexagesimal labels. This option can be used if superscripts result in ‘jumpy’ labels. The reason is that in Matplotlib the TeX labels at the bottom of a plot are aligned at a baseline at the top of the characters.
  • markerdict (Python dictionary) –

    Properties for the tick marker. Amongst others:

    • markersize: Size of tick line.
    • direction: Use keyword argument ‘direction=’ get tick lines that point outside the plot instead of the default which is inside.
    • Set the tick label pad in points. Use a negative number to shift a label inwards.
    • markeredgewidth: The width of the marker
    • color: Color of the marker (not the label)
  • **kwargs (Matplotlib keyword arguments) – Keyword arguments for plot properties like color, visible, rotation etc. The plot attributes are standard Matplotlib attributes which can be found in the Matplotlib documentation.
Note:

Some projections generate labels that are very close to each other. If you want to skip labels then you can use keyword/value visible=False. There is not a documented keyword visible in this method because visible is a valid keyword argument in Matplotlib. To set the direction of the tickmarks, use keyword argument direction= with one of the options ‘in’ (default), ‘out’ or ‘inout’. In the set with example code, one can find examples with this keyword.

Examples:

1. Set tick properties with setp_tick(). The last line makes the label at a declination of -10 degrees (we assume a spatial map) invisible:

grat.setp_tick(wcsaxis=0, color='g')
grat.setp_tick(wcsaxis=1, color='m')
grat.setp_tick(wcsaxis=1, plotaxis=wcsgrat.bottom,
   color='c', rotation=-30, ha='left')
grat.setp_tick(plotaxis=wcsgrat.right, backgroundcolor='yellow')
grat.setp_tick(plotaxis=wcsgrat.left, position=-10, visible=False)

2. Example of an external function to change the values of the tick labels for the horizontal axis only:

def fx(x):
   return x/1000.0

setp_tick(wcsaxis=0, fun=fx)

Or use the lambda operator as in: fun=lambda x: x/1000

3. Using the utility routines setp_ticklabel() and setp_tickmark():

graticule4.setp_tickmark(plotaxis="bottom", markersize=8, color='m',
                         markeredgewidth=3, direction='out')
graticule4.setp_ticklabel(plotaxis="bottom", rotation=20, color='y',
                          ha='right', va='top') 
setp_plotaxis(plotaxis, mode=None, label=None, xpos=None, ypos=None, **kwargs)[source]

Set (plot) attributes for titles along a plot axis and set the ticks mode. The ticks mode sets the relation between the ticks and the plot axis. For example a rotated map will show a rotated graticule, so ticks for both axes can appear along a plot axis. With parameter mode one can influence this behaviour.

Note

This method addresses the four axes of a plot separately. Therefore its functionality cannot be incorporated in setp_tick()

Parameters:
  • plotaxis (Integer or String) –

    The axis number of one of the axes of the plot rectangle:

    • wcsgrat.left
    • wcsgrat.bottom
    • wcsgrat.right
    • wcsgrat.top

    or (part of) a string which can be (case insensitive) matched by one from ‘left’, ‘bottom’, ‘right’, ‘top’.

  • mode (Integer or String) –

    What should this axis do with the tick marks and labels?

    • 0 = ticks native to axis type only
    • 1 = only the tick that is not native to axis type
    • 2 = both types of ticks (map could be rotated)
    • 3 = no ticks

    Or use a text that can (case insensitive) match one of:

    • ”NATIVE_TICKS”
    • ”SWITCHED_TICKS”
    • ”ALL_TICKS”
    • ”NO_TICKS”
  • label (String) – An annotation of the current axis
  • **kwargs (Matplotlib keyword argument(s)) – Keywords for (plot) attributes
Examples:

Change the font size of the tick labels along the bottom axis in 11:

grat = Graticule(...)
grat.setp_plotaxis(wcsgrat.bottom, fontsize=11)
setp_lineswcs0(position=None, tol=1e-12, **kwargs)[source]

Helper method for setp_gratline(). It pre-selects the grid line that corresponds to the first world coordinate.

Parameters:

See description at setp_gratline()

Examples:

Make lines of constant latitude magenta and lines of constant longitude green. The line that corresponds to a latitude of 30 degrees and the line that corresponds to a longitude of 0 degrees are plotted in red with a line width of 2:

grat.setp_lineswcs1(color='m')
grat.setp_lineswcs0(color='g')
grat.setp_lineswcs1(30, color='r', lw=2)
grat.setp_lineswcs0(0, color='r', lw=2)
setp_lineswcs1(position=None, tol=1e-12, **kwargs)[source]

Equivalent to method setp_gratline(). It pre-selects the grid line that corresponds to the second world coordinate.

Parameters:See description at setp_gratline()
Examples:See example at setp_lineswcs0().
setp_gratline(wcsaxis=None, position=None, tol=1e-12, **kwargs)[source]

Set (plot) attributes for one or more graticule lines. These graticule lines are identified by the wcs axis number (wcsaxis=0 or wcsaxis=1) and by their constant world coordinate in position.

Parameters:
  • wcsaxis (None , integer or tuple with integers from set 0, 1.) – If omitted, then for both types of graticule lines the attributes are set. If one value is given then only for that axis the attributes will be set.
  • position (None, one or a sequence of floating point numbers) – None, one value or a sequence of values representing the constant value of a graticule line in world coordinates. For the graticule line(s) that match a position in this sequence, the attributes are updated.
  • tol (Floating point number) – If a value > 0 is given, the graticule line with the constant value closest to a given position within distance tol gets updated attributes.
  • **kwargs (Matplotlib keyword argument(s)) – Keyword arguments for plot properties like color, rotation or visible, linestyle etc.
Returns:

Notes:

For each value in position find the index of the graticule line that belongs to wcsaxis so that the distance between that value and the constant value of the graticule line is the smallest of all the graticule lines. If position=None then apply change of properties to ALL graticule lines. The (plot) properties are stored in **kwargs Note that graticule lines are initialized with default properties. These kwargs only update the existing kwargs i.e. appending new keywords and update existing keywords.

setp_axislabel(plotaxis=None, label=None, xpos=None, ypos=None, **kwargs)[source]

Utility method that calls method setp_plotaxis() but the parameters are restricted to the axis labels. These labels belong to one of the 4 plot axes. See the documentation at setp_plotaxis for the input of the plotaxis parameter. The kwargs are Matplotlib attributes.

Possible useful Matplotlib attributes:

  • backgroundcolor
  • color
  • rotation
  • style or fontstyle [ ‘normal’ | ‘italic’ | ‘oblique’]
  • weight or fontweight
Parameters:
  • plotaxis (Integer or String) –

    The axis number of one of the axes of the plot rectangle:

    • wcsgrat.left
    • wcsgrat.bottom
    • wcsgrat.right
    • wcsgrat.top

    or (part of) a string which can be (case insensitive) matched by one from ‘left’, ‘bottom’, ‘right’, ‘top’.

  • label (String) – The label text.
  • xpos (Floating point number) – The x position of the label in normalized device coordinates
  • **kwargs (Matplotlib keyword argument(s)) – Keywords for (plot) attributes
setp_tickmark(wcsaxis=None, plotaxis=None, position=None, tol=1e-12, **mkwargs)[source]

Utility method for setp_tick(). It handles the properties of the tick marks, which are Line2D objects in Matplotlib. The most useful properties are color, markeredgewidth and markersize. Keyword direction= sets a tick direction to inwards or outwards, or both (‘in’, ‘out’, ‘inout’).

See also documentation for :func`wcsgrat.setp_ticklabel`.

setp_ticklabel(wcsaxis=None, plotaxis=None, position=None, tol=1e-12, fmt=None, fun=None, tex=None, texsexa=None, **kwargs)[source]

Utility method for setp_tick(). It handles the properties of the tick labels, which are Text objects in Matplotlib. The most useful properties are color, fontsize and fontstyle.

Parameters:
  • wcsaxis (None, 0, 1 or tuple with both) – Values are 0 or 1, corresponding to the first and second world coordinate types. Note that wcsaxis=0 corresponds to the first element in the axis permutation array given in parameter axnum.
  • plotaxis (One or more integers between 0 and 3.) – Accepted values are ‘None’, 0, 1, 2, 3 or a combination, to represent the left, bottom, right and top axis of the enclosing rectangle that represents the limits in pixel coordinates.
  • position (None or one or a sequence of floating point numbers) – Accepted are None, or one or more values representing the constant value of the graticule line in world coordinates. These positions are used to identify individual graticule lines so that each line can have its own properties. The input can also be a string that represents a sexagesimal number.
  • tol (Floating point number) – If a value > 0 is given, the gridline with the constant value closest to a given position within distance ‘tol’ gets updated attributes.
  • fmt (String) – A string that formats the tick value e.g. fmt="%10.5f" in the Python way, or a string that contains no percentage character (%) but a format to set the output of sexagesimal numbers e.g. fmt=’HMs’. The characters in the format either force (uppercase) a field to be printed, or it suppresses (lowercase) a field to be printed. See also the examples at makelabel().
  • fun (Python function or Lambda expression) – An external function which will be used to convert the tick value e.g. to convert velocities from m/s to km/s. See also example 2 below.
  • tex (Boolean) – If True then format the tick label in LaTeX. This is the default. If False then standard text will applies. Some text properties cannot be changed if LaTeX is in use.
  • texsexa – If False and parameter tex is True, then format the tick label without superscripts for sexagesimal labels. This option can be used if superscripts result in ‘jumpy’ labels. The reason is that in Matplotlib the TeX labels at the bottom of a plot are aligned at a baseline at the top of the characters.
  • **kwargs (Matplotlib keyword arguments) – Keyword arguments for plot properties like color, visible, rotation etc. The plot attributes are standard Matplotlib attributes which can be found in the Matplotlib documentation.
Note:

Some projections generate labels that are very close to each other. If you want to skip labels then you can use keyword/value visible=False. There is not a documented keyword visible in this method because visible is a valid keyword argument in Matplotlib.

set_tickmode(plotaxis=None, mode=None)[source]

Utility method that calls method setp_plotaxis() but the parameters are restricted to the tick mode.

Each plot axis has a tick mode.

Parameters:
  • plotaxis (Integer or String) –

    The axis number of one of the axes of the plot rectangle:

    • wcsgrat.left
    • wcsgrat.bottom
    • wcsgrat.right
    • wcsgrat.top

    or (part of) a string which can be (minimal & case insensitive) matched by one from ‘left’, ‘bottom’, ‘right’, ‘top’.

  • mode (Integer or String) –

    What should this axis do with the tick marks and labels?

    • 0 = ticks native to axis type only
    • 1 = only the tick that is not native to axis type
    • 2 = both types of ticks (map could be rotated)
    • 3 = no ticks

    Or use a text that can (minimal) match one of:

    • ”NATIVE_TICKS”
    • ”SWITCHED_TICKS”
    • ”ALL_TICKS”
    • ”NO_TICKS”

Methods that deal with special curves like borders:

scanborder(xstart, ystart, deltax=None, deltay=None, nxy=1000, tol=None)[source]

For the slanted azimuthal projections, it is not trivial to draw a border because these borders are not graticule lines with a constant longitude or constant latitude. Nor it is easy or even possible to find mathematical expressions for this type of projection. Also, the mathematical expressions return world coordinates which can suffer from loss of precision. This method tracks the border from a starting point by scanning in x- and y direction and tries to find the position of a limb with a standard bisection technique. This method has been applied to a number of all-sky plots with slanted projections.

Parameters:
  • xstart (Floating point) – X-coordinate in pixels of position where to start the scan to find a border. The parameter has no default.
  • ystart (Floating point) – Y-coordinate in pixels of position where to start the scan to find border. The parameter has no default.
  • deltax (Floating point) – Set range in pixels to look for a border in scan direction. The default value is 10 percent of the total pixel range in x- or y-direction.
  • deltay (Floating point) – See deltayx.
  • nxy (Integer) – Number of scan lines in x and y direction. Default is 1000.
  • tol (Floating point) – See note below.
Returns:

Identifier to set attributes of this graticule line with method setp_linespecial().

Note:

This method uses an algorithm to find positions along the border of a projection. It scans along both x- and y-axis for a NaN (Not a Number number) transition as a result of an invalid coordinate transformation, and repeats this for a number of scan lines along the x-axis and y-axis.

A position on a border off an all-sky plot is the position at
which a transition occurs from a valid coordinate to a NaN.

Its accuracy depends on the the tolerance given in argument tol. The start coordinates to find the next border position on the next scan line is the position of the previous border point. If you have missing line pieces, then add more borders by calling this method with different starting points.

addgratline(x, y, pixels=False)[source]

For any path given by a set of world coordinates of which none is a constant value (e.g. borders in slanted projections where the positions are calculated by an external routine), one can create a line that is processed as a graticule line, i.e. intersections and jumps are addressed. Instead of world coordinates, this method can also process pixel positions. The type of input is set by the pixels parameter.

Parameters:
  • x (Floating point numbers) – A sequence of world coordinates or pixels that correspond to the horizontal axis in a graticule plot..
  • y – The same for the second axis
  • pixels (Boolean) – False or True If False the coordinates in x and y are world- coordinates. Else they are pixel coordinates.
Returns:

A Identification number id which can be used to set properties for this special path with method setp_linespecial(). Return None if no line piece could be found inside the pixel limits of the graticule.

Note:

This method can be used to plot a border around an all-sky plot e.g. for slanted projections. See code at scanborder().

setp_linespecial(id, **kwargs)[source]

Set (plot) attributes for a special type of graticule line made with method addgratline() or method scanborder(). This graticule line has no constant x- or y- value. It is identified by an id returned by method addgratline().

Parameters:
  • id (Integer) – id from addgratline()
  • **kwargs (Matplotlib keyword argument(s)) – keywords for (plot) attributes
Examples:

Create a special graticule line which follows the positions in two given sequences x and y. and set the line width for this line to 2:

id = grat.addgratline(x, y)
grat.setp_linespecial(id, lw=2)

Methods related to plotting derived elements:

Insidelabels(wcsaxis=0, world=None, constval=None, deltapx=0.0, deltapy=0.0, angle=None, addangle=0.0, fun=None, fmt=None, tex=True, aspect=1.0, **kwargs)[source]

Annotate positions in world coordinates within the boundaries of the plot. This method can be used to plot positions on all-sky maps where there are usually no intersections with the enclosing axes rectangle.

Parameters:
  • wcsaxis (Integer) – Values are 0 or 1, corresponding to the first and second world coordinate types. The accepted values are 0 and 1. The default is 0.
  • world (One or a sequence of floating point number(s) or None) – One or a sequence of world coordinates on the axis given by wcsaxis. The positions are completed with one value for constval. If world=None (the default) then the world coordinates are copied from graticule world coordinates.
  • constval (Floating point number or String) – A constant world coordinate to complete the positions at which a label is plotted. The value can also be a string representing a sexagesimal number.
  • deltapx (Floating point number.) – Small shift in pixels in x-direction of text. This enables us to improve the layout of the plot by preventing that labels are intersected by lines.
  • deltapy (Floating point number.) – See description at deltapx.
  • angle (Floating point number) – Use this angle (in degrees) instead of calculated defaults. It is the angle at which then all position labels are plotted.
  • addangle (Floating point number) – Add this angle (in degrees) to the calculated default angles.
  • fun – Function or lambda expression to convert the label value.
  • fmt (String) – String to format the numbers. If omitted the format ‘%g’ is used.
  • tex – Format these ‘inside’ labels in LaTeX if this parameter is set to True (which is the default).
  • aspect (Floating point number) – The aspect ratio of the frame. This number is needed to plot labels at the right angle. It cannot be derived from the aspect ratio of the frame, because at the moment of creation, the frame is not known (only after a call to the plot() method, a frame is known). If the aspect ratio is known in the calling environment, we should use it there to get the angles right.
  • **kwargs (Matplotlib keyword argument(s)) – Keywords for (plot) attributes.
Returns:

An Insidelabel object with a series of derived label objects. These label objects have a number of attributes, see Insidelabels

Notes:

For a map with only one spatial axis, the value of ‘mixpix’ is used as pixel value for the matching spatial axis. The mixed() method from module wcs is used to calculate the right positions.

Examples:

Annotate a plot with labels at positions from a list with longitudes at given fixed latitude:

grat = Graticule(...)
lon_world = [0,30,60,90,120,150,180]
lat_constval = 30
inlabs = grat.Insidelabels(wcsaxis=0,
                           world=lon_world,
                           constval=lat_constval,
                           color='r')
Insidelabels.setp_label(position=None, tol=1e-12, fmt=None, fun=None, tex=None, texsexa=None, **kwargs)

This method handles the properties of the ‘inside’ labels, which are Text objects in Matplotlib. The most useful properties are color, fontsize and fontstyle. One can change the label values using an external function and/or change the format of the label.

Parameters:
  • position (None or one or a sequence of floating point numbers) – Accepted are None, or one or more values representing the constant value of the graticule line in world coordinates. These positions are used to identify individual graticule lines so that each line can have its own properties. If no position is entered, then the changes are applied to all the labels in the current object. The input can also be a string that represents a sexagesimal number.
  • tol (Floating point number) – If a value > 0 is given, the gridline with the constant value closest to a given position within distance ‘tol’ gets updated attributes.
  • fmt (String) – A string that formats the tick value e.g. fmt="%10.5f" in the Python way, or a string that contains no percentage character (%) but a format to set the output of sexagesimal numbers e.g. fmt=’HMs’. The characters in the format either force (uppercase) a field to be printed, or it suppresses (lowercase) a field to be printed. See also the examples at makelabel().
  • fun (Python function or Lambda expression) – An external function which will be used to convert the tick value e.g. to convert velocities from m/s to km/s. See also example 2 below.
  • tex (Boolean) – If True then format the tick label in LaTeX. This is the default. If False then standard text will be applied. Some text properties cannot be changed if LaTeX is in use.
  • texsexa – If False and parameter tex is True, then format the tick label without superscripts for sexagesimal labels. This option can be used if superscripts result in ‘jumpy’ labels. The reason is that in Matplotlib the TeX labels at the bottom of a plot are aligned at a baseline at the top of the characters and not at the bottom, while the height between LaTeX boxes may vary.
  • **kwargs (Matplotlib keyword arguments) – Keyword arguments for plot properties like color, visible, rotation etc. The plot attributes are standard Matplotlib attributes which can be found in the Matplotlib documentation.
Note:

Some projections generate labels that are very close to each other. If you want to skip labels then you can use keyword/value visible=False. Note that visible is a parameter of Matplotlib’s plot functions.

Utility methods:

get_aspectratio(xcm=None, ycm=None)[source]

Calculate and set, the aspect ratio for the current pixels. Also set default values for figure size and axes lengths (i.e. size of canvas depends on the size of plot window with this aspect ratio).

Parameters:
  • xcm (Floating point number) – Given a value for xcm or ycm (or omit both), suggest a suitable figure size in and a viewport in normalized device coordinates of a plot which has an axes rectangle that corrects the figure for an aspect ratio (i.e. CDELTy/CDELTx) unequal to 1 while the length of the x-axis is xcm OR the length of the y-axis is ycm. See note for non-spatial maps.
  • ycm (Floating point number) – See description at xcm.
Returns:

The aspect ratio defined as: AR = CDELTy/CDELTx.

Note:

(i.e. AR > 10 or AR < 0.1), an aspect ratio of 1 is returned. This method sets the attributes: ‘axesrect’, ‘figsize’, ‘aspectratio’. The attribute ‘figsize’ is in inches which is compatible to the methods of Matplotlib.

class kapteyn.wcsgrat.WCStick(x, y, axisnr, labval, wcsaxis, offset, fun=None, fmt=None)[source]

A WCStick object is an intersection of a parallel or meridian (or equivalent lines with one constant world coordinate) with one of the axes of a rectangle in pixels. The position of that intersection is stored in pixel coordinates and can be used to plot a (formatted) label showing the position of the constant world coordinate of the graticule line. This class is only used in the context of the Graticule class.

Class Insidelabels

class kapteyn.wcsgrat.Insidelabels(wcsaxis)[source]

A small utility class for wcs labels inside a plot with a graticule. Useful for all sky plots.

setp_label(position=None, tol=1e-12, fmt=None, fun=None, tex=None, texsexa=None, **kwargs)[source]

This method handles the properties of the ‘inside’ labels, which are Text objects in Matplotlib. The most useful properties are color, fontsize and fontstyle. One can change the label values using an external function and/or change the format of the label.

Parameters:
  • position (None or one or a sequence of floating point numbers) – Accepted are None, or one or more values representing the constant value of the graticule line in world coordinates. These positions are used to identify individual graticule lines so that each line can have its own properties. If no position is entered, then the changes are applied to all the labels in the current object. The input can also be a string that represents a sexagesimal number.
  • tol (Floating point number) – If a value > 0 is given, the gridline with the constant value closest to a given position within distance ‘tol’ gets updated attributes.
  • fmt (String) – A string that formats the tick value e.g. fmt="%10.5f" in the Python way, or a string that contains no percentage character (%) but a format to set the output of sexagesimal numbers e.g. fmt=’HMs’. The characters in the format either force (uppercase) a field to be printed, or it suppresses (lowercase) a field to be printed. See also the examples at makelabel().
  • fun (Python function or Lambda expression) – An external function which will be used to convert the tick value e.g. to convert velocities from m/s to km/s. See also example 2 below.
  • tex (Boolean) – If True then format the tick label in LaTeX. This is the default. If False then standard text will be applied. Some text properties cannot be changed if LaTeX is in use.
  • texsexa – If False and parameter tex is True, then format the tick label without superscripts for sexagesimal labels. This option can be used if superscripts result in ‘jumpy’ labels. The reason is that in Matplotlib the TeX labels at the bottom of a plot are aligned at a baseline at the top of the characters and not at the bottom, while the height between LaTeX boxes may vary.
  • **kwargs (Matplotlib keyword arguments) – Keyword arguments for plot properties like color, visible, rotation etc. The plot attributes are standard Matplotlib attributes which can be found in the Matplotlib documentation.
Note:

Some projections generate labels that are very close to each other. If you want to skip labels then you can use keyword/value visible=False. Note that visible is a parameter of Matplotlib’s plot functions.