0

I have a figure (below) in python. i want to make double right-angle triangles as my legend using ax.get_legend_handles_labels. enter image description here

I want this (legend shape below) could you please help me get the shape of double right-angle triangles as the legend (below) using matplotlib.Line2D? enter image description here

i tried the following codes but it fails.

#define right angles triangles
angle=180
verts_ob = [[-1, -1], [1, -1], [1, 1], [-1, -1]]
verts = mpl.markers.MarkerStyle(marker=verts_ob)
verts._transform = verts.get_transform().rotate_deg(angle)

##apply mlines.Line2D to get shapes of the desired marker
import matplotlib.lines as mlines
Del_triangle_cna = mlines.Line2D([], [], color='#001261', marker=verts_ob, linestyle='None',mec='white', mfc='#C3B477', mew=1, markersize=100)
Neut_triangle_cna = mlines.Line2D([], [], color='#001261', marker=r'$\blacktriangleleft/\blacktriangleright$', linestyle='None',mec='white', mfc='grey', mew=1,markersize=200)

Thanks for your help.

sahuno
  • 321
  • 1
  • 8
  • 2
    [using mpatches.Patch for a custom legend](https://stackoverflow.com/a/44098900/12046409) gives an example where an ellipse is added to a legend. It could be modified to add a `Polygon`. – JohanC Jan 15 '21 at 17:10
  • sorry, how can I superimpose right-angle triangles as the one in the figure? it isn't part of markers. – sahuno Jan 15 '21 at 18:19

1 Answers1

3

Following the example at this official tutorial, you can create your own handler:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

class DoubleTriangle:
    def __init__(self, color_left, color_right):
        self.color_left = color_left
        self.color_right = color_right

class DoubleTriangleHandler:
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x, y = handlebox.xdescent, handlebox.ydescent
        w, h = handlebox.width, handlebox.height
        gap = h / 3
        triangle_left = mpatches.Polygon([[x, y + gap], [x, y + h], [x + w - gap, y + h]],
                                         facecolor=orig_handle.color_left,
                                         edgecolor='black', lw=1, transform=handlebox.get_transform())
        triangle_right = mpatches.Polygon([[x + gap, y], [x + w, y + h - gap], [x + w, y]],
                                          facecolor=orig_handle.color_right,
                                          edgecolor='black', lw=1, transform=handlebox.get_transform())
        handlebox.add_artist(triangle_left)
        handlebox.add_artist(triangle_right)
        return triangle_left, triangle_right

plt.legend([DoubleTriangle('red', 'green'), DoubleTriangle('blue', 'yellow')],
           ['Red - Green', 'Blue - Yellow'],
           handler_map={DoubleTriangle: DoubleTriangleHandler()})
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66