SVG工具提示

此示例显示如何创建将在Matplotlib面片上悬停时显示的工具提示。

虽然可以从CSS或javascript创建工具提示,但在这里,我们在matplotlib中创建它,并在将其悬停在修补程序上时简单地切换它的可见性。这种方法提供了对工具提示的位置和外观的完全控制,而代价是预先获得更多的代码。

另一种方法是将工具提示内容放在SVG对象的Title属性中。然后,使用现有的js/css库,在浏览器中创建工具提示相对简单。内容由title属性决定,外观由CSS决定。

作者:David Huard

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

下载这个示例