无法在Jupyter笔记本中绘图

时间:2019-11-27 17:18:25

标签: python pandas jupyter-notebook latex

我有一个jupyter笔记本脚本,一部分看起来像这样:

import pandas as pd

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
matplotlib.style.use('ggplot')
matplotlib.rc('text', usetex=True)
import scipy.stats 


df = pd.read_csv("./titanic-train.csv")

ax = df.Age.hist(bins=20)
ax.set_xlabel("age / years")
ax.set_ylabel("frequency");

之后,我得到一个错误,它将不会打印直方图。 我正在使用随Anaconda安装的Python 3.7.3。 在Windows 10的cmd窗口中打印乳胶,我得到:

  

这是pdfTeX版本3.14159265-2.6-1.40.20(MiKTeX 2.9.7250   64位)

这是我通过运行dataframe.hist()得到的错误消息:

Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x0000029D82BD2950> (for post_execute):
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in _run_checked_subprocess(self, command, tex)
    303                                              cwd=self.texcache,
--> 304                                              stderr=subprocess.STDOUT)
    305         except FileNotFoundError as exc:

~\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 

~\Anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:

~\Anaconda3\lib\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)
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:

~\Anaconda3\lib\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, unused_restore_signals, unused_start_new_session)
   1177                                          os.fspath(cwd) if cwd is not None else None,
-> 1178                                          startupinfo)
   1179             finally:

FileNotFoundError: [WinError 2] The system cannot find the file specified

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

~\Anaconda3\lib\site-packages\matplotlib\_pylab_helpers.py in draw_all(cls, force)
    126         for f_mgr in cls.get_all_fig_managers():
    127             if force or f_mgr.canvas.figure.stale:
--> 128                 f_mgr.canvas.draw_idle()
    129 
    130 atexit.register(Gcf.destroy_all)

~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in draw_idle(self, *args, **kwargs)
   1905         if not self._is_idle_drawing:
   1906             with self._idle_draw_cntx():
-> 1907                 self.draw(*args, **kwargs)
   1908 
   1909     def draw_cursor(self, event):

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    386         self.renderer = self.get_renderer(cleared=True)
    387         with RendererAgg.lock:
--> 388             self.figure.draw(self.renderer)
    389             # A GUI class may be need to update a window using this draw, so
    390             # don't forget to call the superclass.

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1707             self.patch.draw(renderer)
   1708             mimage._draw_list_compositing_images(
-> 1709                 renderer, self, artists, self.suppressComposite)
   1710 
   1711             renderer.close_group('figure')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2643             renderer.stop_rasterizing()
   2644 
-> 2645         mimage._draw_list_compositing_images(renderer, self, artists)
   2646 
   2647         renderer.close_group('axes')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1204         ticks_to_draw = self._update_ticks()
   1205         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
-> 1206                                                                 renderer)
   1207 
   1208         for tick in ticks_to_draw:

~\Anaconda3\lib\site-packages\matplotlib\axis.py in _get_tick_bboxes(self, ticks, renderer)
   1149         """Return lists of bboxes for ticks' label1's and label2's."""
   1150         return ([tick.label1.get_window_extent(renderer)
-> 1151                  for tick in ticks if tick.label1.get_visible()],
   1152                 [tick.label2.get_window_extent(renderer)
   1153                  for tick in ticks if tick.label2.get_visible()])

~\Anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
   1149         """Return lists of bboxes for ticks' label1's and label2's."""
   1150         return ([tick.label1.get_window_extent(renderer)
-> 1151                  for tick in ticks if tick.label1.get_visible()],
   1152                 [tick.label2.get_window_extent(renderer)
   1153                  for tick in ticks if tick.label2.get_visible()])

~\Anaconda3\lib\site-packages\matplotlib\text.py in get_window_extent(self, renderer, dpi)
    888             raise RuntimeError('Cannot get window extent w/o renderer')
    889 
--> 890         bbox, info, descent = self._get_layout(self._renderer)
    891         x, y = self.get_unitless_position()
    892         x, y = self.get_transform().transform_point((x, y))

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
    289         _, lp_h, lp_d = renderer.get_text_width_height_descent(
    290             "lp", self._fontproperties,
--> 291             ismath="TeX" if self.get_usetex() else False)
    292         min_dy = (lp_h - lp_d) * self._linespacing
    293 

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    199             fontsize = prop.get_size_in_points()
    200             w, h, d = texmanager.get_text_width_height_descent(
--> 201                 s, fontsize, renderer=self)
    202             return w, h, d
    203 

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    446         else:
    447             # use dviread. It sometimes returns a wrong descent.
--> 448             dvifile = self.make_dvi(tex, fontsize)
    449             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
    450                 page, = dvi

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in make_dvi(self, tex, fontsize)
    336                 self._run_checked_subprocess(
    337                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
--> 338                      texfile], tex)
    339             for fname in glob.glob(basefile + '*'):
    340                 if not fname.endswith(('dvi', 'tex')):

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in _run_checked_subprocess(self, command, tex)
    306             raise RuntimeError(
    307                 'Failed to process string with tex because {} could not be '
--> 308                 'found'.format(command[0])) from exc
    309         except subprocess.CalledProcessError as exc:
    310             raise RuntimeError(

RuntimeError: Failed to process string with tex because latex could not be found

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in _run_checked_subprocess(self, command, tex)
    303                                              cwd=self.texcache,
--> 304                                              stderr=subprocess.STDOUT)
    305         except FileNotFoundError as exc:

