Search code examples
pythonmatplotlibpolar-coordinates

Polar plot of a function with negative radii using matplotlib


The following python code should plot r(theta) = theta on the range [-pi/2, pi/2].

import matplotlib.pyplot as plt
import numpy

theta = numpy.linspace(-numpy.pi / 2, numpy.pi / 2, 64 + 1)
r = theta

plt.polar(theta, r)
plt.savefig('polar.png')

This produces the plot:

polar plot

However, I would expect it to produce:

expected polar plot

The negative values of r(theta) seem to be clipped. How do I make it so that matplotlib plots the negative values of r(theta)?


Solution

  • The first plot seems correct. It just doesn't show the negative values. This can be overcome by explicitely setting the limits of the r axes.

    import matplotlib.pyplot as plt
    import numpy
    
    theta = numpy.linspace(-numpy.pi / 2, numpy.pi / 2, 64 + 1)
    r = theta
    
    plt.polar(theta, r)
    plt.ylim(theta.min(),theta.max())
    plt.yticks([-1, 0,1])
    plt.show()
    

    enter image description here

    This behaviour is based on the assumption that any quantity should be plottable on a polar graph, which might be beneficial for technical questions on relative quantities. E.g. one might ask about the deviation of a quantity in a periodic system from its mean value. In this case the convention used by matplotlib is ideally suited.

    From a more mathematical (theoretical) perspective one might argue that negative radii are a point reflection on the origin. In order to replicate this behaviour, one needs to rotate the points of negative r values by π. The expected graph from the question can thus be reproduced by the following code

    import matplotlib.pyplot as plt
    import numpy as np
    
    theta = np.linspace(-np.pi / 2, np.pi / 2, 64 + 1)
    r = theta
    
    plt.polar(theta+(r<0)*np.pi, np.abs(r))
    
    plt.show()
    

    enter image description here