擅长:python、mysql、java
<p>Matplotlib的<code>contour()</code>函数期望将数据排列为点的二维网格和这些网格点的相应值网格。如果数据自然地排列在网格中,则可以将r、theta转换为x、y,并使用<code>contour(r*np.cos(theta), r*np.sin(theta), values)</code>绘制图。</p>
<p>如果您的数据不是自然网格化的,那么您应该遵循史蒂芬的建议,并使用<code>griddata()</code>将数据插值到网格中。</p>
<p>下面的脚本显示了这两种方法的示例。</p>
<pre><code>import pylab as plt
from matplotlib.mlab import griddata
import numpy as np
# data on a grid
r = np.linspace(0, 1, 100)
t = np.linspace(0, 2*np.pi, 100)
r, t = np.meshgrid(r, t)
z = (t-np.pi)**2 + 10*(r-0.5)**2
plt.subplot(121)
plt.contour(r*np.cos(t), r*np.sin(t), z)
# ungrid data, then re-grid it
r = r.flatten()
t = t.flatten()
x = r*np.cos(t)
y = r*np.sin(t)
z = z.flatten()
xgrid = np.linspace(x.min(), x.max(), 100)
ygrid = np.linspace(y.min(), y.max(), 100)
xgrid, ygrid = np.meshgrid(xgrid, ygrid)
zgrid = griddata(x,y,z, xgrid, ygrid)
plt.subplot(122)
plt.contour(xgrid, ygrid, zgrid)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/9lm6F.png" alt="enter image description here"/></p>