0
votes

I am trying to center some legend entries in matplotlib. This is an en example of the code:

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])

Is it possible to center only the "Cold" description in legend? I have tried r"$\centering Cold$" utilizing the latex expression, but it did not work.

1

1 Answers

0
votes

I could create two different legends by using the add_artist method (otherwise it will just replace the previous legend) that will allow you to set both of them to different location, something like:

from matplotlib.lines import Line2D

custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots()
lines = ax.plot(data)

legend1 = plt.legend(custom_lines[1:], ['Medium', 'Hot'])
legend2 = plt.legend(custom_lines[0], 'Cold', loc=10)

ax.add_artist(legend1)
ax.add_artist(legend2)