~\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 

~\Anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:

~\Anaconda3\lib\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)
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:

~\Anaconda3\lib\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, unused_restore_signals, unused_start_new_session)
   1177                                          os.fspath(cwd) if cwd is not None else None,
-> 1178                                          startupinfo)
   1179             finally:

FileNotFoundError: [WinError 2] The system cannot find the file specified

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
~\Anaconda3\lib\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)

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2054                         orientation=orientation,
   2055                         dryrun=True,
-> 2056                         **kwargs)
   2057                     renderer = self.figure._cachedRenderer
   2058                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args, **kwargs)
    525 
    526         else:
--> 527             FigureCanvasAgg.draw(self)
    528             renderer = self.get_renderer()
    529             with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    386         self.renderer = self.get_renderer(cleared=True)
    387         with RendererAgg.lock:
--> 388             self.figure.draw(self.renderer)
    389             # A GUI class may be need to update a window using this draw, so
    390             # don't forget to call the superclass.

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1707             self.patch.draw(renderer)
   1708             mimage._draw_list_compositing_images(
-> 1709                 renderer, self, artists, self.suppressComposite)
   1710 
   1711             renderer.close_group('figure')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2643             renderer.stop_rasterizing()
   2644 
-> 2645         mimage._draw_list_compositing_images(renderer, self, artists)
   2646 
   2647         renderer.close_group('axes')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1204         ticks_to_draw = self._update_ticks()
   1205         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
-> 1206                                                                 renderer)
   1207 
   1208         for tick in ticks_to_draw:

~\Anaconda3\lib\site-packages\matplotlib\axis.py in _get_tick_bboxes(self, ticks, renderer)
   1149         """Return lists of bboxes for ticks' label1's and label2's."""
   1150         return ([tick.label1.get_window_extent(renderer)
-> 1151                  for tick in ticks if tick.label1.get_visible()],
   1152                 [tick.label2.get_window_extent(renderer)
   1153                  for tick in ticks if tick.label2.get_visible()])

~\Anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
   1149         """Return lists of bboxes for ticks' label1's and label2's."""
   1150         return ([tick.label1.get_window_extent(renderer)
-> 1151                  for tick in ticks if tick.label1.get_visible()],
   1152                 [tick.label2.get_window_extent(renderer)
   1153                  for tick in ticks if tick.label2.get_visible()])

~\Anaconda3\lib\site-packages\matplotlib\text.py in get_window_extent(self, renderer, dpi)
    888             raise RuntimeError('Cannot get window extent w/o renderer')
    889 
--> 890         bbox, info, descent = self._get_layout(self._renderer)
    891         x, y = self.get_unitless_position()
    892         x, y = self.get_transform().transform_point((x, y))

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
    289         _, lp_h, lp_d = renderer.get_text_width_height_descent(
    290             "lp", self._fontproperties,
--> 291             ismath="TeX" if self.get_usetex() else False)
    292         min_dy = (lp_h - lp_d) * self._linespacing
    293 

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    199             fontsize = prop.get_size_in_points()
    200             w, h, d = texmanager.get_text_width_height_descent(
--> 201                 s, fontsize, renderer=self)
    202             return w, h, d
    203 

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    446         else:
    447             # use dviread. It sometimes returns a wrong descent.
--> 448             dvifile = self.make_dvi(tex, fontsize)
    449             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
    450                 page, = dvi

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in make_dvi(self, tex, fontsize)
    336                 self._run_checked_subprocess(
    337                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
--> 338                      texfile], tex)
    339             for fname in glob.glob(basefile + '*'):
    340                 if not fname.endswith(('dvi', 'tex')):

~\Anaconda3\lib\site-packages\matplotlib\texmanager.py in _run_checked_subprocess(self, command, tex)
    306             raise RuntimeError(
    307                 'Failed to process string with tex because {} could not be '
--> 308                 'found'.format(command[0])) from exc
    309         except subprocess.CalledProcessError as exc:
    310             raise RuntimeError(

RuntimeError: Failed to process string with tex because latex could not be found

<Figure size 432x288 with 1 Axes>

编辑1:

我尝试在运行Windows 10的homePC上运行相同的代码,相同的Python版本和乳胶版本,并且该代码未引发错误,并且按预期绘制了所有内容。 我仍然需要它在我有该问题的笔记本电脑上工作,但是我只想说它出奇地在另一台似乎具有相同设置的PC上运行。

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了解决问题的方法。

首先,我卸载了Anaconda。我还删除了在用户目录.anaconda3中找到的文件夹。 我像平常一样重新安装并运行了我的脚本。之后,我有2个外部窗口从LaTex安装软件包。 (我上次没有得到它们)

但是我也正在运行BitDefender,当我想安装它们时,我的防病毒软件不允许他们下载不安全的软件,但没有提及。 我停用了BitDefender并尝试重现LaTex窗口打开的情况。因此,我让我的脚本再次运行,并且两个窗口再次出现。 我现在已经安装了软件包并进行了matplot,其他所有内容现在都可以正常打印。

TL; DR: 对于遇到相同问题的任何人,可能是您的防病毒软件阻止jupyter安装所需的软件包,因此您没有需要绘制的文件。