如何在创建后更改matplotlib LineCollection的偏移量

时间:2011-06-20 22:10:43

标签: python matplotlib

我想使用LineCollection创建一堆线图。下面的代码绘制两条相同的正弦曲线,它们相互偏移(0,0.2):

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

x=np.arange(1000)
y=np.sin(x/50.)
l=zip(x,y)

f=plt.figure()
a=f.add_subplot(111)
lines=matplotlib.collections.LineCollection((l,l), offsets=(0,0.2))
a.add_collection(lines)
a.autoscale_view(True, True, True)
plt.show()

到目前为止一切顺利。问题是我希望能够在创建后调整偏移量。使用set_offsets似乎没有按照我的预期行事。例如,以下内容对图表没有影响

a.collections[0].set_offsets((0, 0.5))
顺便说一句,其他设置命令(例如set_color)按预期工作。如何在创建曲线后更改曲线之间的间距?

2 个答案:

答案 0 :(得分:1)

我认为您在matplotlib中发现了一个错误,但我有几个解决方法。看起来lines._paths使用您提供的偏移量在LineCollection().__init__中生成lines._paths。致电lines.set_offsets()时,lines.set_offsets( (0., 0.2)) lines.set_segments( (l,l) ) 未获得更新。在您的简单示例中,您可以重新生成路径,因为您仍然有原始文件。

lines._paths[1].vertices[:,1] += 1

您也可以手动应用偏移量。请记住,您正在修改偏移点。因此,要获得0.2的偏移量,请将0.1添加到预先存在的0.1的偏移量。

{{1}}

答案 1 :(得分:0)

感谢@matt的建议。基于此我一起攻击了以下根据新的偏移值移动曲线,但考虑了旧的偏移值。这意味着我不必保留原始曲线数据。可能会做一些类似的事情来纠正LineCollection的set_offsets方法,但我不太了解该类的细节以便冒险。

def set_offsets(newoffsets, ax=None, c_num=0):
    '''
        Modifies the offsets between curves of a LineCollection

    '''

    if ax is None:
        ax=plt.gca()

    lcoll=ax.collections[c_num]
    oldoffsets=lcoll.get_offsets()

    if len(newoffsets)==1:
        newoffsets=[i*np.array(newoffsets[0]) for\
         (i,j) in enumerate(lcoll.get_paths())]
    if len(oldoffsets)==1:
        oldoffsets=[i*oldoffsets[0] for (i,j) in enumerate(newoffsets)]

    verts=[path.vertices for path in lcoll.get_paths()]

    for (oset, nset, vert) in zip(oldoffsets, newoffsets, verts):
        vert[:,0]+=(-oset[0]+nset[0])
        vert[:,1]+=(-oset[1]+nset[1])

    lcoll.set_offsets(newoffsets)
    lcoll.set_paths(verts)