如何使用偏移正确放置PolyCollection?

时间:2016-11-05 00:25:21

标签: matplotlib

我想使用PolyCollection绘制一组相同的矩形,但我无法将它们放在正确的位置。在下面的代码中,我想在数据坐标方面放置三个以指定offsets为中心的矩形,但它们不会显示在正确的位置。

from matplotlib import collections

subplot_kw = dict(xlim=(0, 100), ylim=(0, 100))
fig, ax = plt.subplots(subplot_kw=subplot_kw, figsize=(5,5))
ivtx = 10 * np.array([-1,-1,1,1])/2.0
jvtx = 20 * np.array([-1,1,1,-1])/2.0
vtx = np.array(zip(jvtx, ivtx))
rectangles = collections.PolyCollection([vtx], offsets=[(0,0),(20,10),(40,60)], transOffset=ax.transData)
ax.add_collection(rectangles)

我认为问题是transOffset。什么是正确的转换?

rectangles are at the wrong offsets

1 个答案:

答案 0 :(得分:0)

抵消和transOffset的作用令人困惑地记录在案。要在PolyCollection的数据坐标中使用offsets,您需要将transOffset设置为标识转换,并将offset_position更改为"数据"。

collections.PolyCollection([vtx], offsets=[(0,0),(20,10),(40,60)], 
                                        transOffset=mtransforms.IdentityTransform(),
                                        offset_position="data")

完整示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import collections
import matplotlib.transforms as mtransforms

subplot_kw = dict(xlim=(0, 100), ylim=(0, 100))
fig, ax = plt.subplots(subplot_kw=subplot_kw, figsize=(5,5))
ivtx = 10 * np.array([-1,-1,1,1])/2.0
jvtx = 20 * np.array([-1,1,1,-1])/2.0
vtx = np.array(zip(jvtx, ivtx))
rectangles = collections.PolyCollection([vtx], offsets=[(0,0),(20,10),(40,60)], 
                                        transOffset=mtransforms.IdentityTransform(),
                                        offset_position="data")
ax.add_collection(rectangles)

plt.show()

enter image description here

<小时/> 另一种方法是直接计算顶点, 即手动转换它们:

import numpy as np
from matplotlib import collections
import matplotlib.pyplot as plt

subplot_kw = dict(xlim=(-20,70), ylim=(-20, 70))
fig, ax = plt.subplots(figsize=(5,5),subplot_kw=subplot_kw) #, 
ivtx = 10 * np.array([-1,-1,1,1])/2.0
jvtx = 20 * np.array([-1,1,1,-1])/2.0
vtx = np.array(zip(jvtx, ivtx))

def o(vtx, o):
    vtx = np.copy(vtx)
    vtx[:,0] = vtx[:,0]+o[0]
    vtx[:,1] = vtx[:,1]+o[1]
    return vtx

offsets=[(0,0),(20,10),(40,60)]
rectangles = collections.PolyCollection([o(vtx,offset) for offset in offsets])    
ax.add_collection(rectangles)

plt.show()