SVG过滤管道

演示可能与mpl一起使用的SVG过滤效果。饼图绘制代码借用了pie_demo.py

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

SVG过滤管道示例

输出:

  1. Saving 'svg_filter_pie.svg'
  1. import matplotlib.pyplot as plt
  2. from matplotlib.patches import Shadow
  3. # make a square figure and axes
  4. fig1 = plt.figure(1, figsize=(6, 6))
  5. ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
  6. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  7. fracs = [15, 30, 45, 10]
  8. explode = (0, 0.05, 0, 0)
  9. # We want to draw the shadow for each pie but we will not use "shadow"
  10. # option as it does'n save the references to the shadow patches.
  11. pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
  12. for w in pies[0]:
  13. # set the id with the label.
  14. w.set_gid(w.get_label())
  15. # we don't want to draw the edge of the pie
  16. w.set_ec("none")
  17. for w in pies[0]:
  18. # create shadow patch
  19. s = Shadow(w, -0.01, -0.01)
  20. s.set_gid(w.get_gid() + "_shadow")
  21. s.set_zorder(w.get_zorder() - 0.1)
  22. ax.add_patch(s)
  23. # save
  24. from io import BytesIO
  25. f = BytesIO()
  26. plt.savefig(f, format="svg")
  27. import xml.etree.cElementTree as ET
  28. # filter definition for shadow using a gaussian blur
  29. # and lightening effect.
  30. # The lightening filter is copied from http://www.w3.org/TR/SVG/filters.html
  31. # I tested it with Inkscape and Firefox3. "Gaussian blur" is supported
  32. # in both, but the lightening effect only in the Inkscape. Also note
  33. # that, Inkscape's exporting also may not support it.
  34. filter_def = """
  35. <defs xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
  36. <filter id='dropshadow' height='1.2' width='1.2'>
  37. <feGaussianBlur result='blur' stdDeviation='2'/>
  38. </filter>
  39. <filter id='MyFilter' filterUnits='objectBoundingBox' x='0' y='0' width='1' height='1'>
  40. <feGaussianBlur in='SourceAlpha' stdDeviation='4%' result='blur'/>
  41. <feOffset in='blur' dx='4%' dy='4%' result='offsetBlur'/>
  42. <feSpecularLighting in='blur' surfaceScale='5' specularConstant='.75'
  43. specularExponent='20' lighting-color='#bbbbbb' result='specOut'>
  44. <fePointLight x='-5000%' y='-10000%' z='20000%'/>
  45. </feSpecularLighting>
  46. <feComposite in='specOut' in2='SourceAlpha' operator='in' result='specOut'/>
  47. <feComposite in='SourceGraphic' in2='specOut' operator='arithmetic'
  48. k1='0' k2='1' k3='1' k4='0'/>
  49. </filter>
  50. </defs>
  51. """
  52. tree, xmlid = ET.XMLID(f.getvalue())
  53. # insert the filter definition in the svg dom tree.
  54. tree.insert(0, ET.XML(filter_def))
  55. for i, pie_name in enumerate(labels):
  56. pie = xmlid[pie_name]
  57. pie.set("filter", 'url(#MyFilter)')
  58. shadow = xmlid[pie_name + "_shadow"]
  59. shadow.set("filter", 'url(#dropshadow)')
  60. fn = "svg_filter_pie.svg"
  61. print("Saving '%s'" % fn)
  62. ET.ElementTree(tree).write(fn)

下载这个示例