简体   繁体   English

如何为matplotlib设置latex路径

[英]How to set latex path for matplotlib

I am trying to plot latex with matplotlib. I've installed latex with pip. this example works well我正在尝试使用 plot latex 和 matplotlib。我已经安装了 latex 和 pip。这个例子运行良好

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

while matplotlib.rcParams['text.usetex'] = True encounters latex error.matplotlib.rcParams['text.usetex'] = True遇到 latex 错误。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

which produces this stack产生这个堆栈

--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) ~/anaconda3/envs/tf11/lib/python3.6/site-packages/IPython/core/formatters.py in call (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) ---------------------------------------------- ---------------------- FileNotFoundError Traceback(最近调用最后)~/anaconda3/envs/tf11/lib/python3.6/site-packages /IPython/core/formatters.py in call (self, obj) 330 pass 331 else: --> 332 return printer(obj) 333 # 最后寻找特殊方法名 334 method = get_real_method(obj, self.print_method)

~/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)) ~/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 如果格式为 'retina' 或格式为 'png2x': 239 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/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': ~/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 数据 = bytes_io.getvalue() 123 如果 fmt == 'svg':

~/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 ~/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
orientation=orientation, 2048 dryrun=True, -> 2049 **kwargs) 2050 renderer = self.figure._cachedRenderer 2051 orientation=orientation, 2048 dryrun=True, -> 2049 **kwargs) 2050 渲染器 = self.figure._cachedRenderer 2051
bbox_artists = kwargs.pop("bbox_extra_artists", None) bbox_artists = kwargs.pop("bbox_extra_artists", 无)

~/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 ~/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。绘制(自身)511 渲染器 = self.get_renderer() 512

~/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. ~/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 # GUI class 可能需要使用此抽奖更新 window,所以 404 # 不要忘记调用超类。

~/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: ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 返回draw(artist, renderer, *args, **kwargs) 51 最后:52 如果 artist.get_agg_filter() 不是 None:

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer) 1650 1651 ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer) 1650 1651
mimage._draw_list_compositing_images( -> 1652 renderer, self, artists, self.suppressComposite) 1653 1654 mimage._draw_list_compositing_images( -> 1652 渲染器、自我、艺术家、self.suppressComposite) 1653 1654
renderer.close_group('figure') renderer.close_group('图')

~/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 ~/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 # 将任何相邻图像合成在一起

~/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: ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 返回draw(artist, renderer, *args, **kwargs) 51 最后:52 如果 artist.get_agg_filter() 不是 None:

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe) 2602 ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe) 2602
renderer.stop_rasterizing() 2603 -> 2604 mimage._draw_list_compositing_images(renderer, self, artists) 2605 2606 renderer.close_group('axes') renderer.stop_rasterizing() 2603 -> 2604 mimage._draw_list_compositing_images(renderer, self, artists) 2605 2606 renderer.close_group('轴')

~/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 ~/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 # 将任何相邻图像合成在一起

~/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: ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 返回draw(artist, renderer, *args, **kwargs) 51 最后:52 如果 artist.get_agg_filter() 不是 None:

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs) 1185 ticks_to_draw = self._update_ticks(renderer) 1186 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, -> 1187 renderer) 1188 1189 for tick in ticks_to_draw: ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs) 1185 ticks_to_draw = self._update_ticks(renderer) 1186 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, -> 1187 renderer) 1188 1189 用于 ticks_to_draw 中的刻度:

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer) 1123 for tick in ticks: 1124 if tick.label1On and tick.label1.get_visible(): -> 1125 extent = tick.label1.get_window_extent(renderer) 1126 ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer) 1123 for tick in ticks: 1124 if tick.label1On and tick.label1.get_visible( ): -> 1125 extent = tick.label1.get_window_extent(渲染器) 1126
ticklabelBoxes.append(extent) 1127 if tick.label2On and tick.label2.get_visible(): ticklabelBoxes.append(extent) 1127 如果 tick.label2On 和 tick.label2.get_visible():

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi) 927 raise RuntimeError('Cannot get window extent w/o renderer') 928 --> 929 bbox, info, descent = self._get_layout(self._renderer) 930 x, y = self.get_unitless_position() 931 x, y = self.get_transform().transform_point((x, y)) ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi) 927 raise RuntimeError('Cannot get window extent w/o renderer') 928 -- > 929 bbox, 信息, 下降 = self._get_layout(self._renderer) 930 x, y = self.get_unitless_position() 931 x, y = self.get_transform().transform_point((x, y))

~/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 ~/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 其他: 315 w, h, d = 0, 0, 0

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath) 207 fontsize = prop.get_size_in_points() 208 w, h, d = texmanager.get_text_width_height_descent( --> 209 s, fontsize, renderer=self) 210 return w, h, d 211 ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath) 207 fontsize = prop.get_size_in_points() 208 w, h, d = texmanager.get_text_width_height_descent( --> 209 s, fontsize, renderer=self) 210 返回 w, h, d 211

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer) 462 else: 463 # use dviread. ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer) 462 else: 463 # 使用 dviread。 It sometimes returns a wrong descent.它有时会返回错误的血统。 --> 464 dvifile = self.make_dvi(tex, fontsize) 465 with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi: 466 page = next(iter(dvi)) --> 464 dvifile = self.make_dvi(tex, fontsize) 465 with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi: 466 page = next(iter(dvi))

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize) 326 self._run_checked_subprocess( 327 ["latex", "-interaction=nonstopmode", "--halt-on-error", --> 328 texfile], tex) 329 for fname in glob.glob(basefile + '*'): 330 if not fname.endswith(('dvi', 'tex')): ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize) 326 self._run_checked_subprocess( 327 ["latex", "-interaction=nonstopmode", "--halt-on-error", --> 328 texfile], tex) 329 for fname in glob.glob(basefile + '*'): 330 if not fname.endswith(('dvi', 'tex') ):

