'How to add a local image (svg / png) to plotly layout?
I know this question has a few answers, but none satisfy me, because they all include Dash
, and I want to use only basic plotly
.
I have a local image file: /tmp/bla.svg
(and also /tmp/bla.svg
) which I want to appear as a logo on my graph:
This is my the graph code, working with an example from 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'
)
)
This works well, but any attempt to change the source to a local image fails. The doc does not even give an option for a non-url image source.
I did try a local url - but failed:
source=r'file:///tmp/bla.png',
and also
source=r'file:///tmp/bla.svg',
I also tried using 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)
...
but this also fails, even though I tested the output base64, and it is an image!
How can I make it work?
Solution 1:[1]
For a local file you can use pillow (or similar) to read the file and then use that as the source for plotly.
from PIL import Image
pyLogo = Image.open("python-logo.png")
In my case I have python-logo.png
in the same folder as my notebook.
Full example (adapted from 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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jayveesea |