0

I was checking the following example of matplotlib and came across something that I feel is weird.

import matplotlib.pyplot as plt

line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
line3, = plt.plot([4,5,6], label='Line 3')
line4, = plt.plot([-4,-5,-6], label='Line 4')

# Create a legend for the first line.
first_legend = plt.legend(handles=[line1, line3], loc=1)

# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)

# Create another legend for the second line.
plt.legend(handles=[line2, line4], loc=4)

plt.show()

Why do we need to add a trailing comma to line in order for it to work?

Satrapes
  • 183
  • 1
  • 18
  • 3
    Because the function returns an iterable and you just want the first value. – Malik Brahimi Jun 23 '15 at 15:45
  • 1
    Or to correct myself, the function returns an iterable of a single element. – Malik Brahimi Jun 23 '15 at 15:47
  • 1
    @johnrsharpe it is clear as day that this is a duplicate but I would never find the other question as I think it doesn't have a good title. I suggest editing the other title if possible. – Satrapes Jun 23 '15 at 15:54
  • I don't like the single trailing comma -- it looks strange to me and can be hard to spot. What I do -- and it isn't something I've seen done frequently -- is unpack the iterable into list of one item: `[line3] = plt.plot([4,5,6], label='Line 3')`. – jme Jun 23 '15 at 17:01

0 Answers0