0

I'm trying to add a method to the legend class in matplotlib. I've read the following answers here. and I'm basically trying to refactor the answer found here into a reusable method.

I'm not quite sure if I am doing this correctly, but I would like my end result to look something like this:

import matplotlib.pyplot as plt
from matplotlib.pyplot import legend
import pandas as pd
import numpy as np


def set_marker_legend(self, size):
    for handle in lgnd.legendHandles:
        handle._legmarker.set_markersize(size)


# Adding method to legend class
legend.set_marker_legend = set_marker_legend

x = np.arange(1, 11, 1)
y = x**2
group = np.repeat(['case1','case2'], [5,5], axis=0)

dat = pd.DataFrame({"x":x, "y":y, "group":group})

colors = {'case1':'black', 'case2':'red'}

grouped = dat.groupby('group')
for key, group in grouped:
    plt.plot(group.x, group.y, 
             markersize=3, marker='o', 
             linestyle='None', color=colors[key])

# What I would like to be able to do
plt.legend(labels=['Case 1', 'Case 2']).set_marker_legend(8)
plt.show()
dylanjm
  • 2,011
  • 9
  • 21
  • The legend class is at `matplotlib.legend.Legend` (`pyplot.legend` is a function, so adding a method to that function is not going to give anything usable). – ImportanceOfBeingErnest Jul 26 '19 at 20:02
  • @ImportanceOfBeingErnest so what you're saying is that I need to `from matplotlib.legend import Legend` and the method to that class? – dylanjm Jul 26 '19 at 20:04
  • @ImportanceOfBeingErnest That worked for me, please add it as an answer and I will verify. – dylanjm Jul 26 '19 at 20:06
  • I gave an answer in the linked post covering how I would handle such case. I do not intend to trick people into monkey-patching the library by providing an answer here in case such patches are not necessary. – ImportanceOfBeingErnest Jul 26 '19 at 20:07
  • @ImportanceOfBeingErnest Is it really a bad idea in this case since I'm not changing any of the default methods in the Legend class? It seems like it wouldn't cause any issues. – dylanjm Jul 26 '19 at 20:19
  • 1
    The problem is rather the inside of that function. It will sure fail in cases other than lines. So one should have one function per handle type. That is what the `handler_map` dictionary is useful for. (You can sure do whatever you like, but I won't take responsibility for such method by providing an answer here.) – ImportanceOfBeingErnest Jul 26 '19 at 20:25
  • 1
    I updated [my answer](https://stackoverflow.com/a/52674959/4124317) to also show a line plot with markers. – ImportanceOfBeingErnest Jul 26 '19 at 20:52

0 Answers0