Skip to content

Instantly share code, notes, and snippets.

@treuille
Last active November 11, 2019 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treuille/16d8173db45969cfec12adbb56118f87 to your computer and use it in GitHub Desktop.
Save treuille/16d8173db45969cfec12adbb56118f87 to your computer and use it in GitHub Desktop.
Workaround: Rendering LaTeX in Streamlit
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)
@treuille
Copy link
Author

treuille commented Oct 7, 2019

To try this out, run:

streamlit run https://gist.githubusercontent.com/treuille/16d8173db45969cfec12adbb56118f87/raw/9e6c678656c4a0b3925c21c73aefa02ea51a4bae/latex.py

This has been tested in Python 3.6.3 with both streamlit==0.47.3 and matplotlib==3.1.1 installed.

@treuille
Copy link
Author

treuille commented Oct 8, 2019

Note: We now also have a feature request to add latex support to Streamlit's markdown renderer.

@treuille
Copy link
Author

treuille commented Oct 8, 2019

Forgot to say that I adapted this code from this gist.

@treuille
Copy link
Author

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