Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 11th, 2012  |  syntax: None  |  size: 1.22 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to change offsets of matplotlib LineCollection after creation
  2. import matplotlib.pyplot as plt
  3. import matplotlib.collections
  4. import numpy as np
  5.  
  6. x=np.arange(1000)
  7. y=np.sin(x/50.)
  8. l=zip(x,y)
  9.  
  10. f=plt.figure()
  11. a=f.add_subplot(111)
  12. lines=matplotlib.collections.LineCollection((l,l), offsets=(0,0.2))
  13. a.add_collection(lines)
  14. a.autoscale_view(True, True, True)
  15. plt.show()
  16.        
  17. a.collections[0].set_offsets((0, 0.5))
  18.        
  19. lines.set_offsets( (0., 0.2))
  20. lines.set_segments( (l,l) )
  21.        
  22. lines._paths[1].vertices[:,1] += 1
  23.        
  24. def set_offsets(newoffsets, ax=None, c_num=0):
  25.     '''
  26.         Modifies the offsets between curves of a LineCollection
  27.  
  28.     '''
  29.  
  30.     if ax is None:
  31.         ax=plt.gca()
  32.  
  33.     lcoll=ax.collections[c_num]
  34.     oldoffsets=lcoll.get_offsets()
  35.  
  36.     if len(newoffsets)==1:
  37.         newoffsets=[i*np.array(newoffsets[0]) for
  38.          (i,j) in enumerate(lcoll.get_paths())]
  39.     if len(oldoffsets)==1:
  40.         oldoffsets=[i*oldoffsets[0] for (i,j) in enumerate(newoffsets)]
  41.  
  42.     verts=[path.vertices for path in lcoll.get_paths()]
  43.  
  44.     for (oset, nset, vert) in zip(oldoffsets, newoffsets, verts):
  45.         vert[:,0]+=(-oset[0]+nset[0])
  46.         vert[:,1]+=(-oset[1]+nset[1])
  47.  
  48.     lcoll.set_offsets(newoffsets)
  49.     lcoll.set_paths(verts)