【问题标题】:Is it possible to put bbox_to_anchor into a matplotlibrc file?是否可以将 bbox_to_anchor 放入 matplotlibrc 文件中?
【发布时间】:2022-01-24 13:33:46
【问题描述】:
  • 我想使用 matplotlibrc 文件定义标准的 matplotlib 样式,图例在图之外。这可以在绘图代码中使用 bbox_to_anchor,但这不是已知的 rcparam。还有其他选择吗?

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

【问题讨论】:

  • answer here 似乎有助于确定 matplotlibrc 可以控制什么,不能控制什么。不过,我还没有检查 bbox_to_anchor 和大写字母。
  • 如果没有 bbox_to_anchor 的答案是有用的,这个问题可能对不同的标题更有用。 “在情节之外自动绘制一个图例”? “在没有 rcParams 的情况下强制执行绘图样式”?

标签: python matplotlib


【解决方案1】:

简短的回答是这些东西都不能在 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')

结果:

如果我需要绘制特定轴而不是使用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 类本身,以便每个实例都具有装饰的绘图功能?

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2017-12-17
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多