组合 matplotlib quiver 和 elipses 不起作用

Combining matplotlib quiver and elipses doesn't work

我偶然发现了 matplotlib 无法解释的行为。如果我使用 imshow 绘制图像,添加箭袋图和椭圆,箭袋图箭头角度会损坏。请参阅下面的示例代码。 执行它会使椭圆和颤动箭头指向不同的方向,即使两者的角度相同。仅当使用 imshow 绘制图像时才会发生这种情况。经过一天的调试,我发现设置 ylim 解决了问题。您可以 运行 代码,然后取消注释最后两行,然后再次 运行 。 我将 matplotlib 升级到最新版本问题仍然存在。 你的安装有同样的问题吗?这是一个错误还是我在这里遗漏了其他东西?

在两个 Win32 Python 2.7 系统上测试

谢谢!

import numpy as np
import  matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

x,y, width,height,angle=20.0, 20.0, 7.0, 3.0, 160.0

fig = plt.figure(figsize=(12,8))
img=np.zeros((40,40))
ax = fig.add_subplot(111)
ax.imshow(img)
e = Ellipse(xy=(x,y), width=width, height=height, angle=angle)
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.2)
e.set_facecolor('red')
ax.quiver(np.array(x), np.array(y),np.array(x),np.array(x), angles=np.array(angle), headwidth=2, color='green')

#remove comments
#ax.set_xlim([0,40])
#ax.set_ylim([0,40])

添加这些行而不是当前对 ax.imshow 的调用:

ax.set_aspect('equal','box')
ax.imshow(img, origin='lower')

第一行使轴将 x、y 保持在相同的度量中,imshow 的 origin kwarg 使其使用与 matplotlib 的大多数其余部分相同的 (0,0)。

您的示例的一个版本更易于使用以查看各部分的功能:

import numpy as np
import  matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

x, y, width, height, angle=10.0, 6.0, 7.0, 3.0, 160.0

fig = plt.figure(figsize=(12,8))
xx, yy = np.meshgrid(range(20), range(20))
img = (2*xx + yy)/40. # something asymmetrical to understand axes

ax1 = fig.add_subplot(121)
ax1.set_aspect('equal','box')
im1 = ax1.imshow(img, interpolation='none')
ax1.set_title('UL imshow origin')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(img, interpolation='none', origin='lower')
ax2.set_title('LL imshow origin')

def oneEllipse():
    return Ellipse(xy=(x,y), width=width, height=height, angle=angle,
            facecolor='black')
    # Can't define one Ellipse and add it to two axes. Huh. 

for ax in (ax1, ax2):
    ax.add_artist(oneEllipse())
    # quiver can take a bunch of different function signatures
    # comment out the second or the third line to change the signature easily
    qi = ax.quiver(np.array([x, x+1]), np.array([y, y-1]), #
                np.array([width, width*2]),np.array([height, height/2.]),
                #angles='xy', # this uses the U, V args and flips the vectors
                #angles=np.array([angle, angle]), # angles come out the same
                headwidth=2, color=['white', 'red'], zorder=10)

椭圆和imshow一起翻转,箭头原点X,Y同上,angles='xy'翻转箭头方向。对我来说似乎是正确的,但颤抖是挑剔的。