Home > Mobile >  Matplotlib: display legend keys for lines as patches by default
Matplotlib: display legend keys for lines as patches by default

Time:09-27

For background, see the showing lines as patches in legend

CodePudding user response:

You can display legend as patches doing the following:

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

colors = [['#01FF4F','#00FFff'],
           ['#FFEB00','#FFFF00']]
categories = ['A','B']
# categories and colors inside a dict
legend_dict=dict(zip(categories,colors))
# setting up lines for the plot and list for patches
patchList = []
fig, ax = plt.subplots()
# assigning each inner color for each categories to their respective plot lines and legend/patches
for key in legend_dict:
        data_key = mpatches.Patch(facecolor=legend_dict[key][0],
                                  edgecolor=legend_dict[key][1], label=key)
        ax.plot(np.random.randn(100).cumsum(), color=legend_dict[key][0], label=legend_dict[key][1])
        patchList.append(data_key)

ax.legend(handles=patchList, ncol=len(categories), fontsize='small')
plt.show()

Which output: enter image description here

I didn't know matplotlib before making this answer, so I had to mix two or three SO post to get this far (and trying/failing for a bit). Here they are, in a non-special order:

One intriguing and related to patches as legend post that I can't help but link to: Make patches bigger used as legend inside matplotlib

lastly, here is a decent excerpt related to customizing legend on matplotlib: https://jakevdp.github.io/PythonDataScienceHandbook/04.06-customizing-legends.html

  • Related