Creating a Circle in IDL

QUESTION: How can I create a circle in IDL?

ANSWER: Kevin Ivory from the Max Plank Institute offers a very simple algorithm for calculating a circle in IDL:

   FUNCTION CIRCLE, xcenter, ycenter, radius
   points = (2 * !PI / 99.0) * FINDGEN(100)
   x = xcenter + radius * COS(points )
   y = ycenter + radius * SIN(points )
   RETURN, TRANSPOSE([[x],[y]])
   END

The CIRCLE function returns a 2 by 100 array that can be sent to the PLOTS command to draw open circles or to the POLYFILL command to draw closed or filled circles. The circles created with POLYFILL can be filled with different colors.

For example, type these commands:

   TVLCT, [255,0], [255,255], [0,0], 1
   POLYFILL, CIRCLE(65, 65, 20), Color=1, /Device
   PLOTS, CIRCLE(130, 130, 30), /Device
   PLOTS, CIRCLE(195, 195, 20), /Device, Color=2
   PLOTS, CIRCLE(195, 195, 10), /Device, Color=1

You see the result in the picture below.

Circles (2K)

Notice that DEVICE coordinates were used in the code above. The CIRCLE function can also be used with DATA coordinates, but one of the weakness of this simple algorithm is that you are not guaranteed circles when using data coordinates. In fact, if you are not careful about the aspect ratio of your plots, your circles will end up ellipses. Consider these commands:

   WINDOW, XSize=300, YSize=250
   PLOT, FINDGEN(8), /NODATA
   FOR j=1,3 DO POLYFILL, CIRCLE(2*j, 2*j, 1), Color=1

Here is an illustration of what these commands produce.

Circles turn to ellipses (2K)

For this reason, I prefer to use the NASA Goddard Astonomy Library routine TVCIRCLE. With this routine you are guaranteed that you will see a circle on the display whether you specify the circle coordinates in data or device coordinates. You might be interested in the companion routine TVELLIPSE , too.

For example:

   WINDOW, XSize=300, YSize=250
   PLOT, FINDGEN(8), /NODATA
   FOR j=1,3 DO TVCIRCLE, 1, 2*j, 2*j, Color=1, /Data, /Fill

The code above with the call to TVCIRCLE produces this result:

Circles with TVCIRCLE. (2K)

[Return to IDL Programming Tips]