Pablo Reyes
Pablo Reyes

Reputation: 3123

How to fix line size in the legend to match lines in a plot that uses `LineCollection` in matplotlib versions 2.00?

When using LineCollection in newer versions of matplotlib (2.0.0), there is a mismatch of the size of the lines in the plot and the lines of the handle in the legend. Since the lines of the handle are larger than those from the plot, handlelength needs to be used so that the dashes go through a whole cycle, but the problem is that the lines in the legend are still larger. How to make them the same size of the ones on the graph?. See this example:

lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
lc1 = matplotlib.collections.LineCollection(lines1, linestyles="--")
lc2 = matplotlib.collections.LineCollection(lines2, linestyles="-.")
fig, ax = plt.subplots()
ax.add_collection(lc1)
ax.add_collection(lc2)
ax.legend([lc1,lc2],["line1","line2"],handlelength=3)

enter image description here

Alright. The previous plot was made with matplotlib version 2.0.0b4+2415.g6ad368b . Now I have tried using matplotlib version 1.5.3 and there is no mismatch between the lines in the plot and line handle in the legend. So something got wrong (changed) with the newer version of matplotlib.

lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
lc1 = matplotlib.collections.LineCollection(lines1, linestyles="--")
lc2 = matplotlib.collections.LineCollection(lines2, linestyles="-.")
fig, ax = matplotlib.pyplot.subplots()
ax.add_collection(lc1)
ax.add_collection(lc2)
aaa = ax.legend([lc1,lc2],["line1","line2"])

enter image description here

Upvotes: 2

Views: 335

Answers (1)

Stop harming Monica
Stop harming Monica

Reputation: 12618

This happens because the dash patterns now scale with line width but the legend handle associated with a LineCollection doesn't seem to get this right (looks like a bug). You can restore the old behaviour as explained in the link.

classic_dashes = {
    'lines.dotted_pattern': [1, 3],
    'lines.dashdot_pattern': [3, 5, 1, 5],
    'lines.dashed_pattern': [6, 6],
    'lines.scale_dashes': False
}

with plt.rc_context(classic_dashes):
    lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
    lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
    lc1 = matplotlib.collections.LineCollection(lines1, linestyles="--")
    lc2 = matplotlib.collections.LineCollection(lines2, linestyles="-.")
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.add_collection(lc1)
    ax.add_collection(lc2)
    ax.legend([lc1,lc2],["line1","line2"])

enter image description here

Upvotes: 1

Related Questions