Skip to content

[Bug]: PGF file produces incorrect whitespace in the legend when using certain documentclass. #29978

@note286

Description

@note286

Bug summary

When using Matplotlib to generate PGF files with the IEEEtran document class, I noticed that if the legend font size is smaller than 5, extra whitespace appears on the right side. Currently, my workaround is to forcibly override the default article document class, which avoids this issue.

Would it be possible to provide an interface allowing users to directly modify the documentclass used by Matplotlib? Below is the reproducible code and a screenshot demonstrating the issue.

\documentclass{IEEEtran}
\usepackage{pgf}
\begin{document}
\input{main.pgf}
\end{document}

Overriding the default definition can resolve this issue.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pgf
matplotlib.backends.backend_pgf._DOCUMENTCLASS = r"\documentclass{IEEEtran}"
if __name__ == '__main__':
    matplotlib.rcParams['pgf.texsystem'] = 'pdflatex'
    fig, ax = plt.subplots(figsize=(2, 2),constrained_layout=True)
    ax.plot([1, 2, 3, 4, 5], [5, 5, 5, 5, 5], label='legend')
    ax.plot([1, 2, 3, 4, 5], [5, 5, 5, 5, 5], label='test legend')
    legend=ax.legend(fontsize=2)
    pfg_file = 'main.pgf'
    plt.savefig(pfg_file, transparent=True)
    plt.close()

Code for reproduction

import matplotlib
import matplotlib.pyplot as plt
if __name__ == '__main__':
    matplotlib.rcParams['pgf.texsystem'] = 'pdflatex'
    fig, ax = plt.subplots(figsize=(2, 2),constrained_layout=True)
    ax.plot([1, 2, 3, 4, 5], [5, 5, 5, 5, 5], label='legend')
    ax.plot([1, 2, 3, 4, 5], [5, 5, 5, 5, 5], label='test legend')
    legend=ax.legend(fontsize=2)
    pfg_file = 'main.pgf'
    plt.savefig(pfg_file, transparent=True)
    plt.close()

Actual outcome

Image

Expected outcome

Image

Additional information

No response

Operating system

No response

Matplotlib Version

3.10.0

Matplotlib Backend

No response

Python version

3.12.4

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions