Skip to content

Instantly share code, notes, and snippets.

@vaclavcadek
Created April 7, 2021 13:30
Show Gist options
  • Save vaclavcadek/197b8b9f82ba0452a7e6ba4b19b699ab to your computer and use it in GitHub Desktop.
Save vaclavcadek/197b8b9f82ba0452a7e6ba4b19b699ab to your computer and use it in GitHub Desktop.
How to write SVG file instead of broken (blurry) matplotlib.
def svg_write(fig, center=True):
"""
Renders a matplotlib figure object to SVG and embedd it as base64.
Disable center to left-margin align like other objects.
Shamelessly taken from:
https://discuss.streamlit.io/t/display-svg/172
"""
# Save to stringIO instead of file
imgdata = StringIO()
fig.savefig(imgdata, format="svg")
# Retrieve saved string
imgdata.seek(0)
svg_string = imgdata.getvalue()
# Encode as base 64
b64 = base64.b64encode(svg_string.encode("utf-8")).decode("utf-8")
# Add some CSS on top
css_justify = "center" if center else "left"
css = f'<p style="text-align:center; display: flex; justify-content: {css_justify};">'
html = f'{css}<img src="data:image/svg+xml;base64,{b64}"/>'
# Write the HTML
st.write(html, unsafe_allow_html=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment