from matplotlib.backends.backend_svg import RendererSVG
from matplotlib.font_manager import FontProperties
from io import StringIO
from IPython.display import display_htmlWe use matplotlib’s mathtext system and SVG backend to generate an SVG rendering of LaTeX code.
fp = FontProperties()
s = r"$D^{\ast\ast}\ell\nu$"
# get bounding box of rendered text
r = RendererSVG(0, 0, StringIO())
w, h, _ = r.get_text_width_height_descent(s, fp, ismath=True)
with StringIO() as f:
# render LaTeX as path
r = RendererSVG(w, h, f)
r.draw_text(r.new_gc(), 0, h, s, fp, angle=0, ismath=True)
f.seek(0)
svg_code = f.read()
display_html(svg_code, raw=True)We can insert the SVG image into HTML layouts, for example, into an HTML table.
display_html(f"""
<html>
<body>
<table>
<tr>
<td> {svg_code} </td> <td> foo </td>
</tr>
<tr>
<td> bar </td> <td> baz </td>
</tr>
</table>
</body>
</html>
""", raw=True)| foo | |
| bar | baz |