|
| 1 | +""" |
| 2 | +Show how to override basic methods so an artist can contain another |
| 3 | +artist. In this case, the line contains a Text instance to label it. |
| 4 | +""" |
| 5 | +import numpy as np |
| 6 | +import matplotlib.pyplot as plt |
| 7 | +import matplotlib.lines as lines |
| 8 | +import matplotlib.transforms as mtransforms |
| 9 | +import matplotlib.text as mtext |
| 10 | + |
| 11 | + |
| 12 | +class MyLine(lines.Line2D): |
| 13 | + |
| 14 | + def __init__(self, *args, **kwargs): |
| 15 | + # we'll update the position when the line data is set |
| 16 | + self.text = mtext.Text(0, 0, '') |
| 17 | + lines.Line2D.__init__(self, *args, **kwargs) |
| 18 | + |
| 19 | + # we can't access the label attr until *after* the line is |
| 20 | + # inited |
| 21 | + self.text.set_text(self.get_label()) |
| 22 | + |
| 23 | + def set_figure(self, figure): |
| 24 | + self.text.set_figure(figure) |
| 25 | + lines.Line2D.set_figure(self, figure) |
| 26 | + |
| 27 | + def set_axes(self, axes): |
| 28 | + self.text.set_axes(axes) |
| 29 | + lines.Line2D.set_axes(self, axes) |
| 30 | + |
| 31 | + def set_transform(self, transform): |
| 32 | + # 2 pixel offset |
| 33 | + texttrans = transform + mtransforms.Affine2D().translate(2, 2) |
| 34 | + self.text.set_transform(texttrans) |
| 35 | + lines.Line2D.set_transform(self, transform) |
| 36 | + |
| 37 | + |
| 38 | + def set_data(self, x, y): |
| 39 | + if len(x): |
| 40 | + self.text.set_position((x[-1], y[-1])) |
| 41 | + |
| 42 | + lines.Line2D.set_data(self, x, y) |
| 43 | + |
| 44 | + def draw(self, renderer): |
| 45 | + # draw my label at the end of the line with 2 pixel offset |
| 46 | + lines.Line2D.draw(self, renderer) |
| 47 | + self.text.draw(renderer) |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +fig = plt.figure() |
| 54 | +ax = fig.add_subplot(111) |
| 55 | +x, y = np.random.rand(2, 20) |
| 56 | +line = MyLine(x, y, mfc='red', ms=12, label='line label') |
| 57 | +#line.text.set_text('line label') |
| 58 | +line.text.set_color('red') |
| 59 | +line.text.set_fontsize(16) |
| 60 | + |
| 61 | + |
| 62 | +ax.add_line(line) |
| 63 | + |
| 64 | + |
| 65 | +plt.show() |
0 commit comments