Issue
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)
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?
Solution
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)})
Answered By - DavidG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.