user1850133
user1850133

Reputation: 2993

matplotlib set legend items properties such as location and handlelength through function

here is an example plot and a function used to set legend properties:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10), label = 'legend text')
ax.plot(2 * range(10))
leg = plt.legend(title = 'legend here')

def lprop_adjuster(leg, fs = 16)
    ltext = leg.get_texts()
    for item in ltext:
        item.set_fontsize(fs)
    handlelength = 4  #  out of the function I would have passed it within plt.legend()
                      #+ but I didn't find any info about setting it in a way that can be passed 
                      #+ through a function

lprop_adjuster(leg)

Using this method I can set for the legend font size for labels and title (with .get_texts(), .get_title() ...), set on or off the frame, ..., but how to set the location through this function?

edit: I also would like to set legend handlelength value through that function.

Upvotes: 0

Views: 389

Answers (1)

mtd
mtd

Reputation: 2364

There is no documented, public API.

You can use the undocumented, private property _loc to change the legend using the friendly codes in legend.codes:

def lprop_adjuster(leg, fs=16, loc="upper right")
    ltext = leg.get_texts()
    for item in ltext:
        item.set_fontsize(fs)
    leg._loc = leg.codes[loc]

Upvotes: 3

Related Questions