David
David

Reputation: 523

Set a different `numpoints` parameter for each line inside the same matplotlib legend

I have following plot:

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0, 0.25*np.pi, 200)
plt.plot(x, np.sin(x),label="sin", marker="x", markevery=12, c='k')
plt.plot(x, np.cos(x),label="cos", marker=".",markersize=1, lw=0, c='k')
plt.plot(x, np.tan(x),label="tan", ls="-.", c='k')
plt.gca().legend(numpoints=1)

plot of sin(x), cos(x), and tan(x) with a legend

The cosine would be better represented in the legend using, e.g., numpoints=8, while the sine is best represented as it is in the above image. Is there a way (rather a workaround) to use numpoints=1 for all but the cosine? Maybe combining two legends in one?

Upvotes: 2

Views: 170

Answers (1)

DavidG
DavidG

Reputation: 25363

You can create a custom handler, and then pass this handler as an keyword to the legend function. This is shown in the documentation.

We can use legend_handler.HandlerLine2D which accepts a numpoints argument. The lines which are not used in the handler map use the default number of numpoints in the legend:

from matplotlib.legend_handler import HandlerLine2D

x = np.linspace(0, 0.25*np.pi, 200)
line1, = plt.plot(x, np.sin(x),label="sin", marker="x", markevery=12, c='k')
line2, = plt.plot(x, np.cos(x),label="cos", marker=".",markersize=1, lw=0, c='k')
line3, = plt.plot(x, np.tan(x),label="tan", ls="-.", c='k')

plt.gca().legend(handler_map={line2: HandlerLine2D(numpoints=8)})

enter image description here

Upvotes: 2

Related Questions