Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - 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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...