Matplotlib上的Latex未被识别为字符串

2024-09-29 01:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

全部

我试图在Matplotlib上绘制一些数据,并在标题上使用Latex。我以前做过这些,从来没有遇到过这个问题。我使用以下代码来绘制:

plt.subplot(1,2,1)
plt.hist(t_single, bins, rwidth= 0.8, normed= True)
plt.plot(supp, gaussian, 'red')
plt.title(r'Single-selection Estimator ($c_y = $' + str(cy) + ', $c_d = $' + str (cd) + ', $\alpha_0 = $' + str(alpha_0) + ')', fontsize = 16)
plt.legend(['Gaussian', 'Estimator'], loc = 'best', fontsize = 14)
plt.ylabel('Frequency', fontsize = 14)
plt.xlabel('t-statistic', fontsize = 14)

但是,我得到以下错误:

ParseException                            Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/matplotlib/mathtext.py in parse(self, s, fonts_object, fontsize, dpi)
   2515         try:
-> 2516             result = self._expression.parseString(s)
   2517         except ParseBaseException as err:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in parseString(self, instring, parseAll)
   1631                 # catch and re-raise exception from here, clears out pyparsing internal stack trace
-> 1632                 raise exc
   1633         else:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in parseString(self, instring, parseAll)
   1621         try:
-> 1622             loc, tokens = self._parse( instring, 0 )
   1623             if parseAll:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseCache(self, instring, loc, doActions, callPreParse)
   1528                 try:
-> 1529                     value = self._parseNoCache(instring, loc, doActions, callPreParse)
   1530                 except ParseBaseException as pe:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1378                 try:
-> 1379                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1380                 except IndexError:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   3716         if self.expr is not None:
-> 3717             return self.expr._parse( instring, loc, doActions, callPreParse=False )
   3718         else:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseCache(self, instring, loc, doActions, callPreParse)
   1528                 try:
-> 1529                     value = self._parseNoCache(instring, loc, doActions, callPreParse)
   1530                 except ParseBaseException as pe:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1378                 try:
-> 1379                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1380                 except IndexError:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   3394             else:
-> 3395                 loc, exprtokens = e._parse( instring, loc, doActions )
   3396             if exprtokens or exprtokens.haskeys():

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseCache(self, instring, loc, doActions, callPreParse)
   1528                 try:
-> 1529                     value = self._parseNoCache(instring, loc, doActions, callPreParse)
   1530                 except ParseBaseException as pe:

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1382             else:
-> 1383                 loc,tokens = self.parseImpl( instring, preloc, doActions )
   1384 

~/anaconda3/lib/python3.6/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   3182         if loc < len(instring):
-> 3183             raise ParseException(instring, loc, self.errmsg, self)
   3184         elif loc == len(instring):

ParseException: Expected end of text (at char 50), (line:1, col:51)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
~/Google Drive/Mestrado/Tese/Code/Belloni_simulations/sim_plotter.py in <module>()
     59 folder = 'alpha_' + str(alpha_0) + '/'
     60 figname = 'single_vs_double_cy_' + str(cy) + '_cd_' + str(cd) + '_alpha' + str(alpha_0) + '.png'
---> 61 plt.savefig(folder + figname, bbox_inches = 'tight', dpi = 300)
     62 
     63 

~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py in savefig(*args, **kwargs)
    699 def savefig(*args, **kwargs):
    700     fig = gcf()
--> 701     res = fig.savefig(*args, **kwargs)
    702     fig.canvas.draw_idle()   # need this if 'transparent=True' to reset colors
    703     return res

~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py in savefig(self, fname, **kwargs)
   1832             self.set_frameon(frameon)
   1833 
-> 1834         self.canvas.print_figure(fname, **kwargs)
   1835 
   1836         if frameon:

~/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2214                     orientation=orientation,
   2215                     dryrun=True,
-> 2216                     **kwargs)
   2217                 renderer = self.figure._cachedRenderer
   2218                 bbox_inches = self.figure.get_tightbbox(renderer)

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    505 
    506     def print_png(self, filename_or_obj, *args, **kwargs):
--> 507         FigureCanvasAgg.draw(self)
    508         renderer = self.get_renderer()
    509         original_dpi = renderer.dpi

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    428             # if toolbar:
    429             #     toolbar.set_cursor(cursors.WAIT)
--> 430             self.figure.draw(self.renderer)
    431         finally:
    432             # if toolbar:

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1297 
   1298             mimage._draw_list_compositing_images(
-> 1299                 renderer, self, artists, self.suppressComposite)
   1300 
   1301             renderer.close_group('figure')

~/anaconda3/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

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2435             renderer.stop_rasterizing()
   2436 
-> 2437         mimage._draw_list_compositing_images(renderer, self, artists)
   2438 
   2439         renderer.close_group('axes')

~/anaconda3/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

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/text.py in draw(self, renderer)
    713 
    714         with _wrap_text(self) as textobj:
--> 715             bbox, info, descent = textobj._get_layout(renderer)
    716             trans = textobj.get_transform()
    717 

~/anaconda3/lib/python3.6/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    315                 w, h, d = renderer.get_text_width_height_descent(clean_line,
    316                                                         self._fontproperties,
--> 317                                                         ismath=ismath)
    318             else:
    319                 w, h, d = 0, 0, 0

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    229         if ismath:
    230             ox, oy, width, height, descent, fonts, used_characters = \
--> 231                 self.mathtext_parser.parse(s, self.dpi, prop)
    232             return width, height, descent
    233 

~/anaconda3/lib/python3.6/site-packages/matplotlib/mathtext.py in parse(self, s, dpi, prop)
   3301             self.__class__._parser = Parser()
   3302 
-> 3303         box = self._parser.parse(s, font_output, fontsize, dpi)
   3304         font_output.set_canvas_size(box.width, box.height, box.depth)
   3305         result = font_output.get_results(box)

~/anaconda3/lib/python3.6/site-packages/matplotlib/mathtext.py in parse(self, s, fonts_object, fontsize, dpi)
   2520                         err.line,
   2521                         " " * (err.column - 1) + "^",
-> 2522                         six.text_type(err)]))
   2523         self._state_stack = None
   2524         self._em_width_cache = {}

ValueError: 
Single-selection Estimator ($c_y = $1, $c_d = $1, $lpha_0 = $0.5)
                                                  ^
Expected end of text (at char 50), (line:1, col:51)

我使用的是visualstudio代码,实际上,\a''' part on\alpha\u 0'''以不同的方式突出显示,因为它将它识别为另一个命令,而不是将其解释为乳胶命令的字符串的一部分。你知道吗

有解决办法吗?乳胶将使我的标题真的整洁!你知道吗

提前多谢了!你知道吗


Tags: inpyselfifmatplotliblibpackagessite
2条回答

\a是一个ASCII铃声。您可以只使用原始字符串,这样Python就不会以这种特殊的方式来解释它:

... + r', $\alpha_0 = $' + ...

在matplotlib中连接包含latex的字符串时,仅将'r'放在第一个字符串的开头是不够的,它需要在连接的每个字符串之前(例如,包含'$c_d = $'的latex命令的字符串不需要这样做)。改变

plt.title(r'Single-selection Estimator ($c_y = $' + str(cy) + ', $c_d = $' + 
str (cd) + ', $\alpha_0 = $' + str(alpha_0) + ')', fontsize = 16)

plt.title(r'Single-selection Estimator ($c_y = $' + str(cy) + ', $c_d = $' + 
str (cd) + r', $\alpha_0 = $' + str(alpha_0) + ')', fontsize = 16)

这个问题应该得到解决。这是因为只有第一个字符串被解释为raw,所有连接的后续字符串都没有被解释为raw。你知道吗

相关问题 更多 >