如何将本地图像(svg / png)添加到绘图布局?

CIs*_*ies 6 python svg plotly

我知道这个问题有几个答案,但没有一个让我满意,因为它们都包括Dash,而我只想使用基本的plotly

我有一个本地图像文件:(/tmp/bla.svg还有/tmp/bla.svg)我想将其显示为图形上的徽标:

这是我的图形代码,使用以下示例plotly

    fig.add_layout_image(
        dict(
            source='https://raw.githubusercontent.com/cldougl/plot_images/add_r_img/vox.png',
            xref='paper', yref='paper',
            x=1, y=1.05,
            sizex=0.1, sizey=0.1,
            xanchor='center', yanchor='bottom'
        )
    )
Run Code Online (Sandbox Code Playgroud)

这很有效,但是任何将源更改为本地图像的尝试都会失败。该文档甚至没有提供非 url 图像源的选项。

我确实尝试了本地网址 - 但失败了:

source=r'file:///tmp/bla.png',
Run Code Online (Sandbox Code Playgroud)

并且

source=r'file:///tmp/bla.svg',
Run Code Online (Sandbox Code Playgroud)

我也尝试使用这个答案 - 使用 base64 编码

def _get_image(path):
    with open(path, 'rb') as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode()
    encoded_img = f'data:image/png;base64,{encoded_string}'
    return encoded_img
...
source=_get_image(path)
...
Run Code Online (Sandbox Code Playgroud)

但这也失败了,即使我测试了输出base64,它是一个图像!

我怎样才能让它发挥作用?

jay*_*sea 13

对于本地文件,您可以使用pillow(或类似的)来读取文件,然后将其用作plotly 的源。

from PIL import Image
pyLogo = Image.open("python-logo.png")
Run Code Online (Sandbox Code Playgroud)

就我而言,我与python-logo.png笔记本位于同一文件夹中。

完整示例(改编自此处):

import plotly.graph_objects as go
import plotly.io as pio
from PIL import Image

# to render in jupyterlab
pio.renderers.default = "plotly_mimetype"

# Create figure
fig = go.Figure()

pyLogo = Image.open("python-logo.png")

# Add trace
fig.add_trace(
    go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1])
)

fig.add_layout_image(
        dict(
            source=pyLogo,
            xref="x",
            yref="y",
            x=0,
            y=3,
            sizex=2,
            sizey=2,
            sizing="stretch",
            opacity=0.5,
            layer="below")
)

fig.show()
Run Code Online (Sandbox Code Playgroud)