user3737702 user3737702 - 3 months ago 37
Python Question

How to align annotation text and legend in matplotlib?

My current plot has one problem on alignment.
Below is my plot
enter image description here

What I want is to align align annotation text and legend as shown below
enter image description here

Is there any way to achieve this?

Below is my plot code.

from pylab import *
import re
matplotlib.rc('xtick', labelsize=16)
matplotlib.rc('ytick', labelsize=16)
plt.rcParams['font.size'] = 16
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16
plt.rcParams['legend.fontsize'] = 16

fig, ax = plt.subplots(figsize=(5,4))
x = array([2.2,4.4])
a = array([1,2])
b = array([1,2])
c = array([1,2])
total_width, n = 1, 3
width = total_width / n
x = x - width*1.5


plt.xticks(xmarks), a, width=width, color='r',alpha=0.5,label='0%') + width, b, width=width, color='b',alpha=0.5,label='60%') + 2 * width, c, width=width,color='g', alpha=0.5,label='100%')

extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
leg=ax.legend([extra, xx, xy,xz], ("IOTs replacement\nwith FAC", "0%", "60%",'100%'),loc='upper left')


Answer Source

Best to use the title argument for this:

leg = ax.legend([xx, xy,xz], 
                ("0%", "60%",'100%'),
                title="IOTs replacement\nwith FAC",
                loc='upper left')

enter image description here

Looks like you need to do some manual adjustments to the position of the legend and the title:

leg = ax.legend([xx, xy,xz], 
                ("0%", "60%",'100%'),
                title="IOTs replacement\nwith FAC",
                loc=(-0.035, 0.48))
leg.get_title().set_position((18, 0))

enter image description here