# plotm1.py3 experiment with matplotlib lines_text.py3 import numpy as np from numpy import array import matplotlib.pyplot as plt import matplotlib.lines as lines import matplotlib.transforms as mtransforms import matplotlib.text as mtext class MyLine(lines.Line2D): def __init__(self, *args, **kwargs): # we'll update the position when the line data is set self.text = mtext.Text(0, 0, '') lines.Line2D.__init__(self, *args, **kwargs) # we can't access the label attr until *after* the line is inited self.text.set_text(self.get_label()) def set_figure(self, figure): self.text.set_figure(figure) lines.Line2D.set_figure(self, figure) def set_axes(self, axes): self.text.set_axes(axes) lines.Line2D.set_axes(self, axes) def set_transform(self, transform): # 2 pixel offset texttrans = transform + mtransforms.Affine2D().translate(2, 2) self.text.set_transform(texttrans) lines.Line2D.set_transform(self, transform) def set_data(self, x, y): if len(x): self.text.set_position((x[-1], y[-1])) lines.Line2D.set_data(self, x, y) def draw(self, renderer): # draw my label at the end of the line with 2 pixel offset lines.Line2D.draw(self, renderer) self.text.draw(renderer) print("plotm1.py3 running") fig, ax = plt.subplots() # x, y = np.random.rand(2, 20) # 20 seqments npts = 10 x = array([(0.0) for j in range(npts)]) y = array([(0.0) for j in range(npts)]) x[0] = 0.1 x[1] = 0.2 x[2] = 0.7 x[3] = 0.8 x[4] = 0.9 x[5] = 0.3 x[6] = 0.4 x[7] = 0.5 x[8] = 0.6 x[9] = 0.6 y[0] = 0.1 y[1] = 0.2 y[2] = 0.3 y[3] = 0.4 y[4] = 0.5 y[5] = 0.9 y[6] = 0.8 y[7] = 0.7 y[8] = 0.6 y[9] = 0.6 print("x=",x) print("y=",y) line = MyLine(x, y, mfc='green', ms=12, label='line label') #line.text.set_text('new label') line.text.set_color('red') line.text.set_fontsize(20) ax.add_line(line) plt.title('line text plot1.py3') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show() print("plotm1.py3 finished")