Jupyter 5、Python 3.6 和 Latex

Jupyter 5, Python 3.6, and Latex

我想使用 Jupyter notebook 来记录我的研究结果。以前,我用过 Python 2.7 和 Jupyter 4 的笔记本,没有任何问题。我最近一直在尝试使用 Anaconda 提供的 Jupyter 5 和 Python 3.6。但是,当我尝试显示热图时,收到错误消息。

用简单的折线图编辑 # -- 编码:utf-8 -- %matplotlib 内联

from future.builtins import *
from future.utils import (viewitems, viewkeys, viewvalues)

import sys
from os import (environ, path)
from collections import OrderedDict

# Numpy and related libraries
import numpy as np
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import (linalg, stats)
from matplotlib import (cm, colors, ticker)
from mpl_toolkits import axes_grid1

from IPython.display import (display, )

# Display full list of DataFrame
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
pd.set_option("display.notebook_repr_html",True)

# Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)
pd.set_option("precision", 2)

# This sets reasonable defaults for font size for
# a figure that will go in a paper
sns.set_context("paper")

# Set the font to be serif, rather than sans
sns.set(font='serif')

# Make the background white, and specify the
# specific font family
sns.set_style("white",
              {
                  "font.family": "serif",
                  "font.serif": ["Times New Roman", "Palatino", "serif"],
                  "font.sans-serif": ["Arial", "Helvetica"],
                  "font.monospace": ["Courier New", "Courier"]
              })
sns.set_style("ticks")
models = ("calpha", "caside", "ncsc", "polar")

# Simple test case
data = np.random.random(10)
data = pd.Series(data=data, dtype=np.float)

fig, ax = plt.subplots()
data.plot(ax=ax, title="Linear randomness", kind="line", use_index=True)
ax.set_xlabel(r"Time (${\mu}$s)")
ax.set_ylabel("r.m.s.d. (Å)")
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.1))
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.0f}"))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
ax.grid()
fig.tight_layout()

但是,我收到以下错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-727fbc0d285c> in <module>()
     10 ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
     11 ax.grid()
---> 12 fig.tight_layout()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/figure.py in tight_layout(self, renderer, pad, h_pad, w_pad, rect)
   2005         kwargs = get_tight_layout_figure(
   2006             self, self.axes, subplotspec_list, renderer,
-> 2007             pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
   2008         self.subplots_adjust(**kwargs)
   2009 

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad, h_pad, w_pad, rect)
    349                                      subplot_list=subplot_list,
    350                                      ax_bbox_list=ax_bbox_list,
--> 351                                      pad=pad, h_pad=h_pad, w_pad=w_pad)
    352 
    353     if rect is not None:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in auto_adjust_subplotpars(fig, renderer, nrows_ncols, num1num2_list, subplot_list, ax_bbox_list, pad, h_pad, w_pad, rect)
    127             continue
    128 
--> 129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
    130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in <listcomp>(.0)
    128 
    129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
--> 130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,
    132                                      fig.transFigure.inverted())

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/axes/_base.py in get_tightbbox(self, renderer, call_axes_locator)
   3952 
   3953         if self.title.get_visible():
-> 3954             bb.append(self.title.get_window_extent(renderer))
   3955         if self._left_title.get_visible():
   3956             bb.append(self._left_title.get_window_extent(renderer))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    968             raise RuntimeError('Cannot get window extent w/o renderer')
    969 
--> 970         bbox, info, descent = self._get_layout(self._renderer)
    971         x, y = self.get_unitless_position()
    972         x, y = self.get_transform().transform_point((x, y))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    352         tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp',
    353                                                          self._fontproperties,
--> 354                                                          ismath=False)
    355         offsety = (lp_h - lp_bl) * self._linespacing
    356 

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    224             fontsize = prop.get_size_in_points()
    225             w, h, d = texmanager.get_text_width_height_descent(
--> 226                 s, fontsize, renderer=self)
    227             return w, h, d
    228 

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    602             dvifile = self.make_dvi(tex, fontsize)
    603             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
--> 604                 page = next(iter(dvi))
    605             # A total height (including the descent) needs to be returned.
    606             return page.width, page.height + page.descent, page.descent

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in __iter__(self)
    247         """
    248         while True:
--> 249             have_page = self._read()
    250             if have_page:
    251                 yield self._output()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _read(self)
    308         while True:
    309             byte = ord(self.file.read(1)[0])
--> 310             self._dtable[byte](self, byte)
    311             if byte == 140:                         # end of page
    312                 return True

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in wrapper(self, byte)
    164             if state is not None and self.state != state:
    165                 raise ValueError("state precondition failed")
--> 166             return method(self, *[f(self, byte-min) for f in get_args])
    167         if max is None:
    168             table[min] = wrapper

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def(self, k, c, s, d, a, l)
    455     @dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
    456     def _fnt_def(self, k, c, s, d, a, l):
--> 457         self._fnt_def_real(k, c, s, d, a, l)
    458 
    459     def _fnt_def_real(self, k, c, s, d, a, l):

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def_real(self, k, c, s, d, a, l)
    460         n = self.file.read(a + l)
    461         fontname = n[-l:].decode('ascii')
--> 462         tfm = _tfmfile(fontname)
    463         if tfm is None:
    464             if six.PY2:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _tfmfile(texname)
   1074 
   1075 def _tfmfile(texname):
-> 1076     return _fontfile(texname, Tfm, '.tfm', _tfmcache)
   1077 
   1078 

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fontfile(texname, class_, suffix, cache)
   1063         pass
   1064 
-> 1065     filename = find_tex_file(texname + suffix)
   1066     if filename:
   1067         result = class_(filename)

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in find_tex_file(filename, format)
   1043     # https://github.com/matplotlib/matplotlib/issues/633
   1044     pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-> 1045                             stderr=subprocess.PIPE)
   1046     result = pipe.communicate()[0].rstrip()
   1047     matplotlib.verbose.report('find_tex_file result: %s' % result,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/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)
    707                                 c2pread, c2pwrite,
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:
    711             # Cleanup if the child failed starting.

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/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)
   1342                         if errno_num == errno.ENOENT:
   1343                             err_msg += ': ' + repr(err_filename)
-> 1344                     raise child_exception_type(errno_num, err_msg, err_filename)
   1345                 raise child_exception_type(err_msg)
   1346 

FileNotFoundError: [Errno 2] No such file or directory: 'kpsewhich': 'kpsewhich'

我知道 Latex 是使用 mathjax 显示的,但是 anaconda(和 pip,就此而言)在 Python 3.6 中不可用。我什至尝试使用 Python 2.7 的不同内核,但没有成功。如上所述,我之前在 Python 2.7.

中成功使用了旧版本的 Jupyter

任何帮助将不胜感激。

因此,经过大量搜索和修改,问题出在以下几行:

# Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)

显然,在最新版本的Jupyter中不再需要上述参数。删除这些行后,我的图形正确显示并带有适当的 Latex 名称。