SVG过滤线

演示可能与mpl一起使用的SVG过滤效果。

请注意,过滤效果仅在您的svg渲染器支持时才有效。

SVG过滤线示例

输出:

  1. Saving 'svg_filter_line.svg'
  1. import matplotlib.pyplot as plt
  2. import matplotlib.transforms as mtransforms
  3. fig1 = plt.figure()
  4. ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
  5. # draw lines
  6. l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
  7. mec="b", lw=5, ms=10, label="Line 1")
  8. l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "rs-",
  9. mec="r", lw=5, ms=10, color="r", label="Line 2")
  10. for l in [l1, l2]:
  11. # draw shadows with same lines with slight offset and gray colors.
  12. xx = l.get_xdata()
  13. yy = l.get_ydata()
  14. shadow, = ax.plot(xx, yy)
  15. shadow.update_from(l)
  16. # adjust color
  17. shadow.set_color("0.2")
  18. # adjust zorder of the shadow lines so that it is drawn below the
  19. # original lines
  20. shadow.set_zorder(l.get_zorder() - 0.5)
  21. # offset transform
  22. ot = mtransforms.offset_copy(l.get_transform(), fig1,
  23. x=4.0, y=-6.0, units='points')
  24. shadow.set_transform(ot)
  25. # set the id for a later use
  26. shadow.set_gid(l.get_label() + "_shadow")
  27. ax.set_xlim(0., 1.)
  28. ax.set_ylim(0., 1.)
  29. # save the figure as a bytes string in the svg format.
  30. from io import BytesIO
  31. f = BytesIO()
  32. plt.savefig(f, format="svg")
  33. import xml.etree.cElementTree as ET
  34. # filter definition for a gaussian blur
  35. filter_def = """
  36. <defs xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
  37. <filter id='dropshadow' height='1.2' width='1.2'>
  38. <feGaussianBlur result='blur' stdDeviation='3'/>
  39. </filter>
  40. </defs>
  41. """
  42. # read in the saved svg
  43. tree, xmlid = ET.XMLID(f.getvalue())
  44. # insert the filter definition in the svg dom tree.
  45. tree.insert(0, ET.XML(filter_def))
  46. for l in [l1, l2]:
  47. # pick up the svg element with given id
  48. shadow = xmlid[l.get_label() + "_shadow"]
  49. # apply shadow filter
  50. shadow.set("filter", 'url(#dropshadow)')
  51. fn = "svg_filter_line.svg"
  52. print("Saving '%s'" % fn)
  53. ET.ElementTree(tree).write(fn)

下载这个示例