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

标签 python matplotlib svg random reproducible-research

我正在使用 matplotlib 生成和保存 SVG 图像,并希望它们尽可能可重现。然而,即使在设置了 np.random.seedrandom.seed 之后,各种 idxlink: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/

相关文章:

python - 使用 xlsxwriter 写入单元格时是否可以应用多种单元格格式?

python - Matlibplot 阶跃函数索引 0

python - 在轴之间移动集合

python - Matplotlib 3d 散点动画 - 如何正确更新

javascript - 如何改变节点的不透明度?

python - 从管道中的项目容器打印变量时出错,python scrapy

python - 在 Python 中轻松地从/到 namespace /字典转储变量

python - Django/Python 单元测试 : Let exceptions rise

javascript - SVG - 全局属性和事件列表?

css - 如何在没有 javascript 的情况下使 svg 路径适合某些 px 大小