backend_pgf.py 39 KB

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