33Menu
44====
55
6+ Using texts to construct a simple menu.
67"""
7-
88import matplotlib .pyplot as plt
99
1010import matplotlib .artist as artist
1111import matplotlib .patches as patches
12- from matplotlib .transforms import IdentityTransform
1312
1413
1514class ItemProperties :
@@ -22,8 +21,8 @@ def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow',
2221
2322
2423class MenuItem (artist .Artist ):
25- padx = 5
26- pady = 5
24+ padx = 0.05 # inches
25+ pady = 0.05
2726
2827def __init__ (self ,fig ,labelstr ,props = None ,hoverprops = None ,
2928on_select = None ):
@@ -41,14 +40,16 @@ def __init__(self, fig, labelstr, props=None, hoverprops=None,
4140
4241self .on_select = on_select
4342
44- # Setting the transform to IdentityTransform() lets us specify
45- # coordinates directly in pixels.
46- self .label = fig .text (0 ,0 ,labelstr ,transform = IdentityTransform (),
43+ # specify coordinates in inches.
44+ self .label = fig .text (0 ,0 ,labelstr ,transform = fig .dpi_scale_trans ,
4745size = props .fontsize )
4846self .text_bbox = self .label .get_window_extent (
4947fig .canvas .get_renderer ())
48+ self .text_bbox = fig .dpi_scale_trans .inverted ().transform_bbox (self .text_bbox )
5049
51- self .rect = patches .Rectangle ((0 ,0 ),1 ,1 )# Will be updated later.
50+ self .rect = patches .Rectangle (
51+ (0 ,0 ),1 ,1 ,transform = fig .dpi_scale_trans
52+ )# Will be updated later.
5253
5354self .set_hover_props (False )
5455
@@ -63,7 +64,7 @@ def check_select(self, event):
6364
6465def set_extent (self ,x ,y ,w ,h ,depth ):
6566self .rect .set (x = x ,y = y ,width = w ,height = h )
66- self .label .set (position = (x + self .padx ,y + depth + self .pady / 2 ))
67+ self .label .set (position = (x + self .padx ,y + depth + self .pady / 2 ))
6768self .hover = False
6869
6970def draw (self ,renderer ):
@@ -97,10 +98,10 @@ def __init__(self, fig, menuitems):
9798maxh = max (item .text_bbox .height for item in menuitems )
9899depth = max (- item .text_bbox .y0 for item in menuitems )
99100
100- x0 = 100
101- y0 = 400
101+ x0 = 1
102+ y0 = 4
102103
103- width = maxw + 2 * MenuItem .padx
104+ width = maxw + 2 * MenuItem .padx
104105height = maxh + MenuItem .pady
105106
106107for item in menuitems :