Skip to content
Advertisement

How to have a poligon in the legend

I have a chart with 4 elements: blue square,blue triangle, red square and red triangle, I’m tryng to add these 4 items to the legend. when I add a polygon patch to the legend, it is displayed as a rectangle, even though the patch is of a triangle How can I get it to work?

legend_elements = [patches.RegularPolygon((4, 4), 3, 0.5, np.pi / 4,label="Triangle")]
plt.legend(handles=legend_elements)

Advertisement

Answer

You could use line markers to indicate the polygons:

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

handles = [Line2D([0], [0], linestyle='none', mfc='blue', mec='blue', marker='s', label='blue square'),
           Line2D([0], [0], linestyle='none', mfc='blue', mec='blue', marker='^', label='blue triangle'),
           Line2D([0], [0], linestyle='none', mfc='red', mec='red', marker='s', label='red square'),
           Line2D([0], [0], linestyle='none', mfc='red', mec='red', marker='^', label='red triangle')]
plt.legend(handles=handles)
plt.show()

matplotlib legend with squares and triangles

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement