艺术家中的艺术家

重写基本方法,以便一个艺术家对象可以包含另一个艺术家对象。在这种情况下,该行包含一个文本实例来为其添加标签。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.lines as lines
  4. import matplotlib.transforms as mtransforms
  5. import matplotlib.text as mtext
  6. class MyLine(lines.Line2D):
  7. def __init__(self, *args, **kwargs):
  8. # we'll update the position when the line data is set
  9. self.text = mtext.Text(0, 0, '')
  10. lines.Line2D.__init__(self, *args, **kwargs)
  11. # we can't access the label attr until *after* the line is
  12. # initiated
  13. self.text.set_text(self.get_label())
  14. def set_figure(self, figure):
  15. self.text.set_figure(figure)
  16. lines.Line2D.set_figure(self, figure)
  17. def set_axes(self, axes):
  18. self.text.set_axes(axes)
  19. lines.Line2D.set_axes(self, axes)
  20. def set_transform(self, transform):
  21. # 2 pixel offset
  22. texttrans = transform + mtransforms.Affine2D().translate(2, 2)
  23. self.text.set_transform(texttrans)
  24. lines.Line2D.set_transform(self, transform)
  25. def set_data(self, x, y):
  26. if len(x):
  27. self.text.set_position((x[-1], y[-1]))
  28. lines.Line2D.set_data(self, x, y)
  29. def draw(self, renderer):
  30. # draw my label at the end of the line with 2 pixel offset
  31. lines.Line2D.draw(self, renderer)
  32. self.text.draw(renderer)
  33. # Fixing random state for reproducibility
  34. np.random.seed(19680801)
  35. fig, ax = plt.subplots()
  36. x, y = np.random.rand(2, 20)
  37. line = MyLine(x, y, mfc='red', ms=12, label='line label')
  38. #line.text.set_text('line label')
  39. line.text.set_color('red')
  40. line.text.set_fontsize(16)
  41. ax.add_line(line)
  42. plt.show()

艺术家中的艺术家

参考

此示例显示了以下函数、方法、类和模块的使用:

  1. import matplotlib
  2. matplotlib.lines
  3. matplotlib.lines.Line2D
  4. matplotlib.lines.Line2D.set_data
  5. matplotlib.artist
  6. matplotlib.artist.Artist
  7. matplotlib.artist.Artist.draw
  8. matplotlib.artist.Artist.set_transform
  9. matplotlib.text
  10. matplotlib.text.Text
  11. matplotlib.text.Text.set_color
  12. matplotlib.text.Text.set_fontsize
  13. matplotlib.text.Text.set_position
  14. matplotlib.axes.Axes.add_line
  15. matplotlib.transforms
  16. matplotlib.transforms.Affine2D

下载这个示例