使用matplotlib具有负半径的函数的极坐标图
以下 Python 代码应在 [-pi/2, pi/2] 范围内绘制 r(theta) = theta.
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')
这产生了情节:
但是,我希望它产生:
r(theta)的负值似乎被裁剪.如何使 matplotlib 绘制 r(theta) 的负值?
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)?
第一个图似乎正确.它只是不显示负值.这可以通过明确设置 r 轴的限制来克服.
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()
此行为是基于这样的假设,即任何数量都应可绘制在极坐标图上,这可能对有关相对数量的技术问题有所帮助.例如.人们可能会问周期系统中的一个量与其平均值的偏差.在这种情况下,matplotlib 使用的约定非常适合.
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.
从更数学(理论)的角度来看,人们可能会认为负半径是原点上的点反射.为了复制此行为,需要将 r
负值的点旋转π.因此可以通过以下代码重现问题中的预期图
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()