Home > Net >  How to specify space between matplotlib legend markers
How to specify space between matplotlib legend markers

Time:04-12

I am looking through the matplotlib api and can't seem to find a way to change the space between legend markers. I came across a way to change the space between a marker and its respective handle with handletextpad, but I want to change the space between each marker.

Ideally, I'd like to have the markers touching eachother with the labels above (or on top of) the markers.

My legend:

enter image description here

What I am trying to model:

enter image description here

Is there a way to do this?

CodePudding user response:

I am not sure if this matches your expectations. We have used the standard features to create a graph that is similar to your objectives. Since the code and data are unknown to me, I customized the example in the official reference to create it, using handletextpad and columnspacing, and since the numbers are in font units, I achieved this with a negative value.

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(19680801)

fig, ax = plt.subplots(figsize=(8,8))
for color in ['tab:blue', 'tab:orange', 'tab:green']:
    n = 750
    x, y = np.random.rand(2, n)
    scale = 200.0 * np.random.rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color.split(':')[1][0],
               alpha=0.5, edgecolors='none')
    
handlers, labels = ax.get_legend_handles_labels()
print(labels)

ax.legend(handletextpad=-1.2, columnspacing=-0.5, ncol=3,loc="upper left", bbox_to_anchor=(0.75, 1.08))
ax.grid(True)

plt.show()

enter image description here

  • Related