Search code examples
pythonmatplotlibgraphfigure

Trying to change line thickness with matplotlib.mpatches.Patch


I am manually making a legend as there are too many inputs in my figure, so I use matplotlib.mpatches.Patch to make legend using:

orange_patch = mpatches.Patch(color='orange', label='n=505 distribution', lw = 1)

grey_patch = mpatches.Patch(color = 'grey', label = 'n=100 sampled 100 times', lw = 1)

plt.legend(handles=[orange_patch, grey_patch], frameon = False)

This works, but the lines are very thick. Changing linewidth with "lw" changes the length and width of the line. I am looking to make the line thinner while preserving the length, similar to the thickness shown on the graph. Anyone know how to do this?

upper left shows legend I am trying to change


Solution

  • If the thickness (height of the patch) is not to your liking, you can use line2D instead. Documentation here. Here is the updated code for your reference.... Use lw (float) to adjust the thickness

    from matplotlib.lines import Line2D
    
    myHandle = [Line2D([], [], color='orange', lw = 3), Line2D([], [], color='gray', lw = 3)]
    
    plt.legend(handles = myHandle, labels=['n=505 distribution', 'n=100 sampled 100 times'], frameon = False)
    

    enter image description here