Latex, PgfPlots - Curves and polar coordinates

Logo

Introduction

For commodity reasons, curves can be defined using polar coordinates :

$$\begin{align*} & x = \rho \cos \theta \qquad y = \rho \sin \theta \\[10pt] & \rho = 1 + 2 \cos \theta \end{align*}$$

How to display curves defined in polar coordinates using Latex and PgfPlots package ?

Library polar

The PgfPlots package includes the library polar to plot functions \(\rho=f(\theta) \). To import the polar library :

\usepackage{pgfplots}
\usepgfplotslibrary{polar}

Then the function \(f(\theta) \) is defined in a polaraxis environment :

  \begin{polaraxis}[]
    \addplot[domain=0:360,samples=300, color=red] { f(x) }; 
  \end{polaraxis}

By default \(x \) is in degrees.

To plot in polar coordinates the example in the introduction \(\rho = 1 + 2 \cos \theta \) :

\documentclass[tikz]{standalone}
\usepackage{amsmath,amssymb,amsfonts}

\usepackage{pgfplots}
\usepgfplotslibrary{polar}

\pgfplotsset{compat=newest}
\pgfplotsset{every axis/.append style={
                     tick label style={font=\footnotesize},
                 }}

\begin{document}

  \begin{tikzpicture}

  \begin{polaraxis}[]
    \addplot[domain=0:360,samples=300, color=red] {1 + 2*cos(x)}; 
  \end{polaraxis}
  
  \end{tikzpicture}

\end{document}
Polar curves, default plotting

Plotting in radians (multiples of pi)

The default plotting (degrees) may not fit the need.

  • Define the parameter data cs to polarrad in the plot parameters if the domain is in radians, but bear in mind that the \(x\) variable must be then converted in degrees in the function.
  • Set xtick distance, xtick and xticklabels in the polar axis parameters to show explicit multiples of \(\pi\) instead of degree values.
\begin{tikzpicture}

 \begin{polaraxis}[
  xtick distance = deg(pi/4),	
  xtick = {0,0,deg((pi)/4),deg((pi)/2),deg((3*pi)/4),deg(pi),deg((3*pi)/2),
  xticklabels={,0,$\frac{\pi}{4}$,$\frac{\pi}{2}$,$\frac{3\pi}{4}$,$\pi$,$\frac{3\pi}2$}
 ]
    
  \addplot[domain=0:2*pi,samples=100,color=red,data cs=polarrad] { 1 + 2*cos(deg(x)) }; 

 \end{polaraxis}
  
\end{tikzpicture}
Polar curves, plotting in radians

Plotting curves in polar coordinates on a cartesian grid

To display a curve defined by a polar equation in a cartesian grid, that is usually the case, instead of using the polar library, set data cs to polar in the plot parameters and give the coordinates (\(\theta\),\(f(\theta)\)):

\begin{tikzpicture}

  \begin{axis}[
		xtick distance=1, ytick distance=1,		
		xmin=-4, xmax=4,		
		ymin=-3, ymax=3, 		
		axis lines = center]

    \addplot[domain=0:360,samples=300,color=red,data cs=polar] (x,{1 + 2*cos(x)}); 

  \end{axis}

\end{tikzpicture}

PgfPlots automatically transform the polar coordinates to the output coordinate system.

Polar curves, cartesian grid