title: How to render a latex matrix by using matplotlib
body: <p>I am trying to render a latex matrix by using matplotlib.</p>
  
  <p>this latex string works well by its own</p>
  
  <pre><code>$\begin{bmatrix}    A_{1,1} &amp; A_{1,2} \\    A_{2,1} &amp; A_{2,2} \\ \end{bmatrix}$
  </code></pre>
  
  <p>which generates a matrix as expected.</p>
  
  <p><a href="https://i.stack.imgur.com/YVr7g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YVr7g.png" alt="enter image description here"></a></p>
  
  <p>mpl works well with simple latex</p>
  
  <pre><code>plt.text(0.6, 0.6, r'$A_{1,1}$',
           fontsize=20)
  plt.show()
  </code></pre>
  
  <p>which produces a plot as expected.</p>
  
  <p><a href="https://i.stack.imgur.com/VuGzn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VuGzn.png" alt="enter image description here"></a></p>
  
  <p>unfortunately, putting them together</p>
  
  <pre><code>plt.text(0.6, 0.6, r'$\begin{bmatrix}    A_{1,1} &amp; A_{1,2} \\    A_{2,1} &amp; A_{2,2} \\ \end{bmatrix}$',
           fontsize=20)
  plt.show()
  </code></pre>
  
  <p>produces this trace</p>
  
  <blockquote>
    <p>--------------------------------------------------------------------------- ParseFatalException                       Traceback (most recent call
    last)
    ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/mathtext.py
    in parse(self, s, fonts_object, fontsize, dpi)    2507         try:
    -> 2508             result = self._expression.parseString(s)    2509         except ParseBaseException as err:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseString(self, instring, parseAll)    1653                 # catch
    and re-raise exception from here, clears out pyparsing internal stack
    trace
    -> 1654                 raise exc    1655         else:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseString(self, instring, parseAll)    1643         try:
    -> 1644             loc, tokens = self._parse( instring, 0 )    1645             if parseAll:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3767         if self.expr
    is not None:
    -> 3768             return self.expr._parse( instring, loc, doActions, callPreParse=False )    3769         else:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3445             else:
    -> 3446                 loc, exprtokens = e._parse( instring, loc, doActions )    3447             if exprtokens or exprtokens.haskeys():</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3969         try:
    -> 3970             return super(ZeroOrMore, self).parseImpl(instring, loc, doActions)    3971         except (ParseException,IndexError):</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3898<br>
    try_not_ender(instring, loc)
    -> 3899         loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False )    3900         try:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3428         # pre-parsed
    the string as part of our And pre-parsing
    -> 3429         loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )    3430         errorStop = False</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1427                 for fn in self.parseAction:
    -> 1428                     tokens = fn( instring, tokensStart, retTokens )    1429                     if tokens is not None:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    wrapper(*args)    1071             try:
    -> 1072                 ret = func(*args[limit[0]:])    1073                 foundArity[0] = True</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/mathtext.py
    in math_string(self, s, loc, toks)    2575     def math_string(self,
    s, loc, toks):
    -> 2576         return self._math_expression.parseString(toks[0][1:-1])    2577 </p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseString(self, instring, parseAll)    1653                 # catch
    and re-raise exception from here, clears out pyparsing internal stack
    trace
    -> 1654                 raise exc    1655         else:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseString(self, instring, parseAll)    1643         try:
    -> 1644             loc, tokens = self._parse( instring, 0 )    1645             if parseAll:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3767         if self.expr
    is not None:
    -> 3768             return self.expr._parse( instring, loc, doActions, callPreParse=False )    3769         else:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3898<br>
    try_not_ender(instring, loc)
    -> 3899         loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False )    3900         try:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3767         if self.expr
    is not None:
    -> 3768             return self.expr._parse( instring, loc, doActions, callPreParse=False )    3769         else:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1401                 try:
    -> 1402                     loc,tokens = self.parseImpl( instring, preloc, doActions )    1403                 except IndexError:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    parseImpl(self, instring, loc, doActions)    3580             try:
    -> 3581                 ret = e._parse( instring, loc, doActions )    3582                 return ret</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseCache(self, instring, loc, doActions, callPreParse)    1550                 try:
    -> 1551                     value = self._parseNoCache(instring, loc, doActions, callPreParse)    1552                 except
    ParseBaseException as pe:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    _parseNoCache(self, instring, loc, doActions, callPreParse)    1427                 for fn in self.parseAction:
    -> 1428                     tokens = fn( instring, tokensStart, retTokens )    1429                     if tokens is not None:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/pyparsing.py in
    wrapper(*args)    1071             try:
    -> 1072                 ret = func(*args[limit[0]:])    1073                 foundArity[0] = True</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/mathtext.py
    in unknown_symbol(self, s, loc, toks)    2667         c = toks[0]
    -> 2668         raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)    2669 </p>
    
    <p>ParseFatalException: Unknown symbol: \begin (at char 0), (line:1,
    col:1)</p>
    
    <p>During handling of the above exception, another exception occurred:</p>
    
    <p>ValueError                                Traceback (most recent call
    last)
    ~/anaconda3/envs/tf11/lib/python3.6/site-packages/IPython/core/formatters.py
    in <strong>call</strong>(self, obj)
        330                 pass
        331             else:
    --> 332                 return printer(obj)
        333             # Finally look for special method names
        334             method = get_real_method(obj, self.print_method)</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/IPython/core/pylabtools.py
    in (fig)
        235 
        236     if 'png' in formats:
    --> 237         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
        238     if 'retina' in formats or 'png2x' in formats:
        239         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/IPython/core/pylabtools.py
    in print_figure(fig, fmt, bbox_inches, **kwargs)
        119 
        120     bytes_io = BytesIO()
    --> 121     fig.canvas.print_figure(bytes_io, **kw)
        122     data = bytes_io.getvalue()
        123     if fmt == 'svg':</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backend_bases.py
    in print_figure(self, filename, dpi, facecolor, edgecolor,
    orientation, format, bbox_inches, **kwargs)    2047<br>
    orientation=orientation,    2048                         dryrun=True,
    -> 2049                         **kwargs)    2050                     renderer = self.figure._cachedRenderer    2051<br>
    bbox_artists = kwargs.pop("bbox_extra_artists", None)</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py
    in print_png(self, filename_or_obj, *args, **kwargs)
        508 
        509         """
    --> 510         FigureCanvasAgg.draw(self)
        511         renderer = self.get_renderer()
        512 </p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py
    in draw(self)
        400         toolbar = self.toolbar
        401         try:
    --> 402             self.figure.draw(self.renderer)
        403             # A GUI class may be need to update a window using this draw, so
        404             # don't forget to call the superclass.</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py
    in draw_wrapper(artist, renderer, *args, **kwargs)
         48                 renderer.start_filter()
         49 
    ---> 50             return draw(artist, renderer, *args, **kwargs)
         51         finally:
         52             if artist.get_agg_filter() is not None:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/figure.py
    in draw(self, renderer)    1650     1651<br>
    mimage._draw_list_compositing_images(
    -> 1652                 renderer, self, artists, self.suppressComposite)    1653     1654<br>
    renderer.close_group('figure')</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/image.py
    in _draw_list_compositing_images(renderer, parent, artists,
    suppress_composite)
        136     if not_composite or not has_images:
        137         for a in artists:
    --> 138             a.draw(renderer)
        139     else:
        140         # Composite any adjacent images together</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py
    in draw_wrapper(artist, renderer, *args, **kwargs)
         48                 renderer.start_filter()
         49 
    ---> 50             return draw(artist, renderer, *args, **kwargs)
         51         finally:
         52             if artist.get_agg_filter() is not None:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axes/_base.py
    in draw(self, renderer, inframe)    2602<br>
    renderer.stop_rasterizing()    2603 
    -> 2604         mimage._draw_list_compositing_images(renderer, self, artists)    2605     2606         renderer.close_group('axes')</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/image.py
    in _draw_list_compositing_images(renderer, parent, artists,
    suppress_composite)
        136     if not_composite or not has_images:
        137         for a in artists:
    --> 138             a.draw(renderer)
        139     else:
        140         # Composite any adjacent images together</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py
    in draw_wrapper(artist, renderer, *args, **kwargs)
         48                 renderer.start_filter()
         49 
    ---> 50             return draw(artist, renderer, *args, **kwargs)
         51         finally:
         52             if artist.get_agg_filter() is not None:</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/text.py
    in draw(self, renderer)
        707 
        708         with _wrap_text(self) as textobj:
    --> 709             bbox, info, descent = textobj._get_layout(renderer)
        710             trans = textobj.get_transform()
        711 </p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/text.py
    in _get_layout(self, renderer)
        311                 w, h, d = renderer.get_text_width_height_descent(clean_line,
        312                                                         self._fontproperties,
    --> 313                                                         ismath=ismath)
        314             else:
        315                 w, h, d = 0, 0, 0</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py
    in get_text_width_height_descent(self, s, prop, ismath)
        212         if ismath:
        213             ox, oy, width, height, descent, fonts, used_characters = \
    --> 214                 self.mathtext_parser.parse(s, self.dpi, prop)
        215             return width, height, descent
        216 </p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/mathtext.py
    in parse(self, s, dpi, prop)    3267<br>
    self.<strong>class</strong>._parser = Parser()    3268 
    -> 3269         box = self._parser.parse(s, font_output, fontsize, dpi)    3270         font_output.set_canvas_size(box.width,
    box.height, box.depth)    3271         return
    font_output.get_results(box)</p>
    
    <p>~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/mathtext.py
    in parse(self, s, fonts_object, fontsize, dpi)    2511<br>
    err.line,    2512                                         " " *
    (err.column - 1) + "^",
    -> 2513                                         str(err)]))    2514         self._state_stack = None    2515         self._em_width_cache = {}</p>
    
    <p>ValueError:  \begin{bmatrix}    A_{1,1} &amp; A_{1,2} \    A_{2,1} &amp;
    A_{2,2} \ \end{bmatrix} ^ Unknown symbol: \begin (at char 0),
    (line:1, col:1)</p>
  </blockquote>