Matplotlib Latex troubles



我使用Jupyter notebook访问python。我在MacBook上遇到了很多问题,所以我删除了mac上的所有python文件,并重新安装了anaconda。一开始,它是工作的,但在完成复杂的任务后,我又开始收到奇怪的错误。这是其中之一。我尝试使用pip, conda c-forge安装乳胶。latex模块是在site-packages中下载的,但是错误是一样的。

# %% load libraries
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# %% aesthetics
plt.style.use('seaborn-bright')
plt.rc('text', usetex=True)
plt.rc('font', family='serif', size=10)
# %% generate fake data
x = np.arange(0, 10, 1)
y0 = np.square(x)
y1 = np.sqrt(x)
y2 = 2 + x
# %% figure
# create figure
fig = plt.figure(figsize=(6, 6))
# parition the figure into 4 subplots with 'gridspec'
gs = gridspec.GridSpec(2, 4, # we want 2 rows, 4 cols
figure=fig, # this gs applies to figure
hspace=0.5, wspace=1, # separation between plots
width_ratios=[1, 1, 1, 1], # ration between the
# first and second column
height_ratios=[1, 1]) # ration between the first ans second row
# add plots
ax0 = fig.add_subplot(gs[0, 0:2]) # this will occupy the first row-first colum
ax1 = fig.add_subplot(gs[0, 2:4]) # and so on and so forth...
ax2 = fig.add_subplot(gs[1, 1:3])
# plot left-top
ax0.plot(x, y0, marker='o', color='green')
ax0.set_xlabel(r'$x$')
ax0.set_ylabel(r'$x^{2}$')
ax0.grid(ls='--')
# plot right-top
ax1.plot(x, y1, marker='s', color='red')
ax1.set_xlabel(r'$x$')
ax1.set_ylabel(r'$sqrt{x}$')
ax1.grid(ls='--')
# plot middle-bottom
ax2.plot(x, y2, marker='d', color='blue')
ax2.set_xlabel(r'$x$')
ax2.set_ylabel(r'$2 + x$')
ax2.grid(ls='--')
# save plot
out_f = os.path.join(os.getcwd(), 'multiple_plots.pdf')
fig.savefig(out_f)
# show plot
plt.show()
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex, cwd)
251         try:
--> 252             report = subprocess.check_output(
253                 command, cwd=cwd if cwd is not None else self.texcache,
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in check_output(timeout, *popenargs, **kwargs)
414 
--> 415     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
416                **kwargs).stdout
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
492 
--> 493     with Popen(*popenargs, **kwargs) as process:
494         try:
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
857 
--> 858             self._execute_child(args, executable, preexec_fn, close_fds,
859                                 pass_fds, cwd, env,
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
1703                         err_msg = os.strerror(errno_num)
-> 1704                     raise child_exception_type(errno_num, err_msg, err_filename)
1705                 raise child_exception_type(err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'latex'
The above exception was the direct cause of the following exception:
RuntimeError                              Traceback (most recent call last)
/var/folders/lp/kfk0rkcj6bj31b_4y46369qr0000gn/T/ipykernel_30630/3384632287.py in <module>
69 # save plot
70 out_f = os.path.join(os.getcwd(), 'multiple_plots.pdf')
---> 71 fig.savefig(out_f)
72 
73 # show plot
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/figure.py in savefig(self, fname, transparent, **kwargs)
3003                 patch.set_edgecolor('none')
3004 
-> 3005         self.canvas.print_figure(fname, **kwargs)
3006 
3007         if transparent:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2253                 # force the figure dpi to 72), so we need to set it again here.
2254                 with cbook._setattr_cm(self.figure, dpi=dpi):
-> 2255                     result = print_method(
2256                         filename,
2257                         facecolor=facecolor,
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backend_bases.py in wrapper(*args, **kwargs)
1667             kwargs.pop(arg)
1668 
-> 1669         return func(*args, **kwargs)
1670 
1671     return wrapper
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/_api/deprecation.py in wrapper(*inner_args, **inner_kwargs)
429                          else deprecation_addendum,
430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
432 
433     return wrapper
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backends/backend_pdf.py in print_pdf(self, filename, dpi, bbox_inches_restore, metadata)
2723                 RendererPdf(file, dpi, height, width),
2724                 bbox_inches_restore=bbox_inches_restore)
-> 2725             self.figure.draw(renderer)
2726             renderer.finalize()
2727             if not isinstance(filename, PdfPages):
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
72     @wraps(draw)
73     def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74         result = draw(artist, renderer, *args, **kwargs)
75         if renderer._rasterizing:
76             renderer.stop_rasterizing()
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
2778 
2779             self.patch.draw(renderer)
-> 2780             mimage._draw_list_compositing_images(
2781                 renderer, self, artists, self.suppressComposite)
2782 
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130     if not_composite or not has_images:
131         for a in artists:
--> 132             a.draw(renderer)
133     else:
134         # Composite any adjacent images together
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/_api/deprecation.py in wrapper(*inner_args, **inner_kwargs)
429                          else deprecation_addendum,
430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
432 
433     return wrapper
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2919             renderer.stop_rasterizing()
2920 
-> 2921         mimage._draw_list_compositing_images(renderer, self, artists)
2922 
2923         renderer.close_group('axes')
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130     if not_composite or not has_images:
131         for a in artists:
--> 132             a.draw(renderer)
133     else:
134         # Composite any adjacent images together
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
1135 
1136         ticks_to_draw = self._update_ticks()
-> 1137         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1138                                                                 renderer)
1139 
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer)
1061     def _get_tick_bboxes(self, ticks, renderer):
1062         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1063         return ([tick.label1.get_window_extent(renderer)
1064                  for tick in ticks if tick.label1.get_visible()],
1065                 [tick.label2.get_window_extent(renderer)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in <listcomp>(.0)
1061     def _get_tick_bboxes(self, ticks, renderer):
1062         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1063         return ([tick.label1.get_window_extent(renderer)
1064                  for tick in ticks if tick.label1.get_visible()],
1065                 [tick.label2.get_window_extent(renderer)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
901 
902         with cbook._setattr_cm(self.figure, dpi=dpi):
--> 903             bbox, info, descent = self._get_layout(self._renderer)
904             x, y = self.get_unitless_position()
905             x, y = self.get_transform().transform((x, y))
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/text.py in _get_layout(self, renderer)
304 
305         # Full vertical extent of font, including ascenders and descenders:
--> 306         _, lp_h, lp_d = renderer.get_text_width_height_descent(
307             "lp", self._fontproperties,
308             ismath="TeX" if self.get_usetex() else False)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backends/_backend_pdf_ps.py in get_text_width_height_descent(self, s, prop, ismath)
86             texmanager = self.get_texmanager()
87             fontsize = prop.get_size_in_points()
---> 88             w, h, d = texmanager.get_text_width_height_descent(
89                 s, fontsize, renderer=self)
90             return w, h, d
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
397         else:
398             # use dviread.
--> 399             dvifile = self.make_dvi(tex, fontsize)
400             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
401                 page, = dvi
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize)
289             # and thus replace() works atomically.
290             with TemporaryDirectory(dir=Path(dvifile).parent) as tmpdir:
--> 291                 self._run_checked_subprocess(
292                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
293                      texfile], tex, cwd=tmpdir)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex, cwd)
254                 stderr=subprocess.STDOUT)
255         except FileNotFoundError as exc:
--> 256             raise RuntimeError(
257                 'Failed to process string with tex because {} could not be '
258                 'found'.format(command[0])) from exc
RuntimeError: Failed to process string with tex because latex could not be found
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex, cwd)
251         try:
--> 252             report = subprocess.check_output(
253                 command, cwd=cwd if cwd is not None else self.texcache,
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in check_output(timeout, *popenargs, **kwargs)
414 
--> 415     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
416                **kwargs).stdout
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
492 
--> 493     with Popen(*popenargs, **kwargs) as process:
494         try:
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
857 
--> 858             self._execute_child(args, executable, preexec_fn, close_fds,
859                                 pass_fds, cwd, env,
~/opt/anaconda3/envs/dataviz/lib/python3.8/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
1703                         err_msg = os.strerror(errno_num)
-> 1704                     raise child_exception_type(errno_num, err_msg, err_filename)
1705                 raise child_exception_type(err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'latex'
The above exception was the direct cause of the following exception:
RuntimeError                              Traceback (most recent call last)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj)
339                 pass
340             else:
--> 341                 return printer(obj)
342             # Finally look for special method names
343             method = get_real_method(obj, self.print_method)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
251 
252     if 'png' in formats:
--> 253         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
254     if 'retina' in formats or 'png2x' in formats:
255         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
135         FigureCanvasBase(fig)
136 
--> 137     fig.canvas.print_figure(bytes_io, **kw)
138     data = bytes_io.getvalue()
139     if fmt == 'svg':
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2228                        else suppress())
2229                 with ctx:
-> 2230                     self.figure.draw(renderer)
2231 
2232             if bbox_inches:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
72     @wraps(draw)
73     def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74         result = draw(artist, renderer, *args, **kwargs)
75         if renderer._rasterizing:
76             renderer.stop_rasterizing()
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
2778 
2779             self.patch.draw(renderer)
-> 2780             mimage._draw_list_compositing_images(
2781                 renderer, self, artists, self.suppressComposite)
2782 
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130     if not_composite or not has_images:
131         for a in artists:
--> 132             a.draw(renderer)
133     else:
134         # Composite any adjacent images together
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/_api/deprecation.py in wrapper(*inner_args, **inner_kwargs)
429                          else deprecation_addendum,
430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
432 
433     return wrapper
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2919             renderer.stop_rasterizing()
2920 
-> 2921         mimage._draw_list_compositing_images(renderer, self, artists)
2922 
2923         renderer.close_group('axes')
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130     if not_composite or not has_images:
131         for a in artists:
--> 132             a.draw(renderer)
133     else:
134         # Composite any adjacent images together
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
49                 renderer.start_filter()
50 
---> 51             return draw(artist, renderer, *args, **kwargs)
52         finally:
53             if artist.get_agg_filter() is not None:
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
1135 
1136         ticks_to_draw = self._update_ticks()
-> 1137         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1138                                                                 renderer)
1139 
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer)
1061     def _get_tick_bboxes(self, ticks, renderer):
1062         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1063         return ([tick.label1.get_window_extent(renderer)
1064                  for tick in ticks if tick.label1.get_visible()],
1065                 [tick.label2.get_window_extent(renderer)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/axis.py in <listcomp>(.0)
1061     def _get_tick_bboxes(self, ticks, renderer):
1062         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1063         return ([tick.label1.get_window_extent(renderer)
1064                  for tick in ticks if tick.label1.get_visible()],
1065                 [tick.label2.get_window_extent(renderer)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
901 
902         with cbook._setattr_cm(self.figure, dpi=dpi):
--> 903             bbox, info, descent = self._get_layout(self._renderer)
904             x, y = self.get_unitless_position()
905             x, y = self.get_transform().transform((x, y))
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/text.py in _get_layout(self, renderer)
304 
305         # Full vertical extent of font, including ascenders and descenders:
--> 306         _, lp_h, lp_d = renderer.get_text_width_height_descent(
307             "lp", self._fontproperties,
308             ismath="TeX" if self.get_usetex() else False)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
227             texmanager = self.get_texmanager()
228             fontsize = prop.get_size_in_points()
--> 229             w, h, d = texmanager.get_text_width_height_descent(
230                 s, fontsize, renderer=self)
231             return w, h, d
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
397         else:
398             # use dviread.
--> 399             dvifile = self.make_dvi(tex, fontsize)
400             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
401                 page, = dvi
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize)
289             # and thus replace() works atomically.
290             with TemporaryDirectory(dir=Path(dvifile).parent) as tmpdir:
--> 291                 self._run_checked_subprocess(
292                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
293                      texfile], tex, cwd=tmpdir)
~/opt/anaconda3/envs/dataviz/lib/python3.8/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex, cwd)
254                 stderr=subprocess.STDOUT)
255         except FileNotFoundError as exc:
--> 256             raise RuntimeError(
257                 'Failed to process string with tex because {} could not be '
258                 'found'.format(command[0])) from exc
RuntimeError: Failed to process string with tex because latex could not be found

下载MacTex解决了这个问题