Matplotlib添加默认水印

时间:2019-07-11 04:22:35

标签: python matplotlib

我正在使用matplotlib进行工作,公司的政策是在我们制作的每个图上都添加水印。有没有一种方法可以将matplotlib设置为默认执行此操作?

我当前正在将每个Axes对象传递到一个辅助函数中,该函数在左下角添加水印。

import matplotlib.pyplot as plt

def add_watermark(ax):
    ax.text(ax.get_xlim()[0] + 0.1, 
            ax.get_ylim()[0] + 0.1, 
            "<Company Name>", 
            alpha=0.5)

fig, ax = plt.subplots(1, 1)
x = np.fromiter((np.random.uniform() for _ in range(100)), dtype=np.float32)
y = np.fromiter((np.random.uniform() for _ in range(100)), dtype=np.float32)
ax.scatter(x, y)
add_watermark(ax)

我想修改matplotlib的默认行为,这样就不必将每个轴实例都传递给帮助函数。

2 个答案:

答案 0 :(得分:2)

您可以轻松地对默认轴进行子类化和猴子修补。因此,像这样创建文件 matplotlib_company.py

import matplotlib.axes
from matplotlib.offsetbox import AnchoredText

class MyAxes(matplotlib.axes.Axes):
    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)
        ab = AnchoredText("<company name>", loc="lower left", frameon=False,
                          borderpad=0, prop=dict(alpha=0.5))
        ab.set_zorder(0)
        self.add_artist(ab)

matplotlib.axes.Axes = MyAxes

然后将其导入您需要的任何位置。即以下

import matplotlib_company
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()

创建

enter image description here

答案 1 :(得分:1)

我认为,最干净的解决方案是在python的module search path内的单独python脚本(例如称为 .cbold { font-weight: bold } .citalic { font-style: italic } .cunderline { text-decoration: underline; } )中创建“公司图模板”。

您可以将其保存在与实际图相同的文件夹中,例如通过创建companyplots.py文件夹并正确设置/some/path/to/user_modules变量以包含其路径。

在此文件中,收集所有必要的输入并使用默认绘图设置设置功能,例如:

$PYTHONPATH

现在,只需运行以下命令,所有将来的绘图都可以使用该模板:

def companyFigure((rows,cols),(width,height)=(768,576),dpi=72,fig_kwargs={}):
    """
    first, reset mpl style to default, then enforce a new one. 
    This is helpful when the new style does not overwrite *all* attributes 
    """
    style="ggplot" ##<- put your own style file here, if you have one
    mpl.rcParams.update(mpl.rcParamsDefault)
    mpl.style.use(style)

    ## that's your function:
    def add_watermark(ax):
        ax.text(ax.get_xlim()[0] + 0.1, 
                ax.get_ylim()[0] + 0.1, 
                "<Company Name>", 
                alpha=0.5)

    ## create figure with some arguments
    fig,ax=plt.subplots(rows,cols,
            figsize=(width/float(dpi),height/float(dpi)),
            dpi=dpi,
            **fig_kwargs
            )

    ## I'm presuming that you may want to have subplots somewhere down the line;
    ## for the sake of consistency, I'm thus making sure that "ax" is always a dict:
    if rows==1 and cols==1:
        ax={0:ax}

    for a in ax:
        add_watermark(a)

    return fig,ax