3939
4040
4141class DraggableLegend (DraggableOffsetBox ):
42- def __init__ (self , legend , use_blit = False ):
42+ def __init__ (self , legend , use_blit = False , update = "loc" ):
43+ """
44+ update : If "loc", update *loc* parameter of
45+ legend upon finalizing. If "bbox", update
46+ *bbox_to_anchor* parameter.
47+ """
4348 self .legend = legend
49+
50+ if update in ["loc" , "bbox" ]:
51+ self ._update = update
52+ else :
53+ raise ValueError ("update parameter '%s' is not supported." % update )
54+
4455 DraggableOffsetBox .__init__ (self , legend , legend ._legend_box ,
4556 use_blit = use_blit )
4657
@@ -50,6 +61,14 @@ def artist_picker(self, legend, evt):
5061 def finalize_offset (self ):
5162 loc_in_canvas = self .get_loc_in_canvas ()
5263
64+ if self ._update == "loc" :
65+ self ._update_loc (loc_in_canvas )
66+ elif self ._update == "bbox" :
67+ self ._update_bbox_to_anchor (loc_in_canvas )
68+ else :
69+ raise RuntimeError ("update parameter '%s' is not supported." % self .update )
70+
71+ def _update_loc (self , loc_in_canvas ):
5372 bbox = self .legend .get_bbox_to_anchor ()
5473
5574 # if bbox has zero width or height, the transformation is
@@ -62,6 +81,14 @@ def finalize_offset(self):
6281 self .legend ._loc = tuple (_bbox_transform .transform_point (loc_in_canvas ))
6382
6483
84+ def _update_bbox_to_anchor (self , loc_in_canvas ):
85+
86+ tr = self .legend .axes .transAxes
87+ loc_in_bbox = tr .transform_point (loc_in_canvas )
88+
89+ self .legend .set_bbox_to_anchor (loc_in_bbox )
90+
91+
6592class Legend (Artist ):
6693 """
6794 Place a legend on the axes at location loc. Labels are a
@@ -931,7 +958,7 @@ def _find_best_position(self, width, height, renderer, consider=None):
931958 return ox , oy
932959
933960
934- def draggable (self , state = None , use_blit = False ):
961+ def draggable (self , state = None , use_blit = False , update = "loc" ):
935962 """
936963 Set the draggable state -- if state is
937964
@@ -944,6 +971,10 @@ def draggable(self, state=None, use_blit=False):
944971 If draggable is on, you can drag the legend on the canvas with
945972 the mouse. The DraggableLegend helper instance is returned if
946973 draggable is on.
974+
975+ The update parameter control which parameter of the legend changes
976+ when dragged. If update is "loc", the *loc* paramter of the legend
977+ is changed. If "bbox", the *bbox_to_anchor* parameter is changed.
947978 """
948979 is_draggable = self ._draggable is not None
949980
@@ -953,7 +984,7 @@ def draggable(self, state=None, use_blit=False):
953984
954985 if state :
955986 if self ._draggable is None :
956- self ._draggable = DraggableLegend (self , use_blit )
987+ self ._draggable = DraggableLegend (self , use_blit , update = update )
957988 else :
958989 if self ._draggable is not None :
959990 self ._draggable .disconnect ()
0 commit comments