backend_pgf.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. import codecs
  2. import datetime
  3. import functools
  4. from io import BytesIO
  5. import logging
  6. import math
  7. import os
  8. import pathlib
  9. import shutil
  10. import subprocess
  11. from tempfile import TemporaryDirectory
  12. import weakref
  13. from PIL import Image
  14. import matplotlib as mpl
  15. from matplotlib import _api, cbook, font_manager as fm
  16. from matplotlib.backend_bases import (
  17. _Backend, FigureCanvasBase, FigureManagerBase, RendererBase
  18. )
  19. from matplotlib.backends.backend_mixed import MixedModeRenderer
  20. from matplotlib.backends.backend_pdf import (
  21. _create_pdf_info_dict, _datetime_to_pdf)
  22. from matplotlib.path import Path
  23. from matplotlib.figure import Figure
  24. from matplotlib._pylab_helpers import Gcf
  25. _log = logging.getLogger(__name__)
  26. # Note: When formatting floating point values, it is important to use the
  27. # %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
  28. # which is not recognized by TeX.
  29. def _get_preamble():
  30. """Prepare a LaTeX preamble based on the rcParams configuration."""
  31. preamble = [
  32. # Remove Matplotlib's custom command \mathdefault. (Not using
  33. # \mathnormal instead since this looks odd with Computer Modern.)
  34. r"\def\mathdefault#1{#1}",
  35. # Use displaystyle for all math.
  36. r"\everymath=\expandafter{\the\everymath\displaystyle}",
  37. # Allow pgf.preamble to override the above definitions.
  38. mpl.rcParams["pgf.preamble"],
  39. ]
  40. if mpl.rcParams["pgf.texsystem"] != "pdflatex":
  41. preamble.append("\\usepackage{fontspec}")
  42. if mpl.rcParams["pgf.rcfonts"]:
  43. families = ["serif", "sans\\-serif", "monospace"]
  44. commands = ["setmainfont", "setsansfont", "setmonofont"]
  45. for family, command in zip(families, commands):
  46. # 1) Forward slashes also work on Windows, so don't mess with
  47. # backslashes. 2) The dirname needs to include a separator.
  48. path = pathlib.Path(fm.findfont(family))
  49. preamble.append(r"\%s{%s}[Path=\detokenize{%s/}]" % (
  50. command, path.name, path.parent.as_posix()))
  51. preamble.append(mpl.texmanager._usepackage_if_not_loaded(
  52. "underscore", option="strings")) # Documented as "must come last".
  53. return "\n".join(preamble)
  54. # It's better to use only one unit for all coordinates, since the
  55. # arithmetic in latex seems to produce inaccurate conversions.
  56. latex_pt_to_in = 1. / 72.27
  57. latex_in_to_pt = 1. / latex_pt_to_in
  58. mpl_pt_to_in = 1. / 72.
  59. mpl_in_to_pt = 1. / mpl_pt_to_in
  60. def _tex_escape(text):
  61. r"""
  62. Do some necessary and/or useful substitutions for texts to be included in
  63. LaTeX documents.
  64. """
  65. return text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")
  66. def _writeln(fh, line):
  67. # Ending lines with a % prevents TeX from inserting spurious spaces
  68. # (https://tex.stackexchange.com/questions/7453).
  69. fh.write(line)
  70. fh.write("%\n")
  71. def _escape_and_apply_props(s, prop):
  72. """
  73. Generate a TeX string that renders string *s* with font properties *prop*,
  74. also applying any required escapes to *s*.
  75. """
  76. commands = []
  77. families = {"serif": r"\rmfamily", "sans": r"\sffamily",
  78. "sans-serif": r"\sffamily", "monospace": r"\ttfamily"}
  79. family = prop.get_family()[0]
  80. if family in families:
  81. commands.append(families[family])
  82. elif (any(font.name == family for font in fm.fontManager.ttflist)
  83. and mpl.rcParams["pgf.texsystem"] != "pdflatex"):
  84. commands.append(r"\setmainfont{%s}\rmfamily" % family)
  85. else:
  86. _log.warning("Ignoring unknown font: %s", family)
  87. size = prop.get_size_in_points()
  88. commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))
  89. styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}
  90. commands.append(styles[prop.get_style()])
  91. boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",
  92. "extra bold", "black"]
  93. if prop.get_weight() in boldstyles:
  94. commands.append(r"\bfseries")
  95. commands.append(r"\selectfont")
  96. return (
  97. "{"
  98. + "".join(commands)
  99. + r"\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}"
  100. # It should normally be enough to set the catcode of % to 12 ("normal
  101. # character"); this works on TeXLive 2021 but not on 2018, so we just
  102. # make it active too.
  103. + r"\catcode`\%=\active\def%{\%}"
  104. + _tex_escape(s)
  105. + "}"
  106. )
  107. def _metadata_to_str(key, value):
  108. """Convert metadata key/value to a form that hyperref accepts."""
  109. if isinstance(value, datetime.datetime):
  110. value = _datetime_to_pdf(value)
  111. elif key == 'Trapped':
  112. value = value.name.decode('ascii')
  113. else:
  114. value = str(value)
  115. return f'{key}={{{value}}}'
  116. def make_pdf_to_png_converter():
  117. """Return a function that converts a pdf file to a png file."""
  118. try:
  119. mpl._get_executable_info("pdftocairo")
  120. except mpl.ExecutableNotFoundError:
  121. pass
  122. else:
  123. return lambda pdffile, pngfile, dpi: subprocess.check_output(
  124. ["pdftocairo", "-singlefile", "-transp", "-png", "-r", "%d" % dpi,
  125. pdffile, os.path.splitext(pngfile)[0]],
  126. stderr=subprocess.STDOUT)
  127. try:
  128. gs_info = mpl._get_executable_info("gs")
  129. except mpl.ExecutableNotFoundError:
  130. pass
  131. else:
  132. return lambda pdffile, pngfile, dpi: subprocess.check_output(
  133. [gs_info.executable,
  134. '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
  135. '-dUseCIEColor', '-dTextAlphaBits=4',
  136. '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
  137. '-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile,
  138. '-r%d' % dpi, pdffile],
  139. stderr=subprocess.STDOUT)
  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. def __str__(self):
  146. s, = self.args
  147. if self.latex_output:
  148. s += "\n" + self.latex_output
  149. return s
  150. class LatexManager:
  151. """
  152. The LatexManager opens an instance of the LaTeX application for
  153. determining the metrics of text elements. The LaTeX environment can be
  154. modified by setting fonts and/or a custom preamble in `.rcParams`.
  155. """
  156. @staticmethod
  157. def _build_latex_header():
  158. latex_header = [
  159. r"\documentclass{article}",
  160. # Include TeX program name as a comment for cache invalidation.
  161. # TeX does not allow this to be the first line.
  162. rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",
  163. # Test whether \includegraphics supports interpolate option.
  164. r"\usepackage{graphicx}",
  165. _get_preamble(),
  166. r"\begin{document}",
  167. r"\typeout{pgf_backend_query_start}",
  168. ]
  169. return "\n".join(latex_header)
  170. @classmethod
  171. def _get_cached_or_new(cls):
  172. """
  173. Return the previous LatexManager if the header and tex system did not
  174. change, or a new instance otherwise.
  175. """
  176. return cls._get_cached_or_new_impl(cls._build_latex_header())
  177. @classmethod
  178. @functools.lru_cache(1)
  179. def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
  180. return cls()
  181. def _stdin_writeln(self, s):
  182. if self.latex is None:
  183. self._setup_latex_process()
  184. self.latex.stdin.write(s)
  185. self.latex.stdin.write("\n")
  186. self.latex.stdin.flush()
  187. def _expect(self, s):
  188. s = list(s)
  189. chars = []
  190. while True:
  191. c = self.latex.stdout.read(1)
  192. chars.append(c)
  193. if chars[-len(s):] == s:
  194. break
  195. if not c:
  196. self.latex.kill()
  197. self.latex = None
  198. raise LatexError("LaTeX process halted", "".join(chars))
  199. return "".join(chars)
  200. def _expect_prompt(self):
  201. return self._expect("\n*")
  202. def __init__(self):
  203. # create a tmp directory for running latex, register it for deletion
  204. self._tmpdir = TemporaryDirectory()
  205. self.tmpdir = self._tmpdir.name
  206. self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup)
  207. # test the LaTeX setup to ensure a clean startup of the subprocess
  208. self._setup_latex_process(expect_reply=False)
  209. stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n")
  210. if self.latex.returncode != 0:
  211. raise LatexError(
  212. f"LaTeX errored (probably missing font or error in preamble) "
  213. f"while processing the following input:\n"
  214. f"{self._build_latex_header()}",
  215. stdout)
  216. self.latex = None # Will be set up on first use.
  217. # Per-instance cache.
  218. self._get_box_metrics = functools.lru_cache(self._get_box_metrics)
  219. def _setup_latex_process(self, *, expect_reply=True):
  220. # Open LaTeX process for real work; register it for deletion. On
  221. # Windows, we must ensure that the subprocess has quit before being
  222. # able to delete the tmpdir in which it runs; in order to do so, we
  223. # must first `kill()` it, and then `communicate()` with it.
  224. try:
  225. self.latex = subprocess.Popen(
  226. [mpl.rcParams["pgf.texsystem"], "-halt-on-error"],
  227. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  228. encoding="utf-8", cwd=self.tmpdir)
  229. except FileNotFoundError as err:
  230. raise RuntimeError(
  231. f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change "
  232. f"rcParams['pgf.texsystem'] to an available TeX implementation"
  233. ) from err
  234. except OSError as err:
  235. raise RuntimeError(
  236. f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err
  237. def finalize_latex(latex):
  238. latex.kill()
  239. latex.communicate()
  240. self._finalize_latex = weakref.finalize(
  241. self, finalize_latex, self.latex)
  242. # write header with 'pgf_backend_query_start' token
  243. self._stdin_writeln(self._build_latex_header())
  244. if expect_reply: # read until 'pgf_backend_query_start' token appears
  245. self._expect("*pgf_backend_query_start")
  246. self._expect_prompt()
  247. def get_width_height_descent(self, text, prop):
  248. """
  249. Get the width, total height, and descent (in TeX points) for a text
  250. typeset by the current LaTeX environment.
  251. """
  252. return self._get_box_metrics(_escape_and_apply_props(text, prop))
  253. def _get_box_metrics(self, tex):
  254. """
  255. Get the width, total height and descent (in TeX points) for a TeX
  256. command's output in the current LaTeX environment.
  257. """
  258. # This method gets wrapped in __init__ for per-instance caching.
  259. self._stdin_writeln( # Send textbox to TeX & request metrics typeout.
  260. # \sbox doesn't handle catcode assignments inside its argument,
  261. # so repeat the assignment of the catcode of "^" and "%" outside.
  262. r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}"
  263. r"\typeout{\the\wd0,\the\ht0,\the\dp0}}"
  264. % tex)
  265. try:
  266. answer = self._expect_prompt()
  267. except LatexError as err:
  268. # Here and below, use '{}' instead of {!r} to avoid doubling all
  269. # backslashes.
  270. raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
  271. .format(tex, err.latex_output)) from err
  272. try:
  273. # Parse metrics from the answer string. Last line is prompt, and
  274. # next-to-last-line is blank line from \typeout.
  275. width, height, offset = answer.splitlines()[-3].split(",")
  276. except Exception as err:
  277. raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
  278. .format(tex, answer)) from err
  279. w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
  280. # The height returned from LaTeX goes from base to top;
  281. # the height Matplotlib expects goes from bottom to top.
  282. return w, h + o, o
  283. @functools.lru_cache(1)
  284. def _get_image_inclusion_command():
  285. man = LatexManager._get_cached_or_new()
  286. man._stdin_writeln(
  287. r"\includegraphics[interpolate=true]{%s}"
  288. # Don't mess with backslashes on Windows.
  289. % cbook._get_data_path("images/matplotlib.png").as_posix())
  290. try:
  291. man._expect_prompt()
  292. return r"\includegraphics"
  293. except LatexError:
  294. # Discard the broken manager.
  295. LatexManager._get_cached_or_new_impl.cache_clear()
  296. return r"\pgfimage"
  297. class RendererPgf(RendererBase):
  298. def __init__(self, figure, fh):
  299. """
  300. Create a new PGF renderer that translates any drawing instruction
  301. into text commands to be interpreted in a latex pgfpicture environment.
  302. Attributes
  303. ----------
  304. figure : `~matplotlib.figure.Figure`
  305. Matplotlib figure to initialize height, width and dpi from.
  306. fh : file-like
  307. File handle for the output of the drawing commands.
  308. """
  309. super().__init__()
  310. self.dpi = figure.dpi
  311. self.fh = fh
  312. self.figure = figure
  313. self.image_counter = 0
  314. def draw_markers(self, gc, marker_path, marker_trans, path, trans,
  315. rgbFace=None):
  316. # docstring inherited
  317. _writeln(self.fh, r"\begin{pgfscope}")
  318. # convert from display units to in
  319. f = 1. / self.dpi
  320. # set style and clip
  321. self._print_pgf_clip(gc)
  322. self._print_pgf_path_styles(gc, rgbFace)
  323. # build marker definition
  324. bl, tr = marker_path.get_extents(marker_trans).get_points()
  325. coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f
  326. _writeln(self.fh,
  327. r"\pgfsys@defobject{currentmarker}"
  328. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)
  329. self._print_pgf_path(None, marker_path, marker_trans)
  330. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  331. fill=rgbFace is not None)
  332. _writeln(self.fh, r"}")
  333. maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
  334. clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
  335. # draw marker for each vertex
  336. for point, code in path.iter_segments(trans, simplify=False,
  337. clip=clip):
  338. x, y = point[0] * f, point[1] * f
  339. _writeln(self.fh, r"\begin{pgfscope}")
  340. _writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))
  341. _writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")
  342. _writeln(self.fh, r"\end{pgfscope}")
  343. _writeln(self.fh, r"\end{pgfscope}")
  344. def draw_path(self, gc, path, transform, rgbFace=None):
  345. # docstring inherited
  346. _writeln(self.fh, r"\begin{pgfscope}")
  347. # draw the path
  348. self._print_pgf_clip(gc)
  349. self._print_pgf_path_styles(gc, rgbFace)
  350. self._print_pgf_path(gc, path, transform, rgbFace)
  351. self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
  352. fill=rgbFace is not None)
  353. _writeln(self.fh, r"\end{pgfscope}")
  354. # if present, draw pattern on top
  355. if gc.get_hatch():
  356. _writeln(self.fh, r"\begin{pgfscope}")
  357. self._print_pgf_path_styles(gc, rgbFace)
  358. # combine clip and path for clipping
  359. self._print_pgf_clip(gc)
  360. self._print_pgf_path(gc, path, transform, rgbFace)
  361. _writeln(self.fh, r"\pgfusepath{clip}")
  362. # build pattern definition
  363. _writeln(self.fh,
  364. r"\pgfsys@defobject{currentpattern}"
  365. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")
  366. _writeln(self.fh, r"\begin{pgfscope}")
  367. _writeln(self.fh,
  368. r"\pgfpathrectangle"
  369. r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")
  370. _writeln(self.fh, r"\pgfusepath{clip}")
  371. scale = mpl.transforms.Affine2D().scale(self.dpi)
  372. self._print_pgf_path(None, gc.get_hatch_path(), scale)
  373. self._pgf_path_draw(stroke=True)
  374. _writeln(self.fh, r"\end{pgfscope}")
  375. _writeln(self.fh, r"}")
  376. # repeat pattern, filling the bounding rect of the path
  377. f = 1. / self.dpi
  378. (xmin, ymin), (xmax, ymax) = \
  379. path.get_extents(transform).get_points()
  380. xmin, xmax = f * xmin, f * xmax
  381. ymin, ymax = f * ymin, f * ymax
  382. repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)
  383. _writeln(self.fh,
  384. r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))
  385. for iy in range(repy):
  386. for ix in range(repx):
  387. _writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")
  388. _writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")
  389. _writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)
  390. _writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")
  391. _writeln(self.fh, r"\end{pgfscope}")
  392. def _print_pgf_clip(self, gc):
  393. f = 1. / self.dpi
  394. # check for clip box
  395. bbox = gc.get_clip_rectangle()
  396. if bbox:
  397. p1, p2 = bbox.get_points()
  398. w, h = p2 - p1
  399. coords = p1[0] * f, p1[1] * f, w * f, h * f
  400. _writeln(self.fh,
  401. r"\pgfpathrectangle"
  402. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  403. % coords)
  404. _writeln(self.fh, r"\pgfusepath{clip}")
  405. # check for clip path
  406. clippath, clippath_trans = gc.get_clip_path()
  407. if clippath is not None:
  408. self._print_pgf_path(gc, clippath, clippath_trans)
  409. _writeln(self.fh, r"\pgfusepath{clip}")
  410. def _print_pgf_path_styles(self, gc, rgbFace):
  411. # cap style
  412. capstyles = {"butt": r"\pgfsetbuttcap",
  413. "round": r"\pgfsetroundcap",
  414. "projecting": r"\pgfsetrectcap"}
  415. _writeln(self.fh, capstyles[gc.get_capstyle()])
  416. # join style
  417. joinstyles = {"miter": r"\pgfsetmiterjoin",
  418. "round": r"\pgfsetroundjoin",
  419. "bevel": r"\pgfsetbeveljoin"}
  420. _writeln(self.fh, joinstyles[gc.get_joinstyle()])
  421. # filling
  422. has_fill = rgbFace is not None
  423. if gc.get_forced_alpha():
  424. fillopacity = strokeopacity = gc.get_alpha()
  425. else:
  426. strokeopacity = gc.get_rgb()[3]
  427. fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0
  428. if has_fill:
  429. _writeln(self.fh,
  430. r"\definecolor{currentfill}{rgb}{%f,%f,%f}"
  431. % tuple(rgbFace[:3]))
  432. _writeln(self.fh, r"\pgfsetfillcolor{currentfill}")
  433. if has_fill and fillopacity != 1.0:
  434. _writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)
  435. # linewidth and color
  436. lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt
  437. stroke_rgba = gc.get_rgb()
  438. _writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)
  439. _writeln(self.fh,
  440. r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"
  441. % stroke_rgba[:3])
  442. _writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")
  443. if strokeopacity != 1.0:
  444. _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)
  445. # line style
  446. dash_offset, dash_list = gc.get_dashes()
  447. if dash_list is None:
  448. _writeln(self.fh, r"\pgfsetdash{}{0pt}")
  449. else:
  450. _writeln(self.fh,
  451. r"\pgfsetdash{%s}{%fpt}"
  452. % ("".join(r"{%fpt}" % dash for dash in dash_list),
  453. dash_offset))
  454. def _print_pgf_path(self, gc, path, transform, rgbFace=None):
  455. f = 1. / self.dpi
  456. # check for clip box / ignore clip for filled paths
  457. bbox = gc.get_clip_rectangle() if gc else None
  458. maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
  459. if bbox and (rgbFace is None):
  460. p1, p2 = bbox.get_points()
  461. clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord),
  462. min(p2[0], maxcoord), min(p2[1], maxcoord))
  463. else:
  464. clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
  465. # build path
  466. for points, code in path.iter_segments(transform, clip=clip):
  467. if code == Path.MOVETO:
  468. x, y = tuple(points)
  469. _writeln(self.fh,
  470. r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
  471. (f * x, f * y))
  472. elif code == Path.CLOSEPOLY:
  473. _writeln(self.fh, r"\pgfpathclose")
  474. elif code == Path.LINETO:
  475. x, y = tuple(points)
  476. _writeln(self.fh,
  477. r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
  478. (f * x, f * y))
  479. elif code == Path.CURVE3:
  480. cx, cy, px, py = tuple(points)
  481. coords = cx * f, cy * f, px * f, py * f
  482. _writeln(self.fh,
  483. r"\pgfpathquadraticcurveto"
  484. r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
  485. % coords)
  486. elif code == Path.CURVE4:
  487. c1x, c1y, c2x, c2y, px, py = tuple(points)
  488. coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
  489. _writeln(self.fh,
  490. r"\pgfpathcurveto"
  491. r"{\pgfqpoint{%fin}{%fin}}"
  492. r"{\pgfqpoint{%fin}{%fin}}"
  493. r"{\pgfqpoint{%fin}{%fin}}"
  494. % coords)
  495. # apply pgf decorators
  496. sketch_params = gc.get_sketch_params() if gc else None
  497. if sketch_params is not None:
  498. # Only "length" directly maps to "segment length" in PGF's API.
  499. # PGF uses "amplitude" to pass the combined deviation in both x-
  500. # and y-direction, while matplotlib only varies the length of the
  501. # wiggle along the line ("randomness" and "length" parameters)
  502. # and has a separate "scale" argument for the amplitude.
  503. # -> Use "randomness" as PRNG seed to allow the user to force the
  504. # same shape on multiple sketched lines
  505. scale, length, randomness = sketch_params
  506. if scale is not None:
  507. # make matplotlib and PGF rendering visually similar
  508. length *= 0.5
  509. scale *= 2
  510. # PGF guarantees that repeated loading is a no-op
  511. _writeln(self.fh, r"\usepgfmodule{decorations}")
  512. _writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}")
  513. _writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, "
  514. f"segment length = {(length * f):f}in, "
  515. f"amplitude = {(scale * f):f}in}}")
  516. _writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}")
  517. _writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}")
  518. def _pgf_path_draw(self, stroke=True, fill=False):
  519. actions = []
  520. if stroke:
  521. actions.append("stroke")
  522. if fill:
  523. actions.append("fill")
  524. _writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))
  525. def option_scale_image(self):
  526. # docstring inherited
  527. return True
  528. def option_image_nocomposite(self):
  529. # docstring inherited
  530. return not mpl.rcParams['image.composite_image']
  531. def draw_image(self, gc, x, y, im, transform=None):
  532. # docstring inherited
  533. h, w = im.shape[:2]
  534. if w == 0 or h == 0:
  535. return
  536. if not os.path.exists(getattr(self.fh, "name", "")):
  537. raise ValueError(
  538. "streamed pgf-code does not support raster graphics, consider "
  539. "using the pgf-to-pdf option")
  540. # save the images to png files
  541. path = pathlib.Path(self.fh.name)
  542. fname_img = "%s-img%d.png" % (path.stem, self.image_counter)
  543. Image.fromarray(im[::-1]).save(path.parent / fname_img)
  544. self.image_counter += 1
  545. # reference the image in the pgf picture
  546. _writeln(self.fh, r"\begin{pgfscope}")
  547. self._print_pgf_clip(gc)
  548. f = 1. / self.dpi # from display coords to inch
  549. if transform is None:
  550. _writeln(self.fh,
  551. r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
  552. w, h = w * f, h * f
  553. else:
  554. tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
  555. _writeln(self.fh,
  556. r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
  557. (tr1 * f, tr2 * f, tr3 * f, tr4 * f,
  558. (tr5 + x) * f, (tr6 + y) * f))
  559. w = h = 1 # scale is already included in the transform
  560. interp = str(transform is None).lower() # interpolation in PDF reader
  561. _writeln(self.fh,
  562. r"\pgftext[left,bottom]"
  563. r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %
  564. (_get_image_inclusion_command(),
  565. interp, w, h, fname_img))
  566. _writeln(self.fh, r"\end{pgfscope}")
  567. def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
  568. # docstring inherited
  569. self.draw_text(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext)
  570. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  571. # docstring inherited
  572. # prepare string for tex
  573. s = _escape_and_apply_props(s, prop)
  574. _writeln(self.fh, r"\begin{pgfscope}")
  575. self._print_pgf_clip(gc)
  576. alpha = gc.get_alpha()
  577. if alpha != 1.0:
  578. _writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)
  579. _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)
  580. rgb = tuple(gc.get_rgb())[:3]
  581. _writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)
  582. _writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")
  583. _writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
  584. s = r"\color{textcolor}" + s
  585. dpi = self.figure.dpi
  586. text_args = []
  587. if mtext and (
  588. (angle == 0 or
  589. mtext.get_rotation_mode() == "anchor") and
  590. mtext.get_verticalalignment() != "center_baseline"):
  591. # if text anchoring can be supported, get the original coordinates
  592. # and add alignment information
  593. pos = mtext.get_unitless_position()
  594. x, y = mtext.get_transform().transform(pos)
  595. halign = {"left": "left", "right": "right", "center": ""}
  596. valign = {"top": "top", "bottom": "bottom",
  597. "baseline": "base", "center": ""}
  598. text_args.extend([
  599. f"x={x/dpi:f}in",
  600. f"y={y/dpi:f}in",
  601. halign[mtext.get_horizontalalignment()],
  602. valign[mtext.get_verticalalignment()],
  603. ])
  604. else:
  605. # if not, use the text layout provided by Matplotlib.
  606. text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")
  607. if angle != 0:
  608. text_args.append("rotate=%f" % angle)
  609. _writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))
  610. _writeln(self.fh, r"\end{pgfscope}")
  611. def get_text_width_height_descent(self, s, prop, ismath):
  612. # docstring inherited
  613. # get text metrics in units of latex pt, convert to display units
  614. w, h, d = (LatexManager._get_cached_or_new()
  615. .get_width_height_descent(s, prop))
  616. # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in
  617. # but having a little bit more space around the text looks better,
  618. # plus the bounding box reported by LaTeX is VERY narrow
  619. f = mpl_pt_to_in * self.dpi
  620. return w * f, h * f, d * f
  621. def flipy(self):
  622. # docstring inherited
  623. return False
  624. def get_canvas_width_height(self):
  625. # docstring inherited
  626. return (self.figure.get_figwidth() * self.dpi,
  627. self.figure.get_figheight() * self.dpi)
  628. def points_to_pixels(self, points):
  629. # docstring inherited
  630. return points * mpl_pt_to_in * self.dpi
  631. class FigureCanvasPgf(FigureCanvasBase):
  632. filetypes = {"pgf": "LaTeX PGF picture",
  633. "pdf": "LaTeX compiled PGF picture",
  634. "png": "Portable Network Graphics", }
  635. def get_default_filetype(self):
  636. return 'pdf'
  637. def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None):
  638. header_text = """%% Creator: Matplotlib, PGF backend
  639. %%
  640. %% To include the figure in your LaTeX document, write
  641. %% \\input{<filename>.pgf}
  642. %%
  643. %% Make sure the required packages are loaded in your preamble
  644. %% \\usepackage{pgf}
  645. %%
  646. %% Also ensure that all the required font packages are loaded; for instance,
  647. %% the lmodern package is sometimes necessary when using math font.
  648. %% \\usepackage{lmodern}
  649. %%
  650. %% Figures using additional raster images can only be included by \\input if
  651. %% they are in the same directory as the main LaTeX file. For loading figures
  652. %% from other directories you can use the `import` package
  653. %% \\usepackage{import}
  654. %%
  655. %% and then include the figures with
  656. %% \\import{<path to file>}{<filename>.pgf}
  657. %%
  658. """
  659. # append the preamble used by the backend as a comment for debugging
  660. header_info_preamble = ["%% Matplotlib used the following preamble"]
  661. for line in _get_preamble().splitlines():
  662. header_info_preamble.append("%% " + line)
  663. header_info_preamble.append("%%")
  664. header_info_preamble = "\n".join(header_info_preamble)
  665. # get figure size in inch
  666. w, h = self.figure.get_figwidth(), self.figure.get_figheight()
  667. dpi = self.figure.dpi
  668. # create pgfpicture environment and write the pgf code
  669. fh.write(header_text)
  670. fh.write(header_info_preamble)
  671. fh.write("\n")
  672. _writeln(fh, r"\begingroup")
  673. _writeln(fh, r"\makeatletter")
  674. _writeln(fh, r"\begin{pgfpicture}")
  675. _writeln(fh,
  676. r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
  677. % (w, h))
  678. _writeln(fh, r"\pgfusepath{use as bounding box, clip}")
  679. renderer = MixedModeRenderer(self.figure, w, h, dpi,
  680. RendererPgf(self.figure, fh),
  681. bbox_inches_restore=bbox_inches_restore)
  682. self.figure.draw(renderer)
  683. # end the pgfpicture environment
  684. _writeln(fh, r"\end{pgfpicture}")
  685. _writeln(fh, r"\makeatother")
  686. _writeln(fh, r"\endgroup")
  687. def print_pgf(self, fname_or_fh, **kwargs):
  688. """
  689. Output pgf macros for drawing the figure so it can be included and
  690. rendered in latex documents.
  691. """
  692. with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:
  693. if not cbook.file_requires_unicode(file):
  694. file = codecs.getwriter("utf-8")(file)
  695. self._print_pgf_to_fh(file, **kwargs)
  696. def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
  697. """Use LaTeX to compile a pgf generated figure to pdf."""
  698. w, h = self.figure.get_size_inches()
  699. info_dict = _create_pdf_info_dict('pgf', metadata or {})
  700. pdfinfo = ','.join(
  701. _metadata_to_str(k, v) for k, v in info_dict.items())
  702. # print figure to pgf and compile it with latex
  703. with TemporaryDirectory() as tmpdir:
  704. tmppath = pathlib.Path(tmpdir)
  705. self.print_pgf(tmppath / "figure.pgf", **kwargs)
  706. (tmppath / "figure.tex").write_text(
  707. "\n".join([
  708. r"\documentclass[12pt]{article}",
  709. r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
  710. r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
  711. % (w, h),
  712. r"\usepackage{pgf}",
  713. _get_preamble(),
  714. r"\begin{document}",
  715. r"\centering",
  716. r"\input{figure.pgf}",
  717. r"\end{document}",
  718. ]), encoding="utf-8")
  719. texcommand = mpl.rcParams["pgf.texsystem"]
  720. cbook._check_and_log_subprocess(
  721. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  722. "figure.tex"], _log, cwd=tmpdir)
  723. with (tmppath / "figure.pdf").open("rb") as orig, \
  724. cbook.open_file_cm(fname_or_fh, "wb") as dest:
  725. shutil.copyfileobj(orig, dest) # copy file contents to target
  726. def print_png(self, fname_or_fh, **kwargs):
  727. """Use LaTeX to compile a pgf figure to pdf and convert it to png."""
  728. converter = make_pdf_to_png_converter()
  729. with TemporaryDirectory() as tmpdir:
  730. tmppath = pathlib.Path(tmpdir)
  731. pdf_path = tmppath / "figure.pdf"
  732. png_path = tmppath / "figure.png"
  733. self.print_pdf(pdf_path, **kwargs)
  734. converter(pdf_path, png_path, dpi=self.figure.dpi)
  735. with png_path.open("rb") as orig, \
  736. cbook.open_file_cm(fname_or_fh, "wb") as dest:
  737. shutil.copyfileobj(orig, dest) # copy file contents to target
  738. def get_renderer(self):
  739. return RendererPgf(self.figure, None)
  740. def draw(self):
  741. self.figure.draw_without_rendering()
  742. return super().draw()
  743. FigureManagerPgf = FigureManagerBase
  744. @_Backend.export
  745. class _BackendPgf(_Backend):
  746. FigureCanvas = FigureCanvasPgf
  747. class PdfPages:
  748. """
  749. A multi-page PDF file using the pgf backend
  750. Examples
  751. --------
  752. >>> import matplotlib.pyplot as plt
  753. >>> # Initialize:
  754. >>> with PdfPages('foo.pdf') as pdf:
  755. ... # As many times as you like, create a figure fig and save it:
  756. ... fig = plt.figure()
  757. ... pdf.savefig(fig)
  758. ... # When no figure is specified the current figure is saved
  759. ... pdf.savefig()
  760. """
  761. _UNSET = object()
  762. def __init__(self, filename, *, keep_empty=_UNSET, metadata=None):
  763. """
  764. Create a new PdfPages object.
  765. Parameters
  766. ----------
  767. filename : str or path-like
  768. Plots using `PdfPages.savefig` will be written to a file at this
  769. location. Any older file with the same name is overwritten.
  770. keep_empty : bool, default: True
  771. If set to False, then empty pdf files will be deleted automatically
  772. when closed.
  773. metadata : dict, optional
  774. Information dictionary object (see PDF reference section 10.2.1
  775. 'Document Information Dictionary'), e.g.:
  776. ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
  777. The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
  778. 'Creator', 'Producer', 'CreationDate', 'ModDate', and
  779. 'Trapped'. Values have been predefined for 'Creator', 'Producer'
  780. and 'CreationDate'. They can be removed by setting them to `None`.
  781. Note that some versions of LaTeX engines may ignore the 'Producer'
  782. key and set it to themselves.
  783. """
  784. self._output_name = filename
  785. self._n_figures = 0
  786. if keep_empty and keep_empty is not self._UNSET:
  787. _api.warn_deprecated("3.8", message=(
  788. "Keeping empty pdf files is deprecated since %(since)s and support "
  789. "will be removed %(removal)s."))
  790. self._keep_empty = keep_empty
  791. self._metadata = (metadata or {}).copy()
  792. self._info_dict = _create_pdf_info_dict('pgf', self._metadata)
  793. self._file = BytesIO()
  794. keep_empty = _api.deprecate_privatize_attribute("3.8")
  795. def _write_header(self, width_inches, height_inches):
  796. pdfinfo = ','.join(
  797. _metadata_to_str(k, v) for k, v in self._info_dict.items())
  798. latex_header = "\n".join([
  799. r"\documentclass[12pt]{article}",
  800. r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
  801. r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
  802. % (width_inches, height_inches),
  803. r"\usepackage{pgf}",
  804. _get_preamble(),
  805. r"\setlength{\parindent}{0pt}",
  806. r"\begin{document}%",
  807. ])
  808. self._file.write(latex_header.encode('utf-8'))
  809. def __enter__(self):
  810. return self
  811. def __exit__(self, exc_type, exc_val, exc_tb):
  812. self.close()
  813. def close(self):
  814. """
  815. Finalize this object, running LaTeX in a temporary directory
  816. and moving the final pdf file to *filename*.
  817. """
  818. self._file.write(rb'\end{document}\n')
  819. if self._n_figures > 0:
  820. self._run_latex()
  821. elif self._keep_empty:
  822. _api.warn_deprecated("3.8", message=(
  823. "Keeping empty pdf files is deprecated since %(since)s and support "
  824. "will be removed %(removal)s."))
  825. open(self._output_name, 'wb').close()
  826. self._file.close()
  827. def _run_latex(self):
  828. texcommand = mpl.rcParams["pgf.texsystem"]
  829. with TemporaryDirectory() as tmpdir:
  830. tex_source = pathlib.Path(tmpdir, "pdf_pages.tex")
  831. tex_source.write_bytes(self._file.getvalue())
  832. cbook._check_and_log_subprocess(
  833. [texcommand, "-interaction=nonstopmode", "-halt-on-error",
  834. tex_source],
  835. _log, cwd=tmpdir)
  836. shutil.move(tex_source.with_suffix(".pdf"), self._output_name)
  837. def savefig(self, figure=None, **kwargs):
  838. """
  839. Save a `.Figure` to this file as a new page.
  840. Any other keyword arguments are passed to `~.Figure.savefig`.
  841. Parameters
  842. ----------
  843. figure : `.Figure` or int, default: the active figure
  844. The figure, or index of the figure, that is saved to the file.
  845. """
  846. if not isinstance(figure, Figure):
  847. if figure is None:
  848. manager = Gcf.get_active()
  849. else:
  850. manager = Gcf.get_fig_manager(figure)
  851. if manager is None:
  852. raise ValueError(f"No figure {figure}")
  853. figure = manager.canvas.figure
  854. with cbook._setattr_cm(figure, canvas=FigureCanvasPgf(figure)):
  855. width, height = figure.get_size_inches()
  856. if self._n_figures == 0:
  857. self._write_header(width, height)
  858. else:
  859. # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and
  860. # luatex<0.85; they were renamed to \pagewidth and \pageheight
  861. # on luatex>=0.85.
  862. self._file.write(
  863. (
  864. r'\newpage'
  865. r'\ifdefined\pdfpagewidth\pdfpagewidth'
  866. fr'\else\pagewidth\fi={width}in'
  867. r'\ifdefined\pdfpageheight\pdfpageheight'
  868. fr'\else\pageheight\fi={height}in'
  869. '%%\n'
  870. ).encode("ascii")
  871. )
  872. figure.savefig(self._file, format="pgf", **kwargs)
  873. self._n_figures += 1
  874. def get_pagecount(self):
  875. """Return the current number of pages in the multipage pdf file."""
  876. return self._n_figures