How to render Matplotlib plots with TEX code in Cyrillic - matplotlib
I'm trying to understand how to plot figures with Cyrillic text in the legend.
It seems that axes display TeX characters but text in the legend is using the default font. Here is the code:
import numpy as np
import matplotlib
matplotlib.use("pgf")
import matplotlib.pyplot as plt
matplotlib.rcParams['text.usetex'] = True
%matplotlib inline
x = np.linspace(-np.pi, np.pi, 256)
y = []
for i in range(-100, 100):
y += [np.cos(x + i)]
plt.xlim(-10, 10)
plt.ylim(-2, 2)
plt.xticks([-10, 0, 10])
plt.yticks()
plt.plot(x, y[0], color = 'red', linewidth = 2.5, linestyle = '-', label = 'style1')
plt.plot(x, y[1], color = 'blue', linewidth = 3, linestyle = '-', label = 'style2')
plt.legend()
Changing the label of the first (the red) line to something in cyrillic:
plt.plot(x, y[0], color = 'red', linewidth = 2.5, linestyle = '-', label = 'стил1')
gives the following error:
Error in callback .post_execute at 0x00000202EDCA3AF8> (for post_execute):
---------------------------------------------------------------------------
CalledProcessError 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)
410 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 411 **kwargs).stdout
412
~\anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
511 raise CalledProcessError(retcode, process.args,
--> 512 output=stdout, stderr=stderr)
513 return CompletedProcess(process.args, retcode, stdout, stderr)
CalledProcessError: Command '['latex', '-interaction=nonstopmode', '--halt-on-error', 'C:\\Users\\Victor\\.matplotlib\\tex.cache\\b6f49bb15be8eba85bb671cfafccfb49.tex']' returned non-zero exit status 1.
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)
1914 if not self._is_idle_drawing:
1915 with self._idle_draw_cntx():
-> 1916 self.draw(*args, **kwargs)
1917
1918 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)
2645 renderer.stop_rasterizing()
2646
-> 2647 mimage._draw_list_compositing_images(renderer, self, artists)
2648
2649 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\legend.py in draw(self, renderer)
656 # update the location and size of the legend. This needs to
657 # be done in any case to clip the figure right.
--> 658 bbox = self._legend_box.get_window_extent(renderer)
659 self.legendPatch.set_bounds(bbox.x0, bbox.y0,
660 bbox.width, bbox.height)
...
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
284 def get_extent(self, renderer):
285 """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
--> 286 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
287 return w, h, xd, yd
288
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
284 def get_extent(self, renderer):
285 """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
--> 286 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
287 return w, h, xd, yd
288
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
875 "lp", self._text._fontproperties, ismath=False)
876
--> 877 bbox, info, d = self._text._get_layout(renderer)
878 w, h = bbox.width, bbox.height
879
~\anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
296 if clean_line:
297 w, h, d = renderer.get_text_width_height_descent(
--> 298 clean_line, self._fontproperties, ismath=ismath)
299 else:
300 w = h = d = 0
~\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)
315 prog=command[0],
316 tex=tex.encode('unicode_escape'),
--> 317 exc=exc.output.decode('utf-8'))) from exc
318 _log.debug(report)
319 return report
RuntimeError: latex was not able to process the following string:
b'\\u0441\\u0442\\u0438\\u043b1'
Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019/W32TeX) (preloaded format=latex)
restricted \write18 enabled.
entering extended mode
(c:/Users/Victor/.matplotlib/tex.cache/b6f49bb15be8eba85bb671cfafccfb49.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-02-25>
(c:/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(c:/texlive/2019/texmf-dist/tex/latex/base/size10.clo))
(c:/texlive/2019/texmf-dist/tex/latex/type1cm/type1cm.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/textcomp.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/inputenc.sty)
(c:/texlive/2019/texmf-dist/tex/latex/geometry/geometry.sty
(c:/texlive/2019/texmf-dist/tex/latex/graphics/keyval.sty)
(c:/texlive/2019/texmf-dist/tex/generic/iftex/ifvtex.sty
(c:/texlive/2019/texmf-dist/tex/generic/iftex/iftex.sty))
Package geometry Warning: Over-specification in `h'-direction.
`width' (5058.9pt) is ignored.
Package geometry Warning: Over-specification in `v'-direction.
`height' (5058.9pt) is ignored.
) (c:/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-dvips.def)
(./b6f49bb15be8eba85bb671cfafccfb49.aux)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Package inputenc Error: Unicode character с (U+0441)
(inputenc) not set up for use with LaTeX.
See the inputenc package documentation for explanation.
Type H <return> for immediate help.
...
l.14 \fontsize{10.000000}{12.500000}{\sffamily с
тил1}
No pages of output.
Transcript written on b6f49bb15be8eba85bb671cfafccfb49.log.
---------------------------------------------------------------------------
CalledProcessError 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)
410 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 411 **kwargs).stdout
412
~\anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
511 raise CalledProcessError(retcode, process.args,
--> 512 output=stdout, stderr=stderr)
513 return CompletedProcess(process.args, retcode, stdout, stderr)
CalledProcessError: Command '['latex', '-interaction=nonstopmode', '--halt-on-error', 'C:\\Users\\Victor\\.matplotlib\\tex.cache\\b6f49bb15be8eba85bb671cfafccfb49.tex']' returned non-zero exit status 1.
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)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 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)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io, **kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
~\anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2063 orientation=orientation,
2064 dryrun=True,
-> 2065 **kwargs)
2066 renderer = self.figure._cachedRenderer
2067 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)
2645 renderer.stop_rasterizing()
2646
-> 2647 mimage._draw_list_compositing_images(renderer, self, artists)
2648
2649 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\legend.py in draw(self, renderer)
656 # update the location and size of the legend. This needs to
657 # be done in any case to clip the figure right.
--> 658 bbox = self._legend_box.get_window_extent(renderer)
659 self.legendPatch.set_bounds(bbox.x0, bbox.y0,
660 bbox.width, bbox.height)
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_window_extent(self, renderer)
289 def get_window_extent(self, renderer):
290 """Return the bounding box (`.Bbox`) in display space."""
--> 291 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
292 px, py = self.get_offset(w, h, xd, yd, renderer)
293 return mtransforms.Bbox.from_bounds(px - xd, py - yd, w, h)
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
284 def get_extent(self, renderer):
285 """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
--> 286 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
287 return w, h, xd, yd
288
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
284 def get_extent(self, renderer):
285 """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
--> 286 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
287 return w, h, xd, yd
288
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
417
418 whd_list = [c.get_extent(renderer)
--> 419 for c in self.get_visible_children()]
420 whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
421
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
284 def get_extent(self, renderer):
285 """Return a tuple ``width, height, xdescent, ydescent`` of the box."""
--> 286 w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
287 return w, h, xd, yd
288
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent_offsets(self, renderer)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in <listcomp>(.0)
491
492 whd_list = [c.get_extent(renderer)
--> 493 for c in self.get_visible_children()]
494
495 if not whd_list:
~\anaconda3\lib\site-packages\matplotlib\offsetbox.py in get_extent(self, renderer)
875 "lp", self._text._fontproperties, ismath=False)
876
--> 877 bbox, info, d = self._text._get_layout(renderer)
878 w, h = bbox.width, bbox.height
879
~\anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
296 if clean_line:
297 w, h, d = renderer.get_text_width_height_descent(
--> 298 clean_line, self._fontproperties, ismath=ismath)
299 else:
300 w = h = d = 0
~\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)
315 prog=command[0],
316 tex=tex.encode('unicode_escape'),
--> 317 exc=exc.output.decode('utf-8'))) from exc
318 _log.debug(report)
319 return report
RuntimeError: latex was not able to process the following string:
b'\\u0441\\u0442\\u0438\\u043b1'
Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019/W32TeX) (preloaded format=latex)
restricted \write18 enabled.
entering extended mode
(c:/Users/Victor/.matplotlib/tex.cache/b6f49bb15be8eba85bb671cfafccfb49.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-02-25>
(c:/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(c:/texlive/2019/texmf-dist/tex/latex/base/size10.clo))
(c:/texlive/2019/texmf-dist/tex/latex/type1cm/type1cm.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/textcomp.sty)
(c:/texlive/2019/texmf-dist/tex/latex/base/inputenc.sty)
(c:/texlive/2019/texmf-dist/tex/latex/geometry/geometry.sty
(c:/texlive/2019/texmf-dist/tex/latex/graphics/keyval.sty)
(c:/texlive/2019/texmf-dist/tex/generic/iftex/ifvtex.sty
(c:/texlive/2019/texmf-dist/tex/generic/iftex/iftex.sty))
Package geometry Warning: Over-specification in `h'-direction.
`width' (5058.9pt) is ignored.
Package geometry Warning: Over-specification in `v'-direction.
`height' (5058.9pt) is ignored.
) (c:/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-dvips.def)
(./b6f49bb15be8eba85bb671cfafccfb49.aux)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Package inputenc Error: Unicode character с (U+0441)
(inputenc) not set up for use with LaTeX.
See the inputenc package documentation for explanation.
Type H <return> for immediate help.
...
l.14 \fontsize{10.000000}{12.500000}{\sffamily с
тил1}
No pages of output.
Transcript written on b6f49bb15be8eba85bb671cfafccfb49.log.
Solving this is important for me because I plan to redo a whole project, written using R (a book) in Python.
You need to tell tex that you would like to display some Russian.
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
rc('text.latex',unicode=True)
rc('text.latex',preamble=r'\usepackage[utf8]{inputenc}')
rc('text.latex',preamble=r'\usepackage[russian]{babel}')
x = np.linspace(-np.pi, np.pi, 256)
y = []
for i in range(-100, 100):
y += [np.cos(x + i)]
plt.xlim(-10, 10)
plt.ylim(-2, 2)
plt.xticks([-10, 0, 10])
plt.yticks()
plt.plot(x, y[0], color = 'red', linewidth = 2.5, linestyle = '-', label = 'стил1')
plt.plot(x, y[1], color = 'blue', linewidth = 3, linestyle = '-', label = 'style2')
plt.legend()
plt.show()
Related
tight_layout KeyError default, matplotlib widget
Using jupyterlab, i receive a KeyError: 'Default' when using plt.tight_layout() in combination with %matplotlib widget. The following code reproduces the issue: import matplotlib.pyplot as plt import numpy as np %matplotlib widget x=np.linspace(0,10) y=x**2 plt.plot(x,y) plt.tight_layout() The complete error message is the following: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~/anaconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in _wait_cursor_for_draw_cm(self) 3024 try: -> 3025 self.canvas.set_cursor(tools.Cursors.WAIT) 3026 yield ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in set_cursor(self, cursor) 209 }, cursor=cursor) --> 210 self.send_event('cursor', cursor=cursor) 211 ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in send_event(self, event_type, **kwargs) 391 if self.manager: --> 392 self.manager._send_event(event_type, **kwargs) 393 ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in _send_event(self, event_type, **kwargs) 540 for s in self.web_sockets: --> 541 s.send_json(payload) 542 ~/anaconda3/lib/python3.8/site-packages/ipympl/backend_nbagg.py in send_json(self, content) 180 if content['type'] == 'cursor': --> 181 self._cursor = cursors_str[content['cursor']] 182 KeyError: 'wait' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) /tmp/ipykernel_119035/3466922198.py in <module> 7 y=x**2 8 plt.plot(x,y) ----> 9 plt.tight_layout() ~/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in tight_layout(pad, h_pad, w_pad, rect) 2300 #_copy_docstring_and_deprecators(Figure.tight_layout) 2301 def tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None): -> 2302 return gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) 2303 2304 ~/anaconda3/lib/python3.8/site-packages/matplotlib/figure.py in tight_layout(self, pad, h_pad, w_pad, rect) 3186 "compatible with tight_layout, so results " 3187 "might be incorrect.") -> 3188 renderer = _get_renderer(self) 3189 with getattr(renderer, "_draw_disabled", nullcontext)(): 3190 kwargs = get_tight_layout_figure( ~/anaconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in _get_renderer(figure, print_method) 1542 figure.canvas._get_output_canvas(None, fmt), f"print_{fmt}") 1543 try: -> 1544 print_method(io.BytesIO()) 1545 except Done as exc: 1546 renderer, = figure._cachedRenderer, = exc.args ~/anaconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in wrapper(*args, **kwargs) 1641 kwargs.pop(arg) 1642 -> 1643 return func(*args, **kwargs) 1644 1645 return wrapper ~/anaconda3/lib/python3.8/site-packages/matplotlib/_api/deprecation.py in wrapper(*inner_args, **inner_kwargs) 410 else deprecation_addendum, 411 **kwargs) --> 412 return func(*inner_args, **inner_kwargs) 413 414 DECORATORS[wrapper] = decorator ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args) 538 *metadata*, including the default 'Software' key. 539 """ --> 540 FigureCanvasAgg.draw(self) 541 mpl.image.imsave( 542 filename_or_obj, self.buffer_rgba(), format="png", origin="upper", ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py in draw(self) 431 self.renderer = self.get_renderer(cleared=True) 432 # Acquire a lock on the shared font cache. --> 433 with RendererAgg.lock, \ 434 (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar 435 else nullcontext()): ~/anaconda3/lib/python3.8/contextlib.py in __enter__(self) 111 del self.args, self.kwds, self.func 112 try: --> 113 return next(self.gen) 114 except StopIteration: 115 raise RuntimeError("generator didn't yield") from None ~/anaconda3/lib/python3.8/site-packages/matplotlib/backend_bases.py in _wait_cursor_for_draw_cm(self) 3026 yield 3027 finally: -> 3028 self.canvas.set_cursor(self._lastCursor) 3029 else: 3030 yield ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in set_cursor(self, cursor) 208 backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize', 209 }, cursor=cursor) --> 210 self.send_event('cursor', cursor=cursor) 211 212 def set_image_mode(self, mode): ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in send_event(self, event_type, **kwargs) 390 def send_event(self, event_type, **kwargs): 391 if self.manager: --> 392 self.manager._send_event(event_type, **kwargs) 393 394 ~/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py in _send_event(self, event_type, **kwargs) 539 payload = {'type': event_type, **kwargs} 540 for s in self.web_sockets: --> 541 s.send_json(payload) 542 543 ~/anaconda3/lib/python3.8/site-packages/ipympl/backend_nbagg.py in send_json(self, content) 179 # Change in the widget state? 180 if content['type'] == 'cursor': --> 181 self._cursor = cursors_str[content['cursor']] 182 183 elif content['type'] == 'message': KeyError: 'default'
Run TFMA for Keras models without compiling
I am training a Keras model using custom training loops in TensorFlow, where the weights are updated using gradient tape rather than the model.fit() method. As such, the model is not compiled before training. After exporting the saved_model, I am able to successfully load it for inference: model = tf.saved_model.load("path/to/saved_model") pred_fn = model.signatures["serving_default"] results = pred_fn(tf.constant(examples)) However, when I try loading it with TFMA using run_model_analysis: eval_shared_model = tfma.default_eval_shared_model("path/to/saved_model", eval_config=eval_config) eval_results = tfma.run_model_analysis( eval_shared_model=eval_shared_model, data_location=test_tfrecords_path, file_format="tfrecords" ) I get the following error: WARNING:tensorflow:No training configuration found in save file, so the model was *not* compiled. Compile it manually. ----------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-107-19f51f42014a> in <module> 2 eval_shared_model=eval_shared_model, 3 data_location=test_tfrecords_path, ----> 4 file_format="tfrecords" 5 ) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/api/model_eval_lib.py in run_model_analysis(eval_shared_model, eval_config, data_location, file_format, output_path, extractors, evaluators, writers, pipeline_options, slice_spec, write_config, compute_confidence_intervals, min_slice_size, random_seed_for_testing, schema) 1200 random_seed_for_testing=random_seed_for_testing, 1201 tensor_adapter_config=tensor_adapter_config, -> 1202 schema=schema)) 1203 # pylint: enable=no-value-for-parameter 1204 ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pvalue.py in __or__(self, ptransform) 138 139 def __or__(self, ptransform): --> 140 return self.pipeline.apply(ptransform, self) 141 142 ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 575 if isinstance(transform, ptransform._NamedPTransform): 576 return self.apply( --> 577 transform.transform, pvalueish, label or transform.label) 578 579 if not isinstance(transform, ptransform.PTransform): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 585 try: 586 old_label, transform.label = transform.label, label --> 587 return self.apply(transform, pvalueish) 588 finally: 589 transform.label = old_label ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 628 transform.type_check_inputs(pvalueish) 629 --> 630 pvalueish_result = self.runner.apply(transform, pvalueish, self._options) 631 632 if type_options is not None and type_options.pipeline_type_check: ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply(self, transform, input, options) 196 m = getattr(self, 'apply_%s' % cls.__name__, None) 197 if m: --> 198 return m(transform, input, options) 199 raise NotImplementedError( 200 'Execution of [%s] not implemented in runner %s.' % (transform, self)) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply_PTransform(self, transform, input, options) 226 def apply_PTransform(self, transform, input, options): 227 # The base case of apply is to call the transform's expand. --> 228 return transform.expand(input) 229 230 def run_transform(self, ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/transforms/ptransform.py in expand(self, pcoll) 921 # Might not be a function. 922 pass --> 923 return self._fn(pcoll, *args, **kwargs) 924 925 def default_label(self): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/api/model_eval_lib.py in ExtractEvaluateAndWriteResults(examples, eval_shared_model, eval_config, extractors, evaluators, writers, output_path, display_only_data_location, display_only_file_format, slice_spec, write_config, compute_confidence_intervals, min_slice_size, random_seed_for_testing, tensor_adapter_config, schema) 1079 | 'ExtractAndEvaluate' >> ExtractAndEvaluate( 1080 extractors=extractors, evaluators=evaluators) -> 1081 | 'WriteResults' >> WriteResults(writers=writers)) 1082 1083 return beam.pvalue.PDone(examples.pipeline) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pvalue.py in __or__(self, ptransform) 138 139 def __or__(self, ptransform): --> 140 return self.pipeline.apply(ptransform, self) 141 142 ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 575 if isinstance(transform, ptransform._NamedPTransform): 576 return self.apply( --> 577 transform.transform, pvalueish, label or transform.label) 578 579 if not isinstance(transform, ptransform.PTransform): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 585 try: 586 old_label, transform.label = transform.label, label --> 587 return self.apply(transform, pvalueish) 588 finally: 589 transform.label = old_label ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 628 transform.type_check_inputs(pvalueish) 629 --> 630 pvalueish_result = self.runner.apply(transform, pvalueish, self._options) 631 632 if type_options is not None and type_options.pipeline_type_check: ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply(self, transform, input, options) 196 m = getattr(self, 'apply_%s' % cls.__name__, None) 197 if m: --> 198 return m(transform, input, options) 199 raise NotImplementedError( 200 'Execution of [%s] not implemented in runner %s.' % (transform, self)) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply_PTransform(self, transform, input, options) 226 def apply_PTransform(self, transform, input, options): 227 # The base case of apply is to call the transform's expand. --> 228 return transform.expand(input) 229 230 def run_transform(self, ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/transforms/ptransform.py in expand(self, pcoll) 921 # Might not be a function. 922 pass --> 923 return self._fn(pcoll, *args, **kwargs) 924 925 def default_label(self): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/api/model_eval_lib.py in ExtractAndEvaluate(extracts, extractors, evaluators) 818 for v in evaluators: 819 if v.run_after == x.stage_name: --> 820 update(evaluation, extracts | v.stage_name >> v.ptransform) 821 for v in evaluators: 822 if v.run_after == extractor.LAST_EXTRACTOR_STAGE_NAME: ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pvalue.py in __or__(self, ptransform) 138 139 def __or__(self, ptransform): --> 140 return self.pipeline.apply(ptransform, self) 141 142 ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 575 if isinstance(transform, ptransform._NamedPTransform): 576 return self.apply( --> 577 transform.transform, pvalueish, label or transform.label) 578 579 if not isinstance(transform, ptransform.PTransform): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 585 try: 586 old_label, transform.label = transform.label, label --> 587 return self.apply(transform, pvalueish) 588 finally: 589 transform.label = old_label ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 628 transform.type_check_inputs(pvalueish) 629 --> 630 pvalueish_result = self.runner.apply(transform, pvalueish, self._options) 631 632 if type_options is not None and type_options.pipeline_type_check: ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply(self, transform, input, options) 196 m = getattr(self, 'apply_%s' % cls.__name__, None) 197 if m: --> 198 return m(transform, input, options) 199 raise NotImplementedError( 200 'Execution of [%s] not implemented in runner %s.' % (transform, self)) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply_PTransform(self, transform, input, options) 226 def apply_PTransform(self, transform, input, options): 227 # The base case of apply is to call the transform's expand. --> 228 return transform.expand(input) 229 230 def run_transform(self, ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/transforms/ptransform.py in expand(self, pcoll) 921 # Might not be a function. 922 pass --> 923 return self._fn(pcoll, *args, **kwargs) 924 925 def default_label(self): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/evaluators/metrics_and_plots_evaluator_v2.py in _EvaluateMetricsAndPlots(extracts, eval_config, eval_shared_models, metrics_key, plots_key, validations_key, schema, random_seed_for_testing) 757 plots_key=plots_key, 758 schema=schema, --> 759 random_seed_for_testing=random_seed_for_testing)) 760 761 for k, v in evaluation.items(): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pvalue.py in __or__(self, ptransform) 138 139 def __or__(self, ptransform): --> 140 return self.pipeline.apply(ptransform, self) 141 142 ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 575 if isinstance(transform, ptransform._NamedPTransform): 576 return self.apply( --> 577 transform.transform, pvalueish, label or transform.label) 578 579 if not isinstance(transform, ptransform.PTransform): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 585 try: 586 old_label, transform.label = transform.label, label --> 587 return self.apply(transform, pvalueish) 588 finally: 589 transform.label = old_label ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/pipeline.py in apply(self, transform, pvalueish, label) 628 transform.type_check_inputs(pvalueish) 629 --> 630 pvalueish_result = self.runner.apply(transform, pvalueish, self._options) 631 632 if type_options is not None and type_options.pipeline_type_check: ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply(self, transform, input, options) 196 m = getattr(self, 'apply_%s' % cls.__name__, None) 197 if m: --> 198 return m(transform, input, options) 199 raise NotImplementedError( 200 'Execution of [%s] not implemented in runner %s.' % (transform, self)) ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/runners/runner.py in apply_PTransform(self, transform, input, options) 226 def apply_PTransform(self, transform, input, options): 227 # The base case of apply is to call the transform's expand. --> 228 return transform.expand(input) 229 230 def run_transform(self, ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/apache_beam/transforms/ptransform.py in expand(self, pcoll) 921 # Might not be a function. 922 pass --> 923 return self._fn(pcoll, *args, **kwargs) 924 925 def default_label(self): ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/evaluators/metrics_and_plots_evaluator_v2.py in _ComputeMetricsAndPlots(extracts, eval_config, metrics_specs, eval_shared_models, metrics_key, plots_key, schema, random_seed_for_testing) 582 if eval_shared_model.model_type == constants.TF_KERAS: 583 keras_specs = keras_util.metrics_specs_from_keras( --> 584 model_name, eval_shared_model.model_loader) 585 metrics_specs = keras_specs + metrics_specs[:] 586 # TODO(mdreves): Add support for calling keras.evaluate(). ~/.pyenv/versions/miniconda3-4.3.30/envs/tensorflow/lib/python3.7/site-packages/tensorflow_model_analysis/evaluators/keras_util.py in metrics_specs_from_keras(model_name, model_loader) 60 # y_true, y_pred as inputs so it can't be calculated via standard inputs so 61 # we remove it. ---> 62 metrics.extend(model.compiled_loss.metrics[1:]) 63 metrics.extend(model.compiled_metrics.metrics) 64 metric_names = [m.name for m in metrics] AttributeError: 'NoneType' object has no attribute 'metrics' I suspect this might be because I am not compiling the Keras model before exporting it. Does TFMA only support compiled models? I am using tensorflow==2.3.0 and tensorflow-model-analysis==0.22.1
Yes, your understanding is correct i.e., it is resulting in error because you are not compiling and consequently, not adding the METRICS. It is evident from the statement specified in the Tensorflow Model Analysis Documentation as well, which is mentioned below. Note: Only training time metrics added via model.compile (not model.add_metric) are currently supported for keras.
The Key Error : logtostderr (python, tensorflow)
I am trying to implement a InceptionV3 to classify the images. (python 3.65 / tensorflow 1.14.0) when I run the code, I am getting these key error : "logtostderr". I don't know why this Key error happens. How can I solve this problem? Last week, I ran this code smoothly. but, the problem was happened yesterday suddenly. with tf.train.MonitoredSession(session_creator=session_creator) as sess: for filenames, images in load_images(FLAGS.input_dir, batch_shape): labels = sess.run(predicted_labels, feed_dict={x_input: images}) for filename, label in zip(filenames, labels): true_label = image_labels.merge(pd.DataFrame({"ImageId":[filename[:-4]]}), on="ImageId")["TrueLabel"][0] predictions.append([filename[:-4], true_label, label]) KeyError Traceback (most recent call last) <ipython-input-19-307b2daa19e5> in <module> 88 89 ---> 90 with tf.train.MonitoredSession(session_creator=session_creator) as sess: 91 for filenames, images in load_images(FLAGS.input_dir, batch_shape): 92 labels = sess.run(predicted_labels, feed_dict={x_input: images}) C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in __init__(self, session_creator, hooks, stop_grace_period_secs) 1005 hooks, 1006 should_recover=True, -> 1007 stop_grace_period_secs=stop_grace_period_secs) 1008 1009 C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in __init__(self, session_creator, hooks, should_recover, stop_grace_period_secs) 723 stop_grace_period_secs=stop_grace_period_secs) 724 if should_recover: --> 725 self._sess = _RecoverableSession(self._coordinated_creator) 726 else: 727 self._sess = self._coordinated_creator.create_session() C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in __init__(self, sess_creator) 1198 """ 1199 self._sess_creator = sess_creator -> 1200 _WrappedSession.__init__(self, self._create_session()) 1201 1202 def _create_session(self): C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in _create_session(self) 1203 while True: 1204 try: -> 1205 return self._sess_creator.create_session() 1206 except _PREEMPTION_ERRORS as e: 1207 logging.info( C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in create_session(self) 869 """Creates a coordinated session.""" 870 # Keep the tf_sess for unit testing. --> 871 self.tf_sess = self._session_creator.create_session() 872 # We don't want coordinator to suppress any exception. 873 self.coord = coordinator.Coordinator(clean_stop_exception_types=[]) C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in create_session(self) 636 637 def create_session(self): --> 638 self._scaffold.finalize() 639 return self._get_session_manager().prepare_session( 640 self._master, C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\monitored_session.py in finalize(self) 238 239 ops.get_default_graph().finalize() --> 240 logging.info('Graph was finalized.') 241 return self 242 C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\platform\tf_logging.py in info(msg, *args, **kwargs) 154 #tf_export(v1=['logging.info']) 155 def info(msg, *args, **kwargs): --> 156 get_logger().info(msg, *args, **kwargs) 157 158 C:\ProgramData\Anaconda3\lib\logging\__init__.py in info(self, msg, *args, **kwargs) 1306 """ 1307 if self.isEnabledFor(INFO): -> 1308 self._log(INFO, msg, args, **kwargs) 1309 1310 def warning(self, msg, *args, **kwargs): C:\ProgramData\Anaconda3\lib\logging\__init__.py in _log(self, level, msg, args, exc_info, extra, stack_info) 1442 record = self.makeRecord(self.name, level, fn, lno, msg, args, 1443 exc_info, func, extra, sinfo) -> 1444 self.handle(record) 1445 1446 def handle(self, record): C:\ProgramData\Anaconda3\lib\logging\__init__.py in handle(self, record) 1452 """ 1453 if (not self.disabled) and self.filter(record): -> 1454 self.callHandlers(record) 1455 1456 def addHandler(self, hdlr): C:\ProgramData\Anaconda3\lib\logging\__init__.py in callHandlers(self, record) 1514 found = found + 1 1515 if record.levelno >= hdlr.level: -> 1516 hdlr.handle(record) 1517 if not c.propagate: 1518 c = None #break out C:\ProgramData\Anaconda3\lib\site-packages\absl\logging\__init__.py in handle(self, record) 889 rv = self.filter(record) 890 if rv: --> 891 return self._current_handler.handle(record) 892 return rv 893 C:\ProgramData\Anaconda3\lib\logging\__init__.py in handle(self, record) 863 self.acquire() 864 try: --> 865 self.emit(record) 866 finally: 867 self.release() C:\ProgramData\Anaconda3\lib\site-packages\absl\logging\__init__.py in emit(self, record) 824 _warn_preinit_stderr = False 825 self._log_to_stderr(record) --> 826 elif FLAGS['logtostderr'].value: 827 self._log_to_stderr(record) 828 else: C:\ProgramData\Anaconda3\lib\site-packages\absl\flags\_flagvalues.py in __getitem__(self, name) 461 def __getitem__(self, name): 462 """Returns the Flag object for the flag --name.""" --> 463 return self._flags()[name] 464 465 def _hide_flag(self, name): KeyError: 'logtostderr'
Matplotlib set_major_formatter AttributeError
I'm trying to format the yaxis on a matplotlib graph using set_major_formatter. The plot is generated correctly, but the ax.yaxis.set_major_formatter() throws a couple of weird errors. The formatter: def mjrFormatter(x): return "{0:.0f}%".format(x * 100) The code that uses the formatter: ... ax.yaxis.set_major_formatter(mjrFormatter) ... Error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-108-b436fe657a8b> in <module>() ----> 1 plot_func(data = data, figsize=(20,10), fig_title = 'title') <ipython-input-107-d60ffc010a75> in plot_percent_moc(data, figsize, fig_title) 16 _ = data2[col].plot() 17 ---> 18 ax.yaxis.set_major_formatter(mjrFormatter) 19 20 fig.suptitle(fig_title, fontsize = 14) C:\Python27\lib\site-packages\matplotlib\axis.pyc in set_major_formatter(self, formatter) 1396 self.isDefault_majfmt = False 1397 self.major.formatter = formatter -> 1398 formatter.set_axis(self) 1399 1400 def set_minor_formatter(self, formatter): AttributeError: 'function' object has no attribute 'set_axis' --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\zmq\pylab\backend_inline.pyc in show(close) 100 try: 101 for figure_manager in Gcf.get_all_fig_managers(): --> 102 send_figure(figure_manager.canvas.figure) 103 finally: 104 show._to_draw = [] C:\Python27\lib\site-packages\IPython\zmq\pylab\backend_inline.pyc in send_figure(fig) 209 """ 210 fmt = InlineBackend.instance().figure_format --> 211 data = print_figure(fig, fmt) 212 # print_figure will return None if there's nothing to draw: 213 if data is None: C:\Python27\lib\site-packages\IPython\core\pylabtools.pyc in print_figure(fig, fmt) 102 try: 103 bytes_io = BytesIO() --> 104 fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight') 105 data = bytes_io.getvalue() 106 finally: C:\Python27\lib\site-packages\matplotlib\backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2050 orientation=orientation, 2051 dryrun=True, -> 2052 **kwargs) 2053 renderer = self.figure._cachedRenderer 2054 bbox_inches = self.figure.get_tightbbox(renderer) C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs) 489 490 def print_png(self, filename_or_obj, *args, **kwargs): --> 491 FigureCanvasAgg.draw(self) 492 renderer = self.get_renderer() 493 original_dpi = renderer.dpi C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.pyc in draw(self) 437 438 try: --> 439 self.figure.draw(self.renderer) 440 finally: 441 RendererAgg.lock.release() C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 52 def draw_wrapper(artist, renderer, *args, **kwargs): 53 before(artist, renderer) ---> 54 draw(artist, renderer, *args, **kwargs) 55 after(artist, renderer) 56 C:\Python27\lib\site-packages\matplotlib\figure.pyc in draw(self, renderer) 997 dsu.sort(key=itemgetter(0)) 998 for zorder, a, func, args in dsu: --> 999 func(*args) 1000 1001 renderer.close_group('figure') C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 52 def draw_wrapper(artist, renderer, *args, **kwargs): 53 before(artist, renderer) ---> 54 draw(artist, renderer, *args, **kwargs) 55 after(artist, renderer) 56 C:\Python27\lib\site-packages\matplotlib\axes.pyc in draw(self, renderer, inframe) 2084 2085 for zorder, a in dsu: -> 2086 a.draw(renderer) 2087 2088 renderer.close_group('axes') C:\Python27\lib\site-packages\matplotlib\artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 52 def draw_wrapper(artist, renderer, *args, **kwargs): 53 before(artist, renderer) ---> 54 draw(artist, renderer, *args, **kwargs) 55 after(artist, renderer) 56 C:\Python27\lib\site-packages\matplotlib\axis.pyc in draw(self, renderer, *args, **kwargs) 1046 renderer.open_group(__name__) 1047 -> 1048 ticks_to_draw = self._update_ticks(renderer) 1049 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, 1050 renderer) C:\Python27\lib\site-packages\matplotlib\axis.pyc in _update_ticks(self, renderer) 933 934 interval = self.get_view_interval() --> 935 tick_tups = [t for t in self.iter_ticks()] 936 if self._smart_bounds: 937 # handle inverted limits C:\Python27\lib\site-packages\matplotlib\axis.pyc in iter_ticks(self) 879 majorLocs = self.major.locator() 880 majorTicks = self.get_major_ticks(len(majorLocs)) --> 881 self.major.formatter.set_locs(majorLocs) 882 majorLabels = [self.major.formatter(val, i) 883 for i, val in enumerate(majorLocs)] AttributeError: 'function' object has no attribute 'set_locs' Am I doing something wrong or is this a bug?
The error is because set_major_formatter assumes it is getting a Formatter object (doc) so it is blowing up when it tries to do stuff with your function. I think you are looking for either FormatStrFormatter or FuncFormatter. (doc) def mjrFormatter(x, pos): return "{0:.0f}%".format(x * 100) gca().yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter)) The second argument in the signature is mandatory. or (which doesn't do what you want, but is closely related) gca().yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.2f%%'))
Network Plot Error Using Python / iPython
The following starter code errors out (AttributeError: incompatible shape for a non-contiguous array) when I try to use networkx on OSX 10.8.2, in an IPython notebook. import networkx as nx g = nx.Graph() g.add_node(1) g.add_node(2) g.add_edge(1,2) # no error if this line is omitted nx.draw(g) I do not see the error if I do not add the edge to this graph. Matplotlib, Numpy, and Scipy were all installed as suggested here. Below is the error message: AttributeError Traceback (most recent call last) <ipython-input-33-df7dfeff6452> in <module>() ----> 1 nx.draw(g) /usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.pyc in draw(G, pos, ax, hold, **kwds) 131 pylab.hold(h) 132 try: --> 133 draw_networkx(G,pos=pos,ax=ax,**kwds) 134 ax.set_axis_off() 135 pylab.draw_if_interactive() /usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.pyc in draw_networkx(G, pos, with_labels, **kwds) 265 266 node_collection=draw_networkx_nodes(G, pos, **kwds) --> 267 edge_collection=draw_networkx_edges(G, pos, **kwds) 268 if with_labels: 269 draw_networkx_labels(G, pos, **kwds) /usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.pyc in draw_networkx_edges(G, pos, edgelist, width, edge_color, style, alpha, edge_cmap, edge_vmin, edge_vmax, ax, arrows, label, **kwds) 544 edge_collection.set_zorder(1) # edges go behind nodes 545 edge_collection.set_label(label) --> 546 ax.add_collection(edge_collection) 547 548 # Note: there was a bug in mpl regarding the handling of alpha values for /usr/local/lib/python2.7/site-packages/matplotlib/axes.pyc in add_collection(self, collection, autolim) 1443 if autolim: 1444 if collection._paths and len(collection._paths): -> 1445 self.update_datalim(collection.get_datalim(self.transData)) 1446 1447 collection._remove_method = lambda h: self.collections.remove(h) /usr/local/lib/python2.7/site-packages/matplotlib/collections.pyc in get_datalim(self, transData) 165 offsets = offsets.filled(np.nan) 166 # get_path_collection_extents handles nan but not masked arrays --> 167 offsets.shape = (-1, 2) # Make it Nx2 168 169 result = mpath.get_path_collection_extents( AttributeError: incompatible shape for a non-contiguous array --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /usr/local/lib/python2.7/site-packages/IPython/zmq/pylab/backend_inline.pyc in show(close) 100 try: 101 for figure_manager in Gcf.get_all_fig_managers(): --> 102 send_figure(figure_manager.canvas.figure) 103 finally: 104 show._to_draw = [] /usr/local/lib/python2.7/site-packages/IPython/zmq/pylab/backend_inline.pyc in send_figure(fig) 209 """ 210 fmt = InlineBackend.instance().figure_format --> 211 data = print_figure(fig, fmt) 212 # print_figure will return None if there's nothing to draw: 213 if data is None: /usr/local/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt) 102 try: 103 bytes_io = BytesIO() --> 104 fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight') 105 data = bytes_io.getvalue() 106 finally: /usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 1981 orientation=orientation, 1982 dryrun=True, -> 1983 **kwargs) 1984 renderer = self.figure._cachedRenderer 1985 bbox_inches = self.figure.get_tightbbox(renderer) /usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs) 467 468 def print_png(self, filename_or_obj, *args, **kwargs): --> 469 FigureCanvasAgg.draw(self) 470 renderer = self.get_renderer() 471 original_dpi = renderer.dpi /usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self) 419 420 try: --> 421 self.figure.draw(self.renderer) 422 finally: 423 RendererAgg.lock.release() /usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---> 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /usr/local/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer) 896 dsu.sort(key=itemgetter(0)) 897 for zorder, a, func, args in dsu: --> 898 func(*args) 899 900 renderer.close_group('figure') /usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---> 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /usr/local/lib/python2.7/site-packages/matplotlib/axes.pyc in draw(self, renderer, inframe) 1995 1996 for zorder, a in dsu: -> 1997 a.draw(renderer) 1998 1999 renderer.close_group('axes') /usr/local/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs) 53 def draw_wrapper(artist, renderer, *args, **kwargs): 54 before(artist, renderer) ---> 55 draw(artist, renderer, *args, **kwargs) 56 after(artist, renderer) 57 /usr/local/lib/python2.7/site-packages/matplotlib/collections.pyc in draw(self, renderer) 227 self.update_scalarmappable() 228 --> 229 transform, transOffset, offsets, paths = self._prepare_points() 230 231 gc = renderer.new_gc() /usr/local/lib/python2.7/site-packages/matplotlib/collections.pyc in _prepare_points(self) 203 204 offsets = np.asanyarray(offsets, np.float_) --> 205 offsets.shape = (-1, 2) # Make it Nx2 206 207 if not transform.is_affine: AttributeError: incompatible shape for a non-contiguous array
This was reported earlier in Draw a graph with edges using Networkx. It likely is a bug/feature in the NumPy library development version as mentioned above (numpy issue 2700).