Last active
May 22, 2024 18:01
-
-
Save treuille/16d8173db45969cfec12adbb56118f87 to your computer and use it in GitHub Desktop.
Workaround: Rendering LaTeX in Streamlit
This file contains 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 streamlit as st | |
from io import BytesIO | |
import matplotlib.pyplot as plt | |
def render_latex(formula, fontsize=12, dpi=300): | |
"""Renders LaTeX formula into Streamlit.""" | |
fig = plt.figure() | |
text = fig.text(0, 0, '$%s$' % formula, fontsize=fontsize) | |
fig.savefig(BytesIO(), dpi=dpi) # triggers rendering | |
bbox = text.get_window_extent() | |
width, height = bbox.size / float(dpi) + 0.05 | |
fig.set_size_inches((width, height)) | |
dy = (bbox.ymin / float(dpi)) / height | |
text.set_position((0, -dy)) | |
buffer = BytesIO() | |
fig.savefig(buffer, dpi=dpi, format='jpg') | |
plt.close(fig) | |
st.image(buffer) | |
if __name__ == '__main__': | |
# Demonstrate the use of render_latex(). | |
formula = st.text_input('Formula', r'\alpha^2 > 2\beta') | |
render_latex(formula) |
Note: We now also have a feature request to add latex support to Streamlit's markdown renderer.
Forgot to say that I adapted this code from this gist.
Update
As of v0.50, Streamlit natively supports latex!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To try this out, run:
This has been tested in Python 3.6.3 with both
streamlit==0.47.3
andmatplotlib==3.1.1
installed.