为 matplotlib 绘图后端设置随机种子

Set random seed for matplotlib plotting backend

我正在使用 matplotlib 生成和保存 SVG 图像,并希望它们尽可能可重现。然而,即使在设置 np.random.seedrandom.seed 之后,SVG 图像中的各种 idxlink:href 值仍然在我的代码 运行 之间变化。

我认为这些差异是由于 matplotlib 用于渲染 SVG 图像的后端造成的。有什么方法可以为此后端设置种子,以便相同的图在代码的两个不同 运行 之间产生相同的输出?

示例代码(运行 这两次,将 plt.savefig 中的名称更改为第二次 运行):

import random
import numpy as np
import matplotlib.pyplot as plt

random.seed(42)
np.random.seed(42)

x, y = np.random.randn(4096), np.random.randn(4096)
heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))

fig, axis = plt.subplots()
plt.savefig("random_1.svg")

比较文件:

diff random_1.svg random_2.svg | head
35c35
< " id="md3b71b67b7" style="stroke:#000000;stroke-width:0.8;"/>
---
> " id="m7ee1b067d8" style="stroke:#000000;stroke-width:0.8;"/>
38c38
<        <use style="stroke:#000000;stroke-width:0.8;" x="57.6" xlink:href="#md3b71b67b7" y="307.584"/>
---
>        <use style="stroke:#000000;stroke-width:0.8;" x="57.6" xlink:href="#m7ee1b067d8" y="307.584"/>
82c82
<        <use style="stroke:#000000;stroke-width:0.8;" x="129.024" xlink:href="#md3b71b67b7" y="307.584"/>

matplotlib's rcParams 中有一个选项 svg.hashsalt,似乎正是用于此目的:

# svg backend params
#svg.image_inline : True       # write raster image data directly into the svg file
#svg.fonttype : 'path'         # How to handle SVG fonts:
#    'none': Assume fonts are installed on the machine where the SVG will be viewed.
#    'path': Embed characters as paths -- supported by most SVG renderers
#    'svgfont': Embed characters as SVG fonts -- supported only by Chrome,
#               Opera and Safari
svg.hashsalt : None           # if not None, use this string as hash salt
                              # instead of uuid4

以下代码生成两个完全相同的文件,一直到 XML ids

import numpy             as np
import matplotlib        as mpl
import matplotlib.pyplot as plt

mpl.rcParams['svg.hashsalt'] = 42
np.random.seed(42)

x, y = np.random.randn(4096), np.random.randn(4096)

fig, ax = plt.subplots()
ax.hist(x)

for i in [1,2]:
    plt.savefig("random_{}.svg".format(i))