Search code examples
python-3.xmatplotlibplotlegendlegend-properties

Adjust spacing between 2 markers of same line displayed in the legend of matplotlib plot


I am plotting 2 markers of the same line using the following code and I want to adjust the spacing between two markers in the legend.

Code : ref.

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

fig, ax1 = plt.subplots(1, 1)

# First plot: two legend keys for a single entry
p1, = ax1.plot([1, 2], [5, 6], '-', marker='o', markersize=2, mfc="gray", mec="gray")
# `plot` returns a list, but we want the handle - thus the comma on the left
p2, = ax1.plot([1], [5], "-k", marker='s', markersize=10)

p3, = ax1.plot([3, 4], [2, 3], 'o', mfc="white", mec="k")
p4, = ax1.plot([3], [2], '-k', mfc="white", mec="k")

# Assign two of the handles to the same legend entry by putting them in a tuple
# and using a generic handler map (which would be used for any additional
# tuples of handles like (p1, p3)).
handles = [(p1, p2), (p3, p4)]
l = ax1.legend(
    handles, ['data', 'models'],
    handler_map={tuple: HandlerTuple(ndivide=None)},
    handletextpad=1,
    columnspacing=2.0, ncol=1,
)

# plt.savefig("demo.png")
plt.show()

Results in the following plot

enter image description here

I could use handletextpad to adjust the spacing between the marker and text but I am not sure how to adjust the spacing between 2 markers (i.e. please see the position pointed by the red arrow below).

Suggestions will be of great help.


Solution

  • In your handler_map argument, include the pad param:

    l = ax1.legend(
        handles, ['data', 'models'],
        handler_map={tuple: HandlerTuple(ndivide=None, pad=0.0)},
        handletextpad=1,
        columnspacing=2.0, ncol=1,
    )
    

    Reference: https://matplotlib.org/2.1.0/api/legend_api.html#matplotlib.legend_handler.HandlerTuple