Last active
July 17, 2020 02:08
-
-
Save xhluca/c1b49a1a96f3227df4bda63be8b341de to your computer and use it in GitHub Desktop.
A simple function for converting a SVG file to plotly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import xml | |
import plotly.graph_objects as go | |
def svg_to_fig(svg_bytes, title=None, plot_bgcolor='white', x_lock=False, y_lock=False): | |
svg_enc = base64.b64encode(svg_bytes) | |
svg = f'data:image/svg+xml;base64, {svg_enc.decode()}' | |
# Get the width and height | |
xml_tree = xml.etree.ElementTree.fromstring(svg_bytes.decode()) | |
img_width = int(xml_tree.attrib['width'].strip('pt')) | |
img_height = int(xml_tree.attrib['height'].strip('pt')) | |
fig = go.Figure() | |
# Add invisible scatter trace. | |
# This trace is added to help the autoresize logic work. | |
fig.add_trace( | |
go.Scatter( | |
x=[0, img_width], | |
y=[img_height, 0], | |
mode="markers", | |
marker_opacity=0, | |
hoverinfo="none", | |
) | |
) | |
fig.add_layout_image( | |
dict( | |
source=svg, | |
x=0, | |
y=0, | |
xref="x", | |
yref="y", | |
sizex=img_width, | |
sizey=img_height, | |
opacity=1, | |
layer="below", | |
) | |
) | |
# Adapt axes to the right width and height, lock aspect ratio | |
fig.update_xaxes( | |
showgrid=False, | |
visible=False, | |
range=[0, img_width] | |
) | |
fig.update_yaxes( | |
showgrid=False, | |
visible=False, | |
range=[img_height, 0], | |
) | |
if x_lock is True: | |
fig.update_xaxes(constrain='domain') | |
if y_lock is True: | |
fig.update_yaxes( | |
scaleanchor="x", | |
scaleratio=1 | |
) | |
fig.update_layout(plot_bgcolor=plot_bgcolor) | |
if title: | |
fig.update_layout(title=title) | |
return fig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment