0

In Matplotlib, you can draw an arrow using Axes.arrow (https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.axes.Axes.arrow.html).

Is there a similar function for drawing a line with a circle or other butt at the end? I would've expected this to be a keyword argument option for Axes.arrow, but it doesn't seem to exist.

Orca
  • 177
  • 9
  • Bonus points if the line can be drawn outside the axes (i.e. at any point within the figure). – Orca Apr 13 '22 at 19:39
  • 1
    Related: https://stackoverflow.com/questions/16968007/custom-arrow-style-for-matplotlib-pyplot-annotate/ and https://stackoverflow.com/questions/22212435/possible-to-use-a-custom-arrow-or-polygon-as-a-marker-to-plot-location-and-headi – JohanC Apr 13 '22 at 22:27

1 Answers1

2

Just an idea with classes and inheritance but I think @johanc links are better:

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


class Line2D(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)

l = Line2D([0, 1], [0, 1], color="green")
ax.add_artist(l)

plt.show()

You can get other parameters (linewidth etc) to apply to your patches objetcs.

enter image description here

david
  • 1,302
  • 1
  • 10
  • 21