Matplotlib - 如何在极坐标中绘制流线?

时间:2015-06-02 16:43:05

标签: python matplotlib polar-coordinates

我一直在尝试在matplotlib 1.4.3中绘制极轴上的流线。 streamplot函数自1.2.0以来一直存在,并且被文档认为是功能性和稳定的。这是一个小测试脚本:

from matplotlib import pyplot as plt
import numpy as np

# Define polar grid
r = np.arange(0,2001,50)
theta = np.arange(-np.pi, np.pi+np.pi/180, 2*np.pi/180)
r2D, theta2D = np.meshgrid(r, theta)
# Define some data
u = -np.sin(theta2D)
v = np.cos(theta2D)
# Set up axes
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
# Plot streamlines
ax.streamplot(r, theta, u, v, color='k', density=1, linewidth=1)

此脚本失败并带有以下回溯:

Traceback (most recent call last):
  File "streamline_test.py", line 15, in <module>
    ax.streamplot(r, theta, u, v, color='k', density=1, linewidth=1)
  File "python2.7/site-packages/matplotlib/axes/_axes.py", line 4204, in streamplot
    zorder=zorder)
  File "python2.7/site-packages/matplotlib/streamplot.py", line 167, in streamplot
    axes.add_patch(p)
  File "python2.7/site-packages/matplotlib/axes/_base.py", line 1568, in add_patch
    self._update_patch_limits(p)
  File "python2.7/site-packages/matplotlib/axes/_base.py", line 1586, in _update_patch_limits
    vertices = patch.get_path().vertices
  File "python2.7/site-packages/matplotlib/patches.py", line 4033, in get_path
    _path, fillable = self.get_path_in_displaycoord()
  File "python2.7/site-packages/matplotlib/patches.py", line 4054, in get_path_in_displaycoord
    shrinkB=self.shrinkB * dpi_cor
  File "python2.7/site-packages/matplotlib/patches.py", line 2613, in __call__
    shrinked_path = self._shrink(clipped_path, shrinkA, shrinkB)
  File "python2.7/site-packages/matplotlib/patches.py", line 2586, in _shrink
    left, right = split_path_inout(path, insideA)
  File "python2.7/site-packages/matplotlib/bezier.py", line 246, in split_path_inout
    ctl_points, command = next(path_iter)
StopIteration

显然,streamplot会永远迭代,并且必须在某个时刻停止。我还尝试了一组应用于极轴的规则间隔笛卡尔点,但是以相同的方式失败。使用笛卡尔坐标轴制作极坐标图不是一种选择,因为我需要一个极坐标网格,但是这样的网格在笛卡尔坐标系中不是规则间隔的,而且水库位图需要有规则间隔的点。

有人知道如何让matplotlib在极坐标中绘制流线吗?

1 个答案:

答案 0 :(得分:0)

您只需切换径向和方位角坐标即可。以下代码使this plot;注意在r的第三个参数中除以streamplot(),它将线性转换为角速度:

import math
import numpy
import matplotlib
from matplotlib import pyplot

pyplot.gcf().add_axes([0.1, 0.1, 0.8, 0.8], polar=True)

r = numpy.linspace(0, 1, 11)
phi = numpy.linspace(-1, 1, 361) * math.pi
r, phi = numpy.meshgrid(r, phi)

ones = numpy.ones_like(r)
zeros = numpy.zeros_like(r)
pyplot.streamplot(
  phi.transpose(), r.transpose(),
  (ones/r).transpose(), zeros.transpose(),
  color='red')
pyplot.streamplot(
  phi.transpose(), r.transpose(),
  (zeros/r).transpose(), ones.transpose(),
  color='blue')
pyplot.ylim(0, 1)
pyplot.annotate(matplotlib.__version__,
  (0, 0), (1, 0), 'axes fraction', 'axes fraction',
  ha='left', va='top')
pyplot.savefig('stream.png')