Matplotlib 通过函数设置图例项属性,例如位置和句柄长度



下面是一个示例图和一个用于设置图例属性的函数:

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)

使用这种方法,我可以设置标签和标题的图例字体大小(使用 .get_texts()、.get_title() ...),设置框架或框架外,...,但是如何通过此功能设置位置?

编辑:我还想通过该函数设置图例句柄长度值。

没有记录的公共 API。

您可以使用未记录的私有属性_loc通过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]

最新更新