~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex) 296 report = subprocess.check_output(command, 297 cwd=self.texcache, --> 298 stderr=subprocess.STDOUT) 299 except subprocess.CalledProcessError as exc: 300 raise RuntimeError( ~/anaconda3/envs/tf11/lib/python3.6/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex) 296 report = subprocess.check_output(command, 297 cwd=self.texcache, -- > 298 stderr=subprocess.STDOUT) 299 except subprocess.CalledProcessError as exc: 300 raise RuntimeError(

~/anaconda3/envs/tf11/lib/python3.6/subprocess.py in check_output(timeout, *popenargs, **kwargs) 334 335 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, --> 336 **kwargs).stdout 337 338 ~/anaconda3/envs/tf11/lib/python3.6/subprocess.py in check_output(timeout, *popenargs, **kwargs) 334 335 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, - -> 336 **kwargs).stdout 337 338

~/anaconda3/envs/tf11/lib/python3.6/subprocess.py in run(input, timeout, check, *popenargs, **kwargs) 401 kwargs['stdin'] = PIPE 402 --> 403 with Popen(*popenargs, **kwargs) as process: 404 try: 405 stdout, stderr = process.communicate(input, timeout=timeout) ~/anaconda3/envs/tf11/lib/python3.6/subprocess.py in run(input, timeout, check, *popenargs, **kwargs) 401 kwargs['stdin'] = PIPE 402 --> 403 with Popen( *popenargs, **kwargs) 作为进程:404 try: 405 stdout, stderr = process.communicate(input, timeout=timeout)

~/anaconda3/envs/tf11/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) 705 c2pread, c2pwrite, 706 errread, errwrite, --> 707 restore_signals, start_new_session) 708 except: 709 # Cleanup if the child failed starting. ~/anaconda3/envs/tf11/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) 705 c2pread, c2pwrite, 706 errread, errwrite, --> 707 restore_signals, start_new_session) 708 except: 709 # 如果孩子启动失败则清理。

~/anaconda3/envs/tf11/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) 1331 else: 1332 ~/anaconda3/envs/tf11/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,错误读取,错误写入,restore_signals,start_new_session)1331 其他:1332
err_msg += ': ' + repr(orig_executable) -> 1333 raise child_exception_type(errno_num, err_msg) 1334 raise child_exception_type(err_msg) err_msg += ': ' + repr(orig_executable) -> 1333 提高 child_exception_type(errno_num, err_msg) 1334 提高 child_exception_type(err_msg)
1335 1335

FileNotFoundError: [Errno 2] No such file or directory: 'latex' FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'latex'

The latex PyPI project which you have installed with pip is not a full latex distro, it instead "allows calling LaTeX from Python without leaving a mess."您使用 pip 安装的Latex PyPI 项目不是完整的 Latex 发行版,而是“允许从 Python 调用 LaTeX 而不会留下一团糟。”

The reason your first example works is there is no call to LaTeX.您的第一个示例有效的原因是没有调用 LaTeX。 Instead, matplotlib uses its own TeX expression parser, layout engine and fonts: mathtext .相反,matplotlib 使用自己的 TeX 表达式解析器、布局引擎和字体: mathtext In the second example you really are trying to call LaTeX, but you're getting an error since you don't have a tex distro installed!在第二个示例中,您确实尝试调用 LaTeX,但是由于您没有安装 tex 发行版,因此出现错误!

You will need to ensure you have a tex distribution installed on your system.您需要确保您的系统上安装了 tex 发行版。 Either TeXLive or MikTex will do the trick. TeXLiveMikTex都可以。 Also, the matplotlib documentation on text rendering with LaTeX is very good and I'd recommend you give it a read.此外,关于使用 LaTeX 进行文本渲染的matplotlib 文档非常好,我建议您阅读一下。

Here is how i changed the path.( Now I am pretty new to coding and I don't understand whats going on at the back. )这是我改变路径的方式。(现在我对编码还很陌生,我不明白后面发生了什么。)

opened terminal on my MacBook.在我的 MacBook 上打开终端。 typed 'python' and then the following two commands.输入“python”,然后输入以下两个命令。

import os
print(os.environ['PATH'])

(you will see a path- lets call it path1) (你会看到一条路径——我们称之为路径 1)

opened spyder (where i create and run my python files) and in the console again typed打开 spyder(我在其中创建并运行我的 python 文件)并在控制台中再次输入

import os
print(os.environ['PATH'])

(you will again see a path- lets call it path2) (您将再次看到一条路径 - 让我们称之为路径 2)

for me these two paths were different.对我来说,这两条路是不同的。 then in my spyder console i typed the following然后在我的 spyder 控制台中输入以下内容

os.environ["PATH"]='path1'

i once again checked if both the paths are now matching by typing我再次通过键入检查两条路径是否匹配

print(os.environ['PATH'])

my latex problem got solved after this.我的 latex 问题在此之后得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM