2

In my answer to this question I tried to extend Line2D.draw method so that it can be used with plot.

So I changed matplotlib.lines.Line2D to my Line2D extension:

import matplotlib.lines
import matplotlib.pyplot as plt
import matplotlib.patches as pt


class Line2D(matplotlib.lines.Line2D):
    def draw(self, rdr):
        super().draw(rdr)
        xy = self.get_xydata()
        start, end = xy[0], xy[-1]
        r = pt.Rectangle((start[0] - .05, start[1] - .05), .1, .1,
                         color=self.get_color(),
                         fill=None)
        plt.gca().add_patch(r)
        c = pt.Ellipse(end, .05, .05,
                       color=self.get_color(),
                       fill=True)
        plt.gca().add_patch(c)


fig = plt.figure()
ax = fig.add_subplot()
rg = [-.5, 1.5]
ax.set_xlim(rg)
ax.set_ylim(rg)


original_line2D = matplotlib.lines.Line2D
matplotlib.lines.Line2D = Line2D

plt.plot([0, 1], [1, 0], "r--")

plt.show()

I got this result, and I guess plt.plot is used internally... but how to avoid these ghosts drawings?

enter image description here

gboffi
  • 22,939
  • 8
  • 54
  • 85
david
  • 1,302
  • 1
  • 10
  • 21

1 Answers1

2

I think you are allowed to use your line, but then you should reset it to matplotlib's original Line2D. For example:

fig = plt.figure()
ax = fig.add_subplot()
rg = [-.5, 1.5]
ax.set_xlim(rg)
ax.set_ylim(rg)

original_line2D = matplotlib.lines.Line2D
matplotlib.lines.Line2D = MyLine2D

plt.plot([0, 1], [1, 0], "r--")
matplotlib.lines.Line2D = original_line2D
plt.plot([1, 0], [1, 1], "g")
plt.show()

Removing the last line (green), works as expected.

enter image description here

Davide_sd
  • 10,578
  • 3
  • 18
  • 30
  • 1
    @davide-sd Thx, modifying this class seems to be tricky. I suppose I should not use high levels commands... However thanks. I also noticed `plt.savefig` do not save additionnal drawings... – david Apr 15 '22 at 19:09