backend_pgf.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. import atexit
  2. import codecs
  3. import functools
  4. import logging
  5. import math
  6. import os
  7. import pathlib
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import weakref
  14. import matplotlib as mpl
  15. from matplotlib import _png, cbook, font_manager as fm, __version__, rcParams
  16. from matplotlib.backend_bases import (
  17. _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
  18. RendererBase)
  19. from matplotlib.backends.backend_mixed import MixedModeRenderer
  20. from matplotlib.path import Path
  21. from matplotlib.figure import Figure
  22. from matplotlib._pylab_helpers import Gcf
  23. _log = logging.getLogger(__name__)
  24. # Note: When formatting floating point values, it is important to use the
  25. # %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
  26. # which is not recognized by TeX.
  27. def get_fontspec():
  28. """Build fontspec preamble from rc."""
  29. latex_fontspec = []
  30. texcommand = rcParams["pgf.texsystem"]
  31. if texcommand != "pdflatex":
  32. latex_fontspec.append("\\usepackage{fontspec}")
  33. if texcommand != "pdflatex" and rcParams["pgf.rcfonts"]:
  34. families = ["serif", "sans\\-serif", "monospace"]
  35. commands = ["setmainfont", "setsansfont", "setmonofont"]
  36. for family, command in zip(families, commands):
  37. # 1) Forward slashes also work on Windows, so don't mess with
  38. # backslashes. 2) The dirname needs to include a separator.
  39. path = pathlib.Path(fm.findfont(family))
  40. latex_fontspec.append(r"\%s{%s}[Path=%s]" % (
  41. command, path.name, path.parent.as_posix() + "/"))
  42. return "\n".join(latex_fontspec)
  43. def get_preamble():
  44. """Get LaTeX preamble from rc."""
  45. return rcParams["pgf.preamble"]
  46. ###############################################################################
  47. # This almost made me cry!!!
  48. # In the end, it's better to use only one unit for all coordinates, since the
  49. # arithmetic in latex seems to produce inaccurate conversions.
  50. latex_pt_to_in = 1. / 72.27
  51. latex_in_to_pt = 1. / latex_pt_to_in
  52. mpl_pt_to_in = 1. / 72.
  53. mpl_in_to_pt = 1. / mpl_pt_to_in
  54. ###############################################################################
  55. # helper functions
  56. NO_ESCAPE = r"(?<!\\)(?:\\\\)*"
  57. re_mathsep = re.compile(NO_ESCAPE + r"\$")
  58. @cbook.deprecated("3.2")
  59. def repl_escapetext(m):
  60. return "\\" + m.group(1)
  61. @cbook.deprecated("3.2")
  62. def repl_mathdefault(m):
  63. return m.group(0)[:-len(m.group(1))]
  64. _replace_escapetext = functools.partial(
  65. # When the next character is _, ^, $, or % (not preceded by an escape),
  66. # insert a backslash.
  67. re.compile(NO_ESCAPE + "(?=[_^$%])").sub, "\\\\")
  68. _replace_mathdefault = functools.partial(
  69. # Replace \mathdefault (when not preceded by an escape) by empty string.
  70. re.compile(NO_ESCAPE + r"(\\mathdefault)").sub, "")
  71. def common_texification(text):
  72. """
  73. Do some necessary and/or useful substitutions for texts to be included in
  74. LaTeX documents.
  75. """
  76. # Sometimes, matplotlib adds the unknown command \mathdefault.
  77. # Not using \mathnormal instead since this looks odd for the latex cm font.
  78. text = _replace_mathdefault(text)
  79. # split text into normaltext and inline math parts
  80. parts = re_mathsep.split(text)
  81. for i, s in enumerate(parts):
  82. if not i % 2:
  83. # textmode replacements
  84. s = _replace_escapetext(s)
  85. else:
  86. # mathmode replacements
  87. s = r"\(\displaystyle %s\)" % s
  88. parts[i] = s
  89. return "".join(parts)
  90. def writeln(fh, line):
  91. # every line of a file included with \\input must be terminated with %
  92. # if not, latex will create additional vertical spaces for some reason
  93. fh.write(line)
  94. fh.write("%\n")
  95. def _font_properties_str(prop):
  96. # translate font properties to latex commands, return as string
  97. commands = []
  98. families = {"serif": r"\rmfamily", "sans": r"\sffamily",
  99. "sans-serif": r"\sffamily", "monospace": r"\ttfamily"}
  100. family = prop.get_family()[0]
  101. if family in families:
  102. commands.append(families[family])
  103. elif (any(font.name == family for font in fm.fontManager.ttflist)
  104. and rcParams["pgf.texsystem"] != "pdflatex"):
  105. commands.append(r"\setmainfont{%s}\rmfamily" % family)
  106. else:
  107. pass # print warning?
  108. size = prop.get_size_in_points()
  109. commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))
  110. styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}
  111. commands.append(styles[prop.get_style()])
  112. boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",
  113. "extra bold", "black"]
  114. if prop.get_weight() in boldstyles:
  115. commands.append(r"\bfseries")
  116. commands.append(r"\selectfont")
  117. return "".join(commands)
  118. def make_pdf_to_png_converter():
  119. """Returns a function that converts a pdf file to a png file."""
  120. if shutil.which("pdftocairo"):
  121. def cairo_convert(pdffile, pngfile, dpi):
  122. cmd = ["pdftocairo", "-singlefile", "-png", "-r", "%d" % dpi,
  123. pdffile, os.path.splitext(pngfile)[0]]
  124. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  125. return cairo_convert
  126. try:
  127. gs_info = mpl._get_executable_info("gs")
  128. except mpl.ExecutableNotFoundError:
  129. pass
  130. else:
  131. def gs_convert(pdffile, pngfile, dpi):
  132. cmd = [gs_info.executable,
  133. '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
  134. '-dUseCIEColor', '-dTextAlphaBits=4',
  135. '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
  136. '-sDEVICE=png16m', '-sOutputFile=%s' % pngfile,
  137. '-r%d' % dpi, pdffile]
  138. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  139. return gs_convert
  140. raise RuntimeError("No suitable pdf to png renderer found.")
  141. class LatexError(Exception):
  142. def __init__(self, message, latex_output=""):
  143. super().__init__(message)
  144. self.latex_output = latex_output
  145. @cbook.deprecated("3.1")
  146. class LatexManagerFactory:
  147. previous_instance = None
  148. @staticmethod
  149. def get_latex_manager():
  150. texcommand = rcParams["pgf.texsystem"]
  151. latex_header = LatexManager._build_latex_header()
  152. prev = LatexManagerFactory.previous_instance
  153. # Check if the previous instance of LatexManager can be reused.
  154. if (prev and prev.latex_header == latex_header
  155. and prev.texcommand == texcommand):
  156. _log.debug("reusing LatexManager")
  157. return prev
  158. else:
  159. _log.debug("creating LatexManager")
  160. new_inst = LatexManager()
  161. LatexManagerFactory.previous_instance = new_inst
  162. return new_inst
  163. class LatexManager:
  164. """
  165. The LatexManager opens an instance of the LaTeX application for
  166. determining the metrics of text elements. The LaTeX environment can be
  167. modified by setting fonts and/or a custom preamble in the rc parameters.
  168. """
  169. _unclean_instances = weakref.WeakSet()
  170. @staticmethod
  171. def _build_latex_header():
  172. latex_preamble = get_preamble()
  173. latex_fontspec = get_fontspec()
  174. # Create LaTeX header with some content, else LaTeX will load some math
  175. # fonts later when we don't expect the additional output on stdout.
  176. # TODO: is this sufficient?
  177. latex_header = [
  178. r"\documentclass{minimal}",
  179. # Include TeX program name as a comment for cache invalidation.
  180. # TeX does not allow this to be the first line.
  181. r"% !TeX program = {}".format(rcParams["pgf.texsystem"]),
  182. # Test whether \includegraphics supports interpolate option.
  183. r"\usepackage{graphicx}",
  184. latex_preamble,
  185. latex_fontspec,
  186. r"\begin{document}",
  187. r"text $math \mu$", # force latex to load fonts now
  188. r"\typeout{pgf_backend_query_start}",
  189. ]
  190. return "\n".join(latex_header)
  191. @classmethod
  192. def _get_cached_or_new(cls):
  193. """
  194. Return the previous LatexManager if the header and tex system did not
  195. change, or a new instance otherwise.
  196. """
  197. return cls._get_cached_or_new_impl(cls._build_latex_header())
  198. @classmethod
  199. @functools.lru_cache(1)
  200. def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
  201. return cls()
  202. @staticmethod
  203. def _cleanup_remaining_instances():
  204. unclean_instances = list(LatexManager._unclean_instances)
  205. for latex_manager in unclean_instances:
  206. latex_manager._cleanup()
  207. def _stdin_writeln(self, s):
  208. if self.latex is None:
  209. self._setup_latex_process()
  210. self.latex_stdin_utf8.write(s)
  211. self.latex_stdin_utf8.write("\n")
  212. self.latex_stdin_utf8.flush()
  213. def _expect(self, s):
  214. exp = s.encode("utf8")
  215. buf = bytearray()
  216. while True:
  217. b = self.latex.stdout.read(1)
  218. buf += b
  219. if buf[-len(exp):] == exp:
  220. break
  221. if not len(b):
  222. self.latex.kill()
  223. self.latex = None
  224. raise LatexError("LaTeX process halted", buf.decode("utf8"))
  225. return buf.decode("utf8")
  226. def _expect_prompt(self):
  227. return self._expect("\n*")
  228. def __init__(self):
  229. # store references for __del__
  230. self._os_path = os.path
  231. self._shutil = shutil
  232. # create a tmp directory for running latex, remember to cleanup
  233. self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
  234. LatexManager._unclean_instances.add(self)
  235. # test the LaTeX setup to ensure a clean startup of the subprocess
  236. self.texcommand = rcParams["pgf.texsystem"]
  237. self.latex_header = LatexManager._build_latex_header()
  238. latex_end = "\n\\makeatletter\n\\@@end\n"
  239. try:
  240. latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
  241. stdin=subprocess.PIPE,
  242. stdout=subprocess.PIPE,
  243. cwd=self.tmpdir)
  244. except FileNotFoundError:
  245. raise RuntimeError(
  246. "Latex command not found. Install %r or change "
  247. "pgf.texsystem to the desired command." % self.texcommand)
  248. except OSError:
  249. raise RuntimeError("Error starting process %r" % self.texcommand)
  250. test_input = self.latex_header + latex_end
  251. stdout, stderr = latex.communicate(test_input.encode("utf-8"))
  252. if latex.returncode != 0:
  253. raise LatexError("LaTeX returned an error, probably missing font "
  254. "or error in preamble:\n%s" % stdout)
  255. self.latex = None # Will be set up on first use.
  256. self.str_cache = {} # cache for strings already processed
  257. def _setup_latex_process(self):
  258. # open LaTeX process for real work
  259. latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
  260. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  261. cwd=self.tmpdir)
  262. self.latex = latex
  263. self.latex_stdin_utf8 = codecs.getwriter("utf8")(self.latex.stdin)
  264. # write header with 'pgf_backend_query_start' token
  265. self._stdin_writeln(self._build_latex_header())
  266. # read all lines until our 'pgf_backend_query_start' token appears
  267. self._expect("*pgf_backend_query_start")
  268. self._expect_prompt()
  269. def _cleanup(self):
  270. if not self._os_path.isdir(self.tmpdir):
  271. return
  272. try:
  273. self.latex.communicate()
  274. self.latex_stdin_utf8.close()
  275. self.latex.stdout.close()
  276. except Exception:
  277. pass
  278. try:
  279. self._shutil.rmtree(self.tmpdir)
  280. LatexManager._unclean_instances.discard(self)
  281. except Exception:
  282. sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)
  283. def __del__(self):
  284. _log.debug("deleting LatexManager")
  285. self._cleanup()
  286. def get_width_height_descent(self, text, prop):
  287. """
  288. Get the width, total height and descent for a text typeset by the
  289. current LaTeX environment.
  290. """
  291. # apply font properties and define textbox
  292. prop_cmds = _font_properties_str(prop)
  293. textbox = "\\sbox0{%s %s}" % (prop_cmds, text)
  294. # check cache
  295. if textbox in self.str_cache:
  296. return self.str_cache[textbox]
  297. # send textbox to LaTeX and wait for prompt
  298. self._stdin_writeln(textbox)
  299. try:
  300. self._expect_prompt()
  301. except LatexError as e:
  302. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  303. .format(text, e.latex_output))
  304. # typeout width, height and text offset of the last textbox
  305. self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}")
  306. # read answer from latex and advance to the next prompt
  307. try:
  308. answer = self._expect_prompt()
  309. except LatexError as e:
  310. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  311. .format(text, e.latex_output))
  312. # parse metrics from the answer string
  313. try:
  314. width, height, offset = answer.splitlines()[0].split(",")
  315. except Exception:
  316. raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
  317. .format(text, answer))
  318. w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
  319. # the height returned from LaTeX goes from base to top.
  320. # the height matplotlib expects goes from bottom to top.
  321. self.str_cache[textbox] = (w, h + o, o)
  322. return w, h + o, o
  323. @functools.lru_cache(1)
  324. def _get_image_inclusion_command():
  325. man = LatexManager._get_cached_or_new()
  326. man._stdin_writeln(
  327. r"\includegraphics[interpolate=true]{%s}"
  328. # Don't mess with backslashes on Windows.
  329. % cbook._get_data_path("images/matplotlib.png").as_posix())
  330. try:
  331. prompt = man._expect_prompt()
  332. return r"\includegraphics"
  333. except LatexError:
  334. # Discard the broken manager.
  335. LatexManager._get_cached_or_new_impl.cache_clear()
  336. return r"\pgfimage"
  337. class RendererPgf(RendererBase):
  338. def __init__(self, figure, fh, dummy=False):
  339. """
  340. Creates a new PGF renderer that translates any drawing instruction
  341. into text commands to be interpreted in a latex pgfpicture environment.
  342. Attributes
  343. ----------
  344. figure : `matplotlib.figure.Figure`
  345. Matplotlib figure to initialize height, width and dpi from.
  346. fh : file-like
  347. File handle for the output of the drawing commands.
  348. """
  349. RendererBase.__init__(self)
  350. self.dpi = figure.dpi
  351. self.fh = fh
  352. self.figure = figure
  353. self.image_counter = 0
  354. self._latexManager = LatexManager._get_cached_or_new() # deprecated
  355. if dummy:
  356. # dummy==True deactivate all methods
  357. for m in RendererPgf.__dict__:
  358. if m.startswith("draw_"):
  359. self.__dict__[m] = lambda *args, **kwargs: None
  360. else:
  361. # if fh does not belong to a filename, deactivate draw_image
  362. if not hasattr(fh, 'name') or not os.path.exists(fh.name):
  363. self.__dict__["draw_image"] = \
  364. lambda *args, **kwargs: cbook._warn_external(
  365. "streamed pgf-code does not support raster graphics, "
  366. "consider using the pgf-to-pdf option")
  367. @cbook.deprecated("3.2")
  368. @property
  369. def latexManager(self):
  370. return self._latexManager
  371. def draw_markers(self, gc, marker_path, marker_trans, path, trans,
  372. rgbFace=None):
  373. # docstring inherited
  374. writeln(self.fh, r"\begin{pgfscope}")
  375. # convert from display units to in
  376. f = 1. / self.dpi
  377. # set style and clip
  378. self._print_pgf_clip(gc)
  379. self._print_pgf_path_styles(gc, rgbFace)
  380. # build marker definition
  381. bl, tr = marker_path.get_extents(marker_trans).get_points()
  382. coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f
  383. writeln(self.fh,
  384. r"\pgfsys@defobject{currentmarker}"
  385. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)
  386. self._print_pgf_path(None, marker_path, marker_trans)
  387. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  388. fill=rgbFace is not None)
  389. writeln(self.fh, r"}")
  390. # draw marker for each vertex
  391. for point, code in path.iter_segments(trans, simplify=False):
  392. x, y = point[0] * f, point[1] * f
  393. writeln(self.fh, r"\begin{pgfscope}")
  394. writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))
  395. writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")
  396. writeln(self.fh, r"\end{pgfscope}")
  397. writeln(self.fh, r"\end{pgfscope}")
  398. def draw_path(self, gc, path, transform, rgbFace=None):
  399. # docstring inherited
  400. writeln(self.fh, r"\begin{pgfscope}")
  401. # draw the path
  402. self._print_pgf_clip(gc)
  403. self._print_pgf_path_styles(gc, rgbFace)
  404. self._print_pgf_path(gc, path, transform, rgbFace)
  405. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  406. fill=rgbFace is not None)
  407. writeln(self.fh, r"\end{pgfscope}")
  408. # if present, draw pattern on top
  409. if gc.get_hatch():
  410. writeln(self.fh, r"\begin{pgfscope}")
  411. self._print_pgf_path_styles(gc, rgbFace)
  412. # combine clip and path for clipping
  413. self._print_pgf_clip(gc)
  414. self._print_pgf_path(gc, path, transform, rgbFace)
  415. writeln(self.fh, r"\pgfusepath{clip}")
  416. # build pattern definition
  417. writeln(self.fh,
  418. r"\pgfsys@defobject{currentpattern}"
  419. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")
  420. writeln(self.fh, r"\begin{pgfscope}")
  421. writeln(self.fh,
  422. r"\pgfpathrectangle"
  423. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")
  424. writeln(self.fh, r"\pgfusepath{clip}")
  425. scale = mpl.transforms.Affine2D().scale(self.dpi)
  426. self._print_pgf_path(None, gc.get_hatch_path(), scale)
  427. self._pgf_path_draw(stroke=True)
  428. writeln(self.fh, r"\end{pgfscope}")
  429. writeln(self.fh, r"}")
  430. # repeat pattern, filling the bounding rect of the path
  431. f = 1. / self.dpi
  432. (xmin, ymin), (xmax, ymax) = \
  433. path.get_extents(transform).get_points()
  434. xmin, xmax = f * xmin, f * xmax
  435. ymin, ymax = f * ymin, f * ymax
  436. repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)
  437. writeln(self.fh,
  438. r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))
  439. for iy in range(repy):
  440. for ix in range(repx):
  441. writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")
  442. writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")
  443. writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)
  444. writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")
  445. writeln(self.fh, r"\end{pgfscope}")
  446. def _print_pgf_clip(self, gc):
  447. f = 1. / self.dpi
  448. # check for clip box
  449. bbox = gc.get_clip_rectangle()
  450. if bbox:
  451. p1, p2 = bbox.get_points()
  452. w, h = p2 - p1
  453. coords = p1[0] * f, p1[1] * f, w * f, h * f
  454. writeln(self.fh,
  455. r"\pgfpathrectangle"
  456. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  457. % coords)
  458. writeln(self.fh, r"\pgfusepath{clip}")
  459. # check for clip path
  460. clippath, clippath_trans = gc.get_clip_path()
  461. if clippath is not None:
  462. self._print_pgf_path(gc, clippath, clippath_trans)
  463. writeln(self.fh, r"\pgfusepath{clip}")
  464. def _print_pgf_path_styles(self, gc, rgbFace):
  465. # cap style
  466. capstyles = {"butt": r"\pgfsetbuttcap",
  467. "round": r"\pgfsetroundcap",
  468. "projecting": r"\pgfsetrectcap"}
  469. writeln(self.fh, capstyles[gc.get_capstyle()])
  470. # join style
  471. joinstyles = {"miter": r"\pgfsetmiterjoin",
  472. "round": r"\pgfsetroundjoin",
  473. "bevel": r"\pgfsetbeveljoin"}
  474. writeln(self.fh, joinstyles[gc.get_joinstyle()])
  475. # filling
  476. has_fill = rgbFace is not None
  477. if gc.get_forced_alpha():
  478. fillopacity = strokeopacity = gc.get_alpha()
  479. else:
  480. strokeopacity = gc.get_rgb()[3]
  481. fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0
  482. if has_fill:
  483. writeln(self.fh,
  484. r"\definecolor{currentfill}{rgb}{%f,%f,%f}"
  485. % tuple(rgbFace[:3]))
  486. writeln(self.fh, r"\pgfsetfillcolor{currentfill}")
  487. if has_fill and fillopacity != 1.0:
  488. writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)
  489. # linewidth and color
  490. lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt
  491. stroke_rgba = gc.get_rgb()
  492. writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)
  493. writeln(self.fh,
  494. r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"
  495. % stroke_rgba[:3])
  496. writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")
  497. if strokeopacity != 1.0:
  498. writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)
  499. # line style
  500. dash_offset, dash_list = gc.get_dashes()
  501. if dash_list is None:
  502. writeln(self.fh, r"\pgfsetdash{}{0pt}")
  503. else:
  504. writeln(self.fh,
  505. r"\pgfsetdash{%s}{%fpt}"
  506. % ("".join(r"{%fpt}" % dash for dash in dash_list),
  507. dash_offset))
  508. def _print_pgf_path(self, gc, path, transform, rgbFace=None):
  509. f = 1. / self.dpi
  510. # check for clip box / ignore clip for filled paths
  511. bbox = gc.get_clip_rectangle() if gc else None
  512. if bbox and (rgbFace is None):
  513. p1, p2 = bbox.get_points()
  514. clip = (p1[0], p1[1], p2[0], p2[1])
  515. else:
  516. clip = None
  517. # build path
  518. for points, code in path.iter_segments(transform, clip=clip):
  519. if code == Path.MOVETO:
  520. x, y = tuple(points)
  521. writeln(self.fh,
  522. r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
  523. (f * x, f * y))
  524. elif code == Path.CLOSEPOLY:
  525. writeln(self.fh, r"\pgfpathclose")
  526. elif code == Path.LINETO:
  527. x, y = tuple(points)
  528. writeln(self.fh,
  529. r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
  530. (f * x, f * y))
  531. elif code == Path.CURVE3:
  532. cx, cy, px, py = tuple(points)
  533. coords = cx * f, cy * f, px * f, py * f
  534. writeln(self.fh,
  535. r"\pgfpathquadraticcurveto"
  536. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  537. % coords)
  538. elif code == Path.CURVE4:
  539. c1x, c1y, c2x, c2y, px, py = tuple(points)
  540. coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
  541. writeln(self.fh,
  542. r"\pgfpathcurveto"
  543. r"{\pgfqpoint{%fin}{%fin}}"
  544. r"{\pgfqpoint{%fin}{%fin}}"
  545. r"{\pgfqpoint{%fin}{%fin}}"
  546. % coords)
  547. def _pgf_path_draw(self, stroke=True, fill=False):
  548. actions = []
  549. if stroke:
  550. actions.append("stroke")
  551. if fill:
  552. actions.append("fill")
  553. writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))
  554. def option_scale_image(self):
  555. # docstring inherited
  556. return True
  557. def option_image_nocomposite(self):
  558. # docstring inherited
  559. return not rcParams['image.composite_image']
  560. def draw_image(self, gc, x, y, im, transform=None):
  561. # docstring inherited
  562. h, w = im.shape[:2]
  563. if w == 0 or h == 0:
  564. return
  565. # save the images to png files
  566. path = os.path.dirname(self.fh.name)
  567. fname = os.path.splitext(os.path.basename(self.fh.name))[0]
  568. fname_img = "%s-img%d.png" % (fname, self.image_counter)
  569. self.image_counter += 1
  570. with pathlib.Path(path, fname_img).open("wb") as file:
  571. _png.write_png(im[::-1], file)
  572. # reference the image in the pgf picture
  573. writeln(self.fh, r"\begin{pgfscope}")
  574. self._print_pgf_clip(gc)
  575. f = 1. / self.dpi # from display coords to inch
  576. if transform is None:
  577. writeln(self.fh,
  578. r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
  579. w, h = w * f, h * f
  580. else:
  581. tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
  582. writeln(self.fh,
  583. r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
  584. (tr1 * f, tr2 * f, tr3 * f, tr4 * f,
  585. (tr5 + x) * f, (tr6 + y) * f))
  586. w = h = 1 # scale is already included in the transform
  587. interp = str(transform is None).lower() # interpolation in PDF reader
  588. writeln(self.fh,
  589. r"\pgftext[left,bottom]"
  590. r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %
  591. (_get_image_inclusion_command(),
  592. interp, w, h, fname_img))
  593. writeln(self.fh, r"\end{pgfscope}")
  594. def draw_tex(self, gc, x, y, s, prop, angle, ismath="TeX!", mtext=None):
  595. # docstring inherited
  596. self.draw_text(gc, x, y, s, prop, angle, ismath, mtext)
  597. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  598. # docstring inherited
  599. # prepare string for tex
  600. s = common_texification(s)
  601. prop_cmds = _font_properties_str(prop)
  602. s = r"%s %s" % (prop_cmds, s)
  603. writeln(self.fh, r"\begin{pgfscope}")
  604. alpha = gc.get_alpha()
  605. if alpha != 1.0:
  606. writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)
  607. writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)
  608. rgb = tuple(gc.get_rgb())[:3]
  609. writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)
  610. writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")
  611. writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
  612. s = r"\color{textcolor}" + s
  613. dpi = self.figure.dpi
  614. text_args = []
  615. if mtext and (
  616. (angle == 0 or
  617. mtext.get_rotation_mode() == "anchor") and
  618. mtext.get_verticalalignment() != "center_baseline"):
  619. # if text anchoring can be supported, get the original coordinates
  620. # and add alignment information
  621. pos = mtext.get_unitless_position()
  622. x, y = mtext.get_transform().transform(pos)
  623. halign = {"left": "left", "right": "right", "center": ""}
  624. valign = {"top": "top", "bottom": "bottom",
  625. "baseline": "base", "center": ""}
  626. text_args.extend([
  627. f"x={x/dpi:f}in",
  628. f"y={y/dpi:f}in",
  629. halign[mtext.get_horizontalalignment()],
  630. valign[mtext.get_verticalalignment()],
  631. ])
  632. else:
  633. # if not, use the text layout provided by Matplotlib.
  634. text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")
  635. if angle != 0:
  636. text_args.append("rotate=%f" % angle)
  637. writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))
  638. writeln(self.fh, r"\end{pgfscope}")
  639. def get_text_width_height_descent(self, s, prop, ismath):
  640. # docstring inherited
  641. # check if the math is supposed to be displaystyled
  642. s = common_texification(s)
  643. # get text metrics in units of latex pt, convert to display units
  644. w, h, d = (LatexManager._get_cached_or_new()
  645. .get_width_height_descent(s, prop))
  646. # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in
  647. # but having a little bit more space around the text looks better,
  648. # plus the bounding box reported by LaTeX is VERY narrow
  649. f = mpl_pt_to_in * self.dpi
  650. return w * f, h * f, d * f
  651. def flipy(self):
  652. # docstring inherited
  653. return False
  654. def get_canvas_width_height(self):
  655. # docstring inherited
  656. return (self.figure.get_figwidth() * self.dpi,
  657. self.figure.get_figheight() * self.dpi)
  658. def points_to_pixels(self, points):
  659. # docstring inherited
  660. return points * mpl_pt_to_in * self.dpi
  661. def new_gc(self):
  662. # docstring inherited
  663. return GraphicsContextPgf()
  664. class GraphicsContextPgf(GraphicsContextBase):
  665. pass
  666. ########################################################################
  667. class TmpDirCleaner:
  668. remaining_tmpdirs = set()
  669. @staticmethod
  670. def add(tmpdir):
  671. TmpDirCleaner.remaining_tmpdirs.add(tmpdir)
  672. @staticmethod
  673. def cleanup_remaining_tmpdirs():
  674. for tmpdir in TmpDirCleaner.remaining_tmpdirs:
  675. error_message = "error deleting tmp directory {}".format(tmpdir)
  676. shutil.rmtree(
  677. tmpdir,
  678. onerror=lambda *args: _log.error(error_message))
  679. class FigureCanvasPgf(FigureCanvasBase):
  680. filetypes = {"pgf": "LaTeX PGF picture",
  681. "pdf": "LaTeX compiled PGF picture",
  682. "png": "Portable Network Graphics", }
  683. def get_default_filetype(self):
  684. return 'pdf'
  685. @cbook._delete_parameter("3.2", "dryrun")
  686. def _print_pgf_to_fh(self, fh, *args,
  687. dryrun=False, bbox_inches_restore=None, **kwargs):
  688. if dryrun:
  689. renderer = RendererPgf(self.figure, None, dummy=True)
  690. self.figure.draw(renderer)
  691. return
  692. header_text = """%% Creator: Matplotlib, PGF backend
  693. %%
  694. %% To include the figure in your LaTeX document, write
  695. %% \\input{<filename>.pgf}
  696. %%
  697. %% Make sure the required packages are loaded in your preamble
  698. %% \\usepackage{pgf}
  699. %%
  700. %% and, on pdftex
  701. %% \\usepackage[utf8]{inputenc}\\DeclareUnicodeCharacter{2212}{-}
  702. %%
  703. %% or, on luatex and xetex
  704. %% \\usepackage{unicode-math}
  705. %%
  706. %% Figures using additional raster images can only be included by \\input if
  707. %% they are in the same directory as the main LaTeX file. For loading figures
  708. %% from other directories you can use the `import` package
  709. %% \\usepackage{import}
  710. %%
  711. %% and then include the figures with
  712. %% \\import{<path to file>}{<filename>.pgf}
  713. %%
  714. """
  715. # append the preamble used by the backend as a comment for debugging
  716. header_info_preamble = ["%% Matplotlib used the following preamble"]
  717. for line in get_preamble().splitlines():
  718. header_info_preamble.append("%% " + line)
  719. for line in get_fontspec().splitlines():
  720. header_info_preamble.append("%% " + line)
  721. header_info_preamble.append("%%")
  722. header_info_preamble = "\n".join(header_info_preamble)
  723. # get figure size in inch
  724. w, h = self.figure.get_figwidth(), self.figure.get_figheight()
  725. dpi = self.figure.get_dpi()
  726. # create pgfpicture environment and write the pgf code
  727. fh.write(header_text)
  728. fh.write(header_info_preamble)
  729. fh.write("\n")
  730. writeln(fh, r"\begingroup")
  731. writeln(fh, r"\makeatletter")
  732. writeln(fh, r"\begin{pgfpicture}")
  733. writeln(fh,
  734. r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
  735. % (w, h))
  736. writeln(fh, r"\pgfusepath{use as bounding box, clip}")
  737. renderer = MixedModeRenderer(self.figure, w, h, dpi,
  738. RendererPgf(self.figure, fh),
  739. bbox_inches_restore=bbox_inches_restore)
  740. self.figure.draw(renderer)
  741. # end the pgfpicture environment
  742. writeln(fh, r"\end{pgfpicture}")
  743. writeln(fh, r"\makeatother")
  744. writeln(fh, r"\endgroup")
  745. def print_pgf(self, fname_or_fh, *args, **kwargs):
  746. """
  747. Output pgf commands for drawing the figure so it can be included and
  748. rendered in latex documents.
  749. """
  750. if kwargs.get("dryrun", False):
  751. self._print_pgf_to_fh(None, *args, **kwargs)
  752. return
  753. with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:
  754. if not cbook.file_requires_unicode(file):
  755. file = codecs.getwriter("utf-8")(file)
  756. self._print_pgf_to_fh(file, *args, **kwargs)
  757. def _print_pdf_to_fh(self, fh, *args, **kwargs):
  758. w, h = self.figure.get_figwidth(), self.figure.get_figheight()
  759. try:
  760. # create temporary directory for compiling the figure
  761. tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_")
  762. fname_pgf = os.path.join(tmpdir, "figure.pgf")
  763. fname_tex = os.path.join(tmpdir, "figure.tex")
  764. fname_pdf = os.path.join(tmpdir, "figure.pdf")
  765. # print figure to pgf and compile it with latex
  766. self.print_pgf(fname_pgf, *args, **kwargs)
  767. latex_preamble = get_preamble()
  768. latex_fontspec = get_fontspec()
  769. latexcode = """
  770. \\documentclass[12pt]{minimal}
  771. \\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry}
  772. %s
  773. %s
  774. \\usepackage{pgf}
  775. \\begin{document}
  776. \\centering
  777. \\input{figure.pgf}
  778. \\end{document}""" % (w, h, latex_preamble, latex_fontspec)
  779. pathlib.Path(fname_tex).write_text(latexcode, encoding="utf-8")
  780. texcommand = rcParams["pgf.texsystem"]
  781. cbook._check_and_log_subprocess(
  782. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  783. "figure.tex"], _log, cwd=tmpdir)
  784. # copy file contents to target
  785. with open(fname_pdf, "rb") as fh_src:
  786. shutil.copyfileobj(fh_src, fh)
  787. finally:
  788. try:
  789. shutil.rmtree(tmpdir)
  790. except:
  791. TmpDirCleaner.add(tmpdir)
  792. def print_pdf(self, fname_or_fh, *args, **kwargs):
  793. """Use LaTeX to compile a Pgf generated figure to PDF."""
  794. if kwargs.get("dryrun", False):
  795. self._print_pgf_to_fh(None, *args, **kwargs)
  796. return
  797. with cbook.open_file_cm(fname_or_fh, "wb") as file:
  798. self._print_pdf_to_fh(file, *args, **kwargs)
  799. def _print_png_to_fh(self, fh, *args, **kwargs):
  800. converter = make_pdf_to_png_converter()
  801. try:
  802. # create temporary directory for pdf creation and png conversion
  803. tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_")
  804. fname_pdf = os.path.join(tmpdir, "figure.pdf")
  805. fname_png = os.path.join(tmpdir, "figure.png")
  806. # create pdf and try to convert it to png
  807. self.print_pdf(fname_pdf, *args, **kwargs)
  808. converter(fname_pdf, fname_png, dpi=self.figure.dpi)
  809. # copy file contents to target
  810. with open(fname_png, "rb") as fh_src:
  811. shutil.copyfileobj(fh_src, fh)
  812. finally:
  813. try:
  814. shutil.rmtree(tmpdir)
  815. except:
  816. TmpDirCleaner.add(tmpdir)
  817. def print_png(self, fname_or_fh, *args, **kwargs):
  818. """Use LaTeX to compile a pgf figure to pdf and convert it to png."""
  819. if kwargs.get("dryrun", False):
  820. self._print_pgf_to_fh(None, *args, **kwargs)
  821. return
  822. with cbook.open_file_cm(fname_or_fh, "wb") as file:
  823. self._print_png_to_fh(file, *args, **kwargs)
  824. def get_renderer(self):
  825. return RendererPgf(self.figure, None, dummy=True)
  826. class FigureManagerPgf(FigureManagerBase):
  827. pass
  828. @_Backend.export
  829. class _BackendPgf(_Backend):
  830. FigureCanvas = FigureCanvasPgf
  831. FigureManager = FigureManagerPgf
  832. def _cleanup_all():
  833. LatexManager._cleanup_remaining_instances()
  834. TmpDirCleaner.cleanup_remaining_tmpdirs()
  835. atexit.register(_cleanup_all)
  836. class PdfPages:
  837. """
  838. A multi-page PDF file using the pgf backend
  839. Examples
  840. --------
  841. >>> import matplotlib.pyplot as plt
  842. >>> # Initialize:
  843. >>> with PdfPages('foo.pdf') as pdf:
  844. ... # As many times as you like, create a figure fig and save it:
  845. ... fig = plt.figure()
  846. ... pdf.savefig(fig)
  847. ... # When no figure is specified the current figure is saved
  848. ... pdf.savefig()
  849. """
  850. __slots__ = (
  851. '_outputfile',
  852. 'keep_empty',
  853. '_tmpdir',
  854. '_basename',
  855. '_fname_tex',
  856. '_fname_pdf',
  857. '_n_figures',
  858. '_file',
  859. 'metadata',
  860. )
  861. def __init__(self, filename, *, keep_empty=True, metadata=None):
  862. """
  863. Create a new PdfPages object.
  864. Parameters
  865. ----------
  866. filename : str or path-like
  867. Plots using `PdfPages.savefig` will be written to a file at this
  868. location. Any older file with the same name is overwritten.
  869. keep_empty : bool, optional
  870. If set to False, then empty pdf files will be deleted automatically
  871. when closed.
  872. metadata : dictionary, optional
  873. Information dictionary object (see PDF reference section 10.2.1
  874. 'Document Information Dictionary'), e.g.:
  875. `{'Creator': 'My software', 'Author': 'Me',
  876. 'Title': 'Awesome fig'}`
  877. The standard keys are `'Title'`, `'Author'`, `'Subject'`,
  878. `'Keywords'`, `'Producer'`, `'Creator'` and `'Trapped'`.
  879. Values have been predefined for `'Creator'` and `'Producer'`.
  880. They can be removed by setting them to the empty string.
  881. """
  882. self._outputfile = filename
  883. self._n_figures = 0
  884. self.keep_empty = keep_empty
  885. self.metadata = metadata or {}
  886. # create temporary directory for compiling the figure
  887. self._tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_pdfpages_")
  888. self._basename = 'pdf_pages'
  889. self._fname_tex = os.path.join(self._tmpdir, self._basename + ".tex")
  890. self._fname_pdf = os.path.join(self._tmpdir, self._basename + ".pdf")
  891. self._file = open(self._fname_tex, 'wb')
  892. def _write_header(self, width_inches, height_inches):
  893. supported_keys = {
  894. 'title', 'author', 'subject', 'keywords', 'creator',
  895. 'producer', 'trapped'
  896. }
  897. infoDict = {
  898. 'creator': 'matplotlib %s, https://matplotlib.org' % __version__,
  899. 'producer': 'matplotlib pgf backend %s' % __version__,
  900. }
  901. metadata = {k.lower(): v for k, v in self.metadata.items()}
  902. infoDict.update(metadata)
  903. hyperref_options = ''
  904. for k, v in infoDict.items():
  905. if k not in supported_keys:
  906. raise ValueError(
  907. 'Not a supported pdf metadata field: "{}"'.format(k)
  908. )
  909. hyperref_options += 'pdf' + k + '={' + str(v) + '},'
  910. latex_preamble = get_preamble()
  911. latex_fontspec = get_fontspec()
  912. latex_header = r"""\PassOptionsToPackage{{
  913. {metadata}
  914. }}{{hyperref}}
  915. \RequirePackage{{hyperref}}
  916. \documentclass[12pt]{{minimal}}
  917. \usepackage[
  918. paperwidth={width}in,
  919. paperheight={height}in,
  920. margin=0in
  921. ]{{geometry}}
  922. {preamble}
  923. {fontspec}
  924. \usepackage{{pgf}}
  925. \setlength{{\parindent}}{{0pt}}
  926. \begin{{document}}%%
  927. """.format(
  928. width=width_inches,
  929. height=height_inches,
  930. preamble=latex_preamble,
  931. fontspec=latex_fontspec,
  932. metadata=hyperref_options,
  933. )
  934. self._file.write(latex_header.encode('utf-8'))
  935. def __enter__(self):
  936. return self
  937. def __exit__(self, exc_type, exc_val, exc_tb):
  938. self.close()
  939. def close(self):
  940. """
  941. Finalize this object, running LaTeX in a temporary directory
  942. and moving the final pdf file to *filename*.
  943. """
  944. self._file.write(rb'\end{document}\n')
  945. self._file.close()
  946. if self._n_figures > 0:
  947. try:
  948. self._run_latex()
  949. finally:
  950. try:
  951. shutil.rmtree(self._tmpdir)
  952. except:
  953. TmpDirCleaner.add(self._tmpdir)
  954. elif self.keep_empty:
  955. open(self._outputfile, 'wb').close()
  956. def _run_latex(self):
  957. texcommand = rcParams["pgf.texsystem"]
  958. cbook._check_and_log_subprocess(
  959. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  960. os.path.basename(self._fname_tex)],
  961. _log, cwd=self._tmpdir)
  962. # copy file contents to target
  963. shutil.copyfile(self._fname_pdf, self._outputfile)
  964. def savefig(self, figure=None, **kwargs):
  965. """
  966. Saves a `.Figure` to this file as a new page.
  967. Any other keyword arguments are passed to `~.Figure.savefig`.
  968. Parameters
  969. ----------
  970. figure : `.Figure` or int, optional
  971. Specifies what figure is saved to file. If not specified, the
  972. active figure is saved. If a `.Figure` instance is provided, this
  973. figure is saved. If an int is specified, the figure instance to
  974. save is looked up by number.
  975. """
  976. if not isinstance(figure, Figure):
  977. if figure is None:
  978. manager = Gcf.get_active()
  979. else:
  980. manager = Gcf.get_fig_manager(figure)
  981. if manager is None:
  982. raise ValueError("No figure {}".format(figure))
  983. figure = manager.canvas.figure
  984. try:
  985. orig_canvas = figure.canvas
  986. figure.canvas = FigureCanvasPgf(figure)
  987. width, height = figure.get_size_inches()
  988. if self._n_figures == 0:
  989. self._write_header(width, height)
  990. else:
  991. # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and
  992. # luatex<0.85; they were renamed to \pagewidth and \pageheight
  993. # on luatex>=0.85.
  994. self._file.write(
  995. br'\newpage'
  996. br'\ifdefined\pdfpagewidth\pdfpagewidth'
  997. br'\else\pagewidth\fi=%ain'
  998. br'\ifdefined\pdfpageheight\pdfpageheight'
  999. br'\else\pageheight\fi=%ain'
  1000. b'%%\n' % (width, height)
  1001. )
  1002. figure.savefig(self._file, format="pgf", **kwargs)
  1003. self._n_figures += 1
  1004. finally:
  1005. figure.canvas = orig_canvas
  1006. def get_pagecount(self):
  1007. """
  1008. Returns the current number of pages in the multipage pdf file.
  1009. """
  1010. return self._n_figures