Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 46ef01d

Browse files
committed
added findobj
svn path=/trunk/matplotlib/; revision=5709
1 parent d24de73 commit 46ef01d

7 files changed

Lines changed: 156 additions & 0 deletions

File tree

CHANGELOG

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2007-07-03 Implemented findobj method for artist and pyplot - see
2+
examples/pylab_examples/findobj_demo.py - JDH
3+
14
2008-06-30 Another attempt to fix TextWithDash - DSD
25

36
2008-06-30 Removed Qt4 NavigationToolbar2.destroy -- it appears to
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
import matplotlib.text as text
4+
5+
a = np.arange(0,3,.02)
6+
b = np.arange(0,3,.02)
7+
c = np.exp(a)
8+
d = c[::-1]
9+
10+
fig = plt.figure()
11+
ax = fig.add_subplot(111)
12+
plt.plot(a,c,'k--',a,d,'k:',a,c+d,'k')
13+
plt.legend(('Model length', 'Data length', 'Total message length'),
14+
'upper center', shadow=True)
15+
plt.ylim([-1,20])
16+
plt.grid(False)
17+
plt.xlabel('Model complexity --->')
18+
plt.ylabel('Message length --->')
19+
plt.title('Minimum Message Length')
20+
21+
# match on arbitrary function
22+
def myfunc(x):
23+
return hasattr(x, 'set_color')
24+
25+
for o in fig.findobj(myfunc):
26+
o.set_color('blue')
27+
28+
# match on class instances
29+
for o in fig.findobj(text.Text):
30+
o.set_fontstyle('italic')
31+
32+
33+
34+
plt.show()

lib/matplotlib/artist.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,46 @@ def set(self, **kwargs):
508508
ret.extend( [func(v)] )
509509
return ret
510510

511+
def findobj(self, match=None):
512+
"""
513+
recursively find all :class:matplotlib.artist.Artist instances
514+
contained in self
515+
516+
*match* can be
517+
518+
- None: return all objects contained in artist (including artist)
519+
520+
- function with signature ``boolean = match(artist)`` used to filter matches
521+
522+
- class instance: eg Line2D. Only return artists of class type
523+
"""
524+
525+
if match is None: # always return True
526+
def matchfunc(x): return True
527+
elif cbook.issubclass_safe(match, Artist):
528+
def matchfunc(x):
529+
return isinstance(x, match)
530+
elif callable(match):
531+
matchfunc = match
532+
else:
533+
raise ValueError('match must be None, an matplotlib.artist.Artist subclass, or a callable')
534+
535+
536+
artists = []
537+
if hasattr(self, 'get_children'):
538+
for c in self.get_children():
539+
if matchfunc(c):
540+
artists.append(c)
541+
artists.extend([thisc for thisc in c.findobj(matchfunc) if matchfunc(thisc)])
542+
else:
543+
if matchfunc(self):
544+
artists.append(self)
545+
return artists
546+
547+
548+
549+
550+
511551

512552
class ArtistInspector:
513553
"""
@@ -690,6 +730,48 @@ def pprint_getters(self):
690730
return lines
691731

692732

733+
734+
def findobj(self, match=None):
735+
"""
736+
recursively find all :class:matplotlib.artist.Artist instances
737+
contained in self
738+
739+
if *match* is not None, it can be
740+
741+
- function with signature ``boolean = match(artist)``
742+
743+
- class instance: eg Line2D
744+
745+
used to filter matches
746+
"""
747+
748+
if match is None: # always return True
749+
def matchfunc(x): return True
750+
elif issubclass(match, Artist):
751+
def matchfunc(x):
752+
return isinstance(x, match)
753+
elif callable(match):
754+
matchfunc = func
755+
else:
756+
raise ValueError('match must be None, an matplotlib.artist.Artist subclass, or a callable')
757+
758+
759+
artists = []
760+
if hasattr(self, 'get_children'):
761+
for c in self.get_children():
762+
if matchfunc(c):
763+
artists.append(c)
764+
artists.extend([thisc for thisc in c.findobj(matchfunc) if matchfunc(thisc)])
765+
else:
766+
if matchfunc(self):
767+
artists.append(self)
768+
return artists
769+
770+
771+
772+
773+
774+
693775
def getp(o, property=None):
694776
"""
695777
Return the value of handle property. property is an optional string

lib/matplotlib/cbook.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,13 @@ def safezip(*args):
886886
raise ValueError(_safezip_msg % (Nx, i+1, len(arg)))
887887
return zip(*args)
888888

889+
def issubclass_safe(x, klass):
890+
'return issubclass(x, klass) and return False on a TypeError'
891+
892+
try:
893+
return issubclass(x, klass)
894+
except TypeError:
895+
return False
889896

890897
class MemoryMonitor:
891898
def __init__(self, nmax=20000):

lib/matplotlib/legend.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,12 @@ def draw_frame(self, b):
363363
'b is a boolean. Set draw frame to b'
364364
self._drawFrame = b
365365

366+
def get_children(self):
367+
children = []
368+
children.extend(self.legendHandles)
369+
children.extend(self.texts)
370+
return children
371+
366372
def get_frame(self):
367373
'return the Rectangle instance used to frame the legend'
368374
return self.legendPatch

lib/matplotlib/pylab.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
figtext - add text in figure coords
3939
figure - create or change active figure
4040
fill - make filled polygons
41+
findobj - recursively find all objects matching some criteria
4142
gca - return the current axes
4243
gcf - return the current figure
4344
gci - get the current image, or None

lib/matplotlib/pyplot.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,29 @@
3838
from matplotlib.backends import pylab_setup
3939
new_figure_manager, draw_if_interactive, show = pylab_setup()
4040

41+
42+
43+
def findobj(o=None, match=None):
44+
"""
45+
recursively find all :class:matplotlib.artist.Artist instances
46+
contained in artist instance *p*. if *o* is None, use
47+
current figure
48+
49+
*match* can be
50+
51+
- None: return all objects contained in artist (including artist)
52+
53+
- function with signature ``boolean = match(artist)`` used to filter matches
54+
55+
- class instance: eg Line2D. Only return artists of class type
56+
57+
"""
58+
59+
if o is None:
60+
o = gcf()
61+
return o.findobj(match)
62+
63+
4164
def switch_backend(newbackend):
4265
"""
4366
Switch the default backend to newbackend. This feature is

0 commit comments

Comments
 (0)