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

8
我正在使用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"/>
1个回答

11

Matplotlib的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))

2
请注意,hashsalt实际上应该是一个字符串(请参见引用的文档和此处的用法:https://github.com/matplotlib/matplotlib/blob/ec8e119235b2d4e750514c1cc8d6192f5465aa9c/lib/matplotlib/testing/__init__.py#L28)matplotlib会自动将其转换为字符串,详见 https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/rcsetup.py - Gus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接