我知道这个问题有几个答案,但没有一个能让我满意,因为它们都包含 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'
)
)
这很好用,但是任何将源更改为本地镜像的尝试都会失败。该文档甚至没有提供非网址图像源的选项。
我确实尝试了本地网址 - 但失败了:
source=r'file:///tmp/bla.png',
还有
source=r'file:///tmp/bla.svg',
我也尝试过使用 this answer - using base64 encoding :
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)
...
但这也失败了,即使我测试了输出 base64,它是一个图像!
我怎样才能让它工作?
最佳答案
对于本地文件,您可以使用 pillow (或类似的)读取文件,然后将其用作 plotly 的源。
from PIL import Image
pyLogo = Image.open("python-logo.png")
在我的例子中,我的 python-logo.png
与我的笔记本在同一个文件夹中。
完整示例(改编自 here):
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()
关于python - 如何将本地镜像(svg/png)添加到绘图布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66150459/