Created
April 7, 2021 13:30
-
-
Save vaclavcadek/197b8b9f82ba0452a7e6ba4b19b699ab to your computer and use it in GitHub Desktop.
How to write SVG file instead of broken (blurry) matplotlib.
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
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