Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Add support for pgf.documentclass rcParam #30063

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
Loading
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions 9 doc/users/next_whats_new/pgf-documentclass.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
PGF backend: new rcParam `pgf.documentclass`

Check warning on line 1 in doc/users/next_whats_new/pgf-documentclass.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/users/next_whats_new/pgf-documentclass.rst#L1

py:obj reference target not found: pgf.documentclass [ref.obj]
Raw output
doc/users/next_whats_new/pgf-documentclass.rst:1: WARNING: py:obj reference target not found: pgf.documentclass [ref.obj]
============================================

A new rcParam `pgf.documentclass` has been added to allow users to override

Check warning on line 4 in doc/users/next_whats_new/pgf-documentclass.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/users/next_whats_new/pgf-documentclass.rst#L4

py:obj reference target not found: pgf.documentclass [ref.obj]
Raw output
doc/users/next_whats_new/pgf-documentclass.rst:4: WARNING: py:obj reference target not found: pgf.documentclass [ref.obj]

Check warning on line 4 in doc/users/next_whats_new/pgf-documentclass.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/users/next_whats_new/pgf-documentclass.rst#L4

py:obj reference target not found: article [ref.obj]
Raw output
doc/users/next_whats_new/pgf-documentclass.rst:4: WARNING: py:obj reference target not found: article [ref.obj]
the default LaTeX document class (`article`) used by the PGF backend.

This enables better compatibility when including PGF figures in documents that

Check warning on line 7 in doc/users/next_whats_new/pgf-documentclass.rst

View workflow job for this annotation

GitHub Actions / sphinx

[sphinx] doc/users/next_whats_new/pgf-documentclass.rst#L7

py:obj reference target not found: IEEEtran [ref.obj]
Raw output
doc/users/next_whats_new/pgf-documentclass.rst:7: WARNING: py:obj reference target not found: IEEEtran [ref.obj]
use custom LaTeX classes like `IEEEtran` or others, avoiding layout
issues like incorrect font sizes or spacing mismatches.
13 changes: 13 additions & 0 deletions 13 galleries/users_explain/text/pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
pgf.preamble Lines to be included in the LaTeX preamble
pgf.rcfonts Setup fonts from rc params using the fontspec package
pgf.texsystem Either "xelatex" (default), "lualatex" or "pdflatex"
pgf.documentclass The LaTeX document class to use (e.g., "article", "IEEEtran")
================= =====================================================

.. note::
Expand Down Expand Up @@ -144,6 +145,7 @@
if you want to do the font configuration yourself instead of using the fonts
specified in the rc parameters, make sure to disable :rc:`pgf.rcfonts`.


.. code-block:: python

import matplotlib as mpl
Expand All @@ -170,6 +172,17 @@
ax.set_ylabel(r"\url{https://matplotlib.org}")
ax.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"])

You can also change the LaTeX document class used when generating PGF figures.
By default, Matplotlib uses ``article``, but you can override this using
the ``pgf.documentclass`` rcParam::

import matplotlib.pyplot as plt
plt.rcParams["pgf.documentclass"] = "IEEEtran"

This is useful when including PGF figures into LaTeX documents using
custom classes such as ``IEEEtran``, to avoid layout
mismatches in font size or spacing.

.. redirect-from:: /gallery/userdemo/pgf_texsystem

.. _pgf-texsystem:
Expand Down
1 change: 1 addition & 0 deletions 1 lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,7 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
# Strip leading comment.
transform=lambda line: line[1:] if line.startswith("#") else line,
fail_on_error=True)
rcParamsDefault["pgf.documentclass"] = "article"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
rcParamsDefault._ensure_has_backend()

Expand Down
10 changes: 4 additions & 6 deletions 10 lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@
_log = logging.getLogger(__name__)


_DOCUMENTCLASS = r"\documentclass{article}"


# Note: When formatting floating point values, it is important to use the
# %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
# which is not recognized by TeX.
Expand Down Expand Up @@ -205,7 +202,7 @@ class LatexManager:
@staticmethod
def _build_latex_header():
latex_header = [
_DOCUMENTCLASS,
rf"\documentclass{{{mpl.rcParams.get('pgf.documentclass', 'article')}}}",
# Include TeX program name as a comment for cache invalidation.
# TeX does not allow this to be the first line.
rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",
Expand Down Expand Up @@ -834,7 +831,8 @@ def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
self.print_pgf(tmppath / "figure.pgf", **kwargs)
(tmppath / "figure.tex").write_text(
"\n".join([
_DOCUMENTCLASS,
rf"\documentclass{{{mpl.rcParams.get(
'pgf.documentclass', 'article')}}}",
r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
% (w, h),
Expand Down Expand Up @@ -931,7 +929,7 @@ def _write_header(self, width_inches, height_inches):
pdfinfo = ','.join(
_metadata_to_str(k, v) for k, v in self._info_dict.items())
latex_header = "\n".join([
_DOCUMENTCLASS,
rf"\documentclass{{{mpl.rcParams.get('pgf.documentclass', 'article')}}}",
r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
% (width_inches, height_inches),
Expand Down
1 change: 1 addition & 0 deletions 1 lib/matplotlib/mpl-data/matplotlibrc
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,7 @@
#pgf.rcfonts: True
#pgf.preamble: # See text.latex.preamble for documentation
#pgf.texsystem: xelatex
#pgf.documentclass: article

### docstring params
#docstring.hardcopy: False # set this when you want to generate hardcopy docstring
Expand Down
1 change: 1 addition & 0 deletions 1 lib/matplotlib/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -1336,6 +1336,7 @@ def _convert_validator_spec(key, conv):
"pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
"pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
"pgf.preamble": validate_string, # custom LaTeX preamble
"pgf.documentclass": validate_string, # LaTeX document class used by PGF backend

# write raster image data into the svg file
"svg.image_inline": validate_bool,
Expand Down
9 changes: 9 additions & 0 deletions 9 lib/matplotlib/tests/test_backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,3 +400,12 @@ def test_document_font_size():
label=r'\normalsize the document font size is \the\fontdimen6\font'
)
plt.legend()


@pytest.mark.backend("pgf")
def test_pgf_documentclass_written():
from matplotlib.backends.backend_pgf import LatexManager

mpl.rcParams["pgf.documentclass"] = "IEEEtran"
header = LatexManager._build_latex_header()
assert r"\documentclass{IEEEtran}" in header
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.