Matplotlib将带有url的图形保存为svg导致错误



我正在尝试创建一个条形图,其中每个条形图也链接到一个url。

然而,当我试图将该图保存为svg时,我会收到来自matplotlib的backends_svg.py.的错误AttributeError: 'list' object has no attribute 'replace'

如果没有url,它可以正常工作。使用gid而不是url,行为与相同

MWE:

fig, ax = plt.subplots()
ax.bar(["A","B"], height=[10, 4], url=["https://en.wikipedia.org/wiki/Main_Page", "https://www.google.com/"])
fig.savefig(filename, format="svg")

关于如何修复它,有什么建议吗?

ax.bar的文档声明url必须是字符串,但您使用列表…

为什么在调用ax.bar时使用列表而不是字符串时不引发异常?

ax.bar(["A","B"], [10, 4], url=["https://en.wikipedia.org", "https://www.google.com/"])

因为Matplotlib不键入检查指定给url的表达式。只有当SVG后端尝试使用url的值时,才会引发异常,特别是后端假设它正在处理字符串并使用字符串方法,但您的值是一个列表,没有所需的方法,因此为AttributeError: 'list' object has no attribute 'replace'

当Matplotlib尝试使用url的值时,您可以做些什么来避免出现问题?

  • 如果要将链接与条形图整体关联,则必须使用单个字符串。

  • 如果要将链接关联到图形中的每个条形图可以做如下

    ...
    bars = plt.bar((1, 2), (3, 4))
    for bar, url in zip(bars, ["https://en.wikipedia.org", "https://www.google.com/"]):
    bar.set_url(url)
    ...
    

当然,没有什么能阻止你将链接与条形图和每个条形图关联起来,但

bars = plt.bar((1, 2, 3), (3, 4, 5), url='https://www.google.com/0')
for n, bar in enumerate(bars, 1): bar.set_url('https://www.google.com/%d'%n)
plt.savefig('delenda.est', format='svg')

正如您所看到的,只有与条形图相关的链接保存在SVG文件中:

$ grep google delenda.est 
<a xlink:href="https://www.google.com/1">
<a xlink:href="https://www.google.com/2">
<a xlink:href="https://www.google.com/3">
$ 

最新更新