是否可以将 bbox_to_anchor 放入 matplotlibrc 文件中?

Is it possible to put bbox_to_anchor into a matplotlibrc file?

简短的回答是,这些东西都不能在 rcParams 中设置。您可以通过将元组作为 loc 参数传递给 legend() 来获取 sidebar-legend,但是 rcParams 还不能处理元组值。而且我认为 rcParams 不是进行大写等文本修改的正确位置。

您可以将两者与 rcParams 一起放入装饰器中,并拥有装饰版的 pyplot 调用:


import matplotlib.pyplot as plt
import matplotlib as mpl

xs, x2s, ys = [4,1,3,5,2], [1,2,3,4,5], [2,3,1,2,-1]

def house_style(func):
    def sidelegend_wrapper(*args, **kwargs):
        title = kwargs.pop('title', None)
        with plt.style.context('dark_background'): #or your rcParams
            func(*args, **kwargs)
            cf = plt.gcf()
            cf.subplots_adjust(right=0.7)
            cax = plt.gca()
            if title: cax.set_title(title.upper())
            cax.legend(loc=(1.1, .8))
    return(sidelegend_wrapper)

@house_style
def decorated_scatter(*args, **kwargs):
    plt.scatter(*args, **kwargs)

@house_style
def decorated_plot(*args, **kwargs):
    plt.plot(*args, **kwargs)
    
decorated_scatter(xs, ys, label='decorator', title='lowercase')
decorated_plot(x2s, ys, label='also dec')

结果:

如果我需要绘制到特定的轴上而不是使用 pyplot 我会把 刚刚进入装饰器的东西放到函数中:


def our_function(*args, **kwargs):
    title = kwargs.pop('title', None)
    sc_data = kwargs.pop('sc_data', None)
    line_data = kwargs.pop('line_data', None)
    fig, axs= plt.subplots(2)
    fig.subplots_adjust(right=0.7)
    axs[0].scatter(sc_data[0],sc_data[1], **kwargs)
    axs[1].plot(line_data[0], line_data[1], **kwargs)
    if title: fig.suptitle(title.upper())
    axs[0].legend(loc=(1.1,.5))

  

our_function(sc_data = [xs, ys], line_data=[x2s, ys], label='function', title='lowercase\nwell, it was')

plt.show()

那个不调用 rcParams 但可以,就像装饰器一样。

也许可以装饰 Axes class 本身,以便每个实例都装饰绘图函数?