Home > Software engineering >  How to center Matplotlib text legend
How to center Matplotlib text legend

Time:01-19

I have a plot with a legend. Its title has multiple lines like so

plot with legend

created by this code:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot()
legend = ax.legend(title="Line 1 is short\nLine 2 is slightly longer")
plt.show()

I would like the individual lines of the legend title to be centered. How do I accomplish this?

CodePudding user response:

Adding this will do the job:

legend.get_title().set_multialignment('center')
  •  Tags:  
  • Related