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

标签 python matplotlib

  • 我想使用 matplotlibrc 文件定义标准 matplotlib 样式,并将图例放在图之外。这可以在绘图代码中使用 bbox_to_anchor 来实现,但这不是已知的 rcparam。还有其他选择吗?

  • 是否可以使用 matplotlibrc 让所有绘图标题都以大写字母显示?

最佳答案

简短的回答是,这些东西都不能在 rcParams 中设置。您可以通过将元组作为 loc 参数传递给 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')

结果:

Plot with dark background from rcParam stylesheet, side legend from decorator

如果我需要绘制到特定的轴而不是使用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()

two-axes plot with capitalized title and side legend

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

也许可以修饰 Axes 类本身,以便每个实例都具有修饰的绘图函数?

关于python - 是否可以将 bbox_to_anchor 放入 matplotlibrc 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70834709/

相关文章:

python - 如何在python中找到给定范围内给定函数的最大值?

python - 自定义属性行为

python - matplotlib close 不关闭窗口

python文件读取 "int too large to convert to c long"

python - Google Python API 尝试导入已弃用的 oauth2client.contrib.multistore_file

python - Matplotlib - 如何为具有对数刻度的线图设置颜色条

python - 如何让matplotlib/pcolor显示数据的最后一行和最后一列

python - 如何增加 Matplotlib 图的大小?

python - matplotlib 数据的 cx_freeze 错误

python - matplotlib中如何设置千位分隔符为单引号?