Afshin Oroojlooy
Afshin Oroojlooy

Reputation: 1434

matplotlib legend bars and texts are not aligned

I use matplotlib in python2.7 to get a figure with multiple trajectories. I am getting this figure as the output of my code: enter image description here However, as you see the title of each trajectory is not aligned with the corresponding color line. I played with the options of legend, but did not figure out the solution.

Do you have any idea?

Here is my code:

import numpy as np
import matplotlib.pyplot as plt

liste = range(1,13)
labels = ['3-3','3-4','3-5','3-6','4-3','4-4',
          '4-5','4-6','5-3','5-4','5-5','5-6',
          '6-3','6-4','6-5','6-6']

plt.figure(1)
plt.subplot(2,1,1)

for cnt, j in enumerate(labels):    
    a1 = range(100) # iter
    a2 = np.random.randint(10,size=[100]) # dnn
    a3 = np.ones((100)) # optimal

    if cnt == 0:
        plt.plot(a1,a3,label='BS', color='blue')
        plt.plot(a1, np.divide(a3,a3), color='blue')

    title_font = {'size':'11', 'color':'black', 'weight':'normal',
               'verticalalignment':'bottom'}

    plt.plot(a1,a2,label=j, color='red')


plt.xlabel('episode')
plt.ylabel('cost')
plt.grid(True)

lgd=plt.legend(bbox_to_anchor=(0., 1.0, 1.0, 0.102), 
                loc=3, ncol=len(liste), mode="expand", borderaxespad=0.)

plt.show()

Upvotes: 0

Views: 392

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

The legend handles and labels do not fit into the legend box. You may see that when removing the mode="expand" label.

To get the legend entries take less space, use the handlelength, handletextpad and the columnspacing and play with the parameters until they fit. If that would still not be the case, using less columns is necessary. Set the ncols to a lower number. E.g. with the following

lgd=plt.legend(bbox_to_anchor=(0., 1.02, 1.0, 0.102),
               handlelength=0.9, handletextpad=0.3,columnspacing=0.7,
               loc=3, ncol=9, mode="expand", borderaxespad=0.)

one would get an image with all legend entries fitting

enter image description here

Upvotes: 2

Related Questions