1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import matplotlib.pyplot as plt import xml.etree.ElementTree as ET from io import BytesIO
ET.register_namespace("", "http://www.w3.org/2000/svg")
fig, ax = plt.subplots()
rect1 = plt.Rectangle((10, -20), 10, 5, fc='blue') rect2 = plt.Rectangle((-20, 15), 10, 5, fc='green')
shapes = [rect1, rect2] labels = ['This is a blue rectangle.', 'This is a green rectangle']
for i, (item, label) in enumerate(zip(shapes, labels)): patch = ax.add_patch(item) annotate = ax.annotate(labels[i], xy=item.get_xy(), xytext=(0, 0), textcoords='offset points', color='w', ha='center', fontsize=8, bbox=dict(boxstyle='round, pad=.5', fc=(.1, .1, .1, .92), ec=(1., 1., 1.), lw=1, zorder=1))
ax.add_patch(patch) patch.set_gid('mypatch_{:03d}'.format(i)) annotate.set_gid('mytooltip_{:03d}'.format(i))
ax.set_xlim(-30, 30) ax.set_ylim(-30, 30) ax.set_aspect('equal')
f = BytesIO() plt.savefig(f, format="svg")
tree, xmlid = ET.XMLID(f.getvalue()) tree.set('onload', 'init(evt)')
for i in shapes: index = shapes.index(i) tooltip = xmlid['mytooltip_{:03d}'.format(index)] tooltip.set('visibility', 'hidden') mypatch = xmlid['mypatch_{:03d}'.format(index)] mypatch.set('onmouseover', "ShowTooltip(this)") mypatch.set('onmouseout', "HideTooltip(this)")
script = """ <script type="text/ecmascript"> <![CDATA[
function init(evt) { if ( window.svgDocument == null ) { svgDocument = evt.target.ownerDocument; } }
function ShowTooltip(obj) { var cur = obj.id.split("_")[1]; var tip = svgDocument.getElementById('mytooltip_' + cur); tip.setAttribute('visibility',"visible") }
function HideTooltip(obj) { var cur = obj.id.split("_")[1]; var tip = svgDocument.getElementById('mytooltip_' + cur); tip.setAttribute('visibility',"hidden") }
]]> </script> """
tree.insert(0, ET.XML(script)) ET.ElementTree(tree).write('svg_tooltip.svg')
|