【问题标题】:Visualize an SVG using Plotly Python使用 Plotly Python 可视化 SVG
【发布时间】:2021-09-20 16:49:18
【问题描述】:

我正在尝试使用 px.imshow() 在绘图上可视化图像。是否可以为此传入 svg 而不是图像数组?

提前致谢。

【问题讨论】:

  • 你试过什么? - 您可以提供对您的 svg 的访问权限吗?
  • 你的答案在这里:stackoverflow.com/questions/6589358/… cairo 在我的 Mac 上安装有点固执
  • @RobRaymond 我有 3 个简单的 svg,我正在尝试将 plotly imshow 用于动画功能,如 here 所述。所以我可以通过将每个 png 添加到一个 numpy 数组并使用 px.imshow(array) 来使用 pngs 而不是 svgs 来做到这一点,但是由于这个函数是一个 API 端点,我试图将 plotly 返回到一个网站,svgs更可取,因为结果大小更小,而且响应速度快。我已经尝试将 svg 字符串添加到 numpy 数组中,但没有成功。
  • 目前的 svg 就是这个 <svg width="100" height="100"> <circle cx="20" cy="20" r="10" stroke="black" stroke-width="4" fill="red" /> </svg> <svg width="100" height="100"> <circle cx="40" cy="40" r="20" stroke="black" stroke-width="4" fill="red" /> </svg> <svg width="100" height="100"> <circle cx="60" cy="60" r="30" stroke="black" stroke-width="4" fill="red" /> </svg>

标签: python plotly visualization plotly-python


【解决方案1】:
  • 第一步是将 SVG 转换为px.imshow() 所需的格式。使用过 cairosvg(这个库安装起来有点困难)
  • 已经使用了为动画创建帧的方法,也许可以组合图像以便可以从 3D 数组中完成
import numpy as np
import requests, io
import PIL
import cairosvg
import plotly.express as px
import plotly.graph_objects as go

svg_url = "https://logincdn.msauth.net/16.000.28611.4/content/images/microsoft_logo_ee5c8d9fb6248c938fd0dc19370e90bd.svg"
res = requests.get(svg_url)
svgs = [
    '<svg width="100" height="100"><circle cx="20" cy="20" r="10" stroke="black" stroke-width="4" fill="red" /></svg>',
    '<svg width="100" height="100"><circle cx="40" cy="40" r="20" stroke="black" stroke-width="4" fill="red" /></svg>',
    '<svg width="100" height="100"><circle cx="60" cy="60" r="30" stroke="black" stroke-width="4" fill="red" /></svg>',
]

im = [
    PIL.Image.open(io.BytesIO(cairosvg.svg2png(bytestring=svg))).convert("RGBA")
    for svg in svgs
]
go.Figure(data=px.imshow(im[0]).data,
    frames=[go.Frame(data=px.imshow(im).data) for im in im]).update_layout(
    updatemenus=[
        dict(
            type="buttons", buttons=[dict(label="Play", method="animate", args=[None])]
        )
    ]
)

【讨论】:

    猜你喜欢
    • 2022-10-06
    • 2022-06-11
    • 2021-08-18
    • 2015-12-11
    • 2021-09-25
    • 2021-07-20
    • 2022-12-10
    • 2011-02-03
    • 2020-07-07
    相关资源
    最近更新 更多