Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2This module is to support *bbox_inches* option in savefig command. 

3""" 

4 

5from matplotlib.transforms import Bbox, TransformedBbox, Affine2D 

6 

7 

8def adjust_bbox(fig, bbox_inches, fixed_dpi=None): 

9 """ 

10 Temporarily adjust the figure so that only the specified area 

11 (bbox_inches) is saved. 

12 

13 It modifies fig.bbox, fig.bbox_inches, 

14 fig.transFigure._boxout, and fig.patch. While the figure size 

15 changes, the scale of the original figure is conserved. A 

16 function which restores the original values are returned. 

17 """ 

18 

19 origBbox = fig.bbox 

20 origBboxInches = fig.bbox_inches 

21 orig_tight_layout = fig.get_tight_layout() 

22 _boxout = fig.transFigure._boxout 

23 

24 fig.set_tight_layout(False) 

25 

26 asp_list = [] 

27 locator_list = [] 

28 for ax in fig.axes: 

29 pos = ax.get_position(original=False).frozen() 

30 locator_list.append(ax.get_axes_locator()) 

31 asp_list.append(ax.get_aspect()) 

32 

33 def _l(a, r, pos=pos): 

34 return pos 

35 ax.set_axes_locator(_l) 

36 ax.set_aspect("auto") 

37 

38 def restore_bbox(): 

39 for ax, asp, loc in zip(fig.axes, asp_list, locator_list): 

40 ax.set_aspect(asp) 

41 ax.set_axes_locator(loc) 

42 

43 fig.bbox = origBbox 

44 fig.bbox_inches = origBboxInches 

45 fig.set_tight_layout(orig_tight_layout) 

46 fig.transFigure._boxout = _boxout 

47 fig.transFigure.invalidate() 

48 fig.patch.set_bounds(0, 0, 1, 1) 

49 

50 if fixed_dpi is not None: 

51 tr = Affine2D().scale(fixed_dpi) 

52 dpi_scale = fixed_dpi / fig.dpi 

53 else: 

54 tr = Affine2D().scale(fig.dpi) 

55 dpi_scale = 1. 

56 

57 _bbox = TransformedBbox(bbox_inches, tr) 

58 

59 fig.bbox_inches = Bbox.from_bounds(0, 0, 

60 bbox_inches.width, bbox_inches.height) 

61 x0, y0 = _bbox.x0, _bbox.y0 

62 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale 

63 fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) 

64 fig.transFigure.invalidate() 

65 

66 fig.bbox = TransformedBbox(fig.bbox_inches, tr) 

67 

68 fig.patch.set_bounds(x0 / w1, y0 / h1, 

69 fig.bbox.width / w1, fig.bbox.height / h1) 

70 

71 return restore_bbox 

72 

73 

74def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): 

75 """ 

76 This need to be called when figure dpi changes during the drawing 

77 (e.g., rasterizing). It recovers the bbox and re-adjust it with 

78 the new dpi. 

79 """ 

80 

81 bbox_inches, restore_bbox = bbox_inches_restore 

82 restore_bbox() 

83 r = adjust_bbox(fig, bbox_inches, fixed_dpi) 

84 

85 return bbox_inches, r