Jessica Chambers
Jessica Chambers

Reputation: 1316

Matplotlib graph legend for multiple entries

I am plotting several polygons in a plot:

from shapely.geometry import Polygon
import matplotlib.pyplot as plt

polygons.append(Polygon([(1,9), (4,9), (4,6), (1,6)]))
polygons.append(Polygon([(7,9), (10,9), (10,6), (7,6)]))
polygons.append(Polygon([(7,4), (10,4), (10,1), (7,1)]))
polygons.append(Polygon([(1,4), (4,4), (4,1), (1,1)]))
polygons.append(Polygon([(3,3), (3,7), (8,7), (8,3)]))

plt.figure()
for poly in polygons:
    plt.plot(*poly.exterior.xy)
plt.show()

The resulting plot correctly show my polygons, but I would like to know which one corresponds to which index on the plot (eg: the green polygon is the polygon at polygons[2]). Ideally I'd like a legend that associates the colour of the polygon with its index, but I can not figure out how to add such a legend in a loop like this. I have tried plt.legend(polygons.index(poly)) but that did not work.

The amount of polygons is variable so strictly assigning colours is out of the question.

How can I add a legend?

Upvotes: 1

Views: 342

Answers (1)

Sheldore
Sheldore

Reputation: 39042

I do not have shapely installed but you can try something along these lines. You can use label parameter to mark the legends by tracking the polygon index using enumerate.

plt.figure()

for i, poly in enumerate(polygons):
    plt.plot(*poly.exterior.xy, label="Polygon %d"%i)
plt.legend()
plt.show()

Upvotes: 1

Related Questions