我正在使用 matplotlib
生成和保存 SVG 图像,并希望它们尽可能可重现。然而,即使在设置了 np.random.seed
和 random.seed
之后,各种 id
和 xlink:href
SVG 图像中的值在我的代码运行之间仍然会发生变化。
我假设这些差异是由于 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))
关于python - 为 matplotlib 绘图后端设置随机种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48107